Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dynamic class names

Tags:

python

Trying to instantiate a class based on a string value and... failing. The parser object below is a dict, in the example let's say we have one called foo and here parser['name'] is 'foo':

obj = parser['name']()

Fails, yielding TypeError: 'str' object is not callable. But, since I have:

class foo:
    def __init__(self():
        print 'Hello'

And if I do obj = foo() it works fine and creates the correct object. Also, calling obj = type(parser['name'])() doesn't work.

How to resolve this? Update: I don't really want to use a mapping system: the names of these classes are defined INI files, and parsed that way, so they will be strings..

like image 684
Wells Avatar asked Dec 22 '10 20:12

Wells


People also ask

How do you create a dynamic class in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

How do you change a class name in Python?

Just set __name__ and __qualname__ to your new name. You should set both attributes, since you cannot be sure at which one 3rd-party code will look. If you want to change Outer 's name, you need to patch three places, namely Outer.

Can a class name be a variable Python?

there are no variables in python, just names. In one recent case, I implemented two different subclasses of a class. They had similar different implementations for the same general work, and they had roughly the same API.

What is class type '> in Python?

In general, the type of any new-style class is type . type is a metaclass, of which classes are instances. Just as an ordinary object is an instance of a class, any new-style class in Python, and thus any class in Python 3, is an instance of the type metaclass.


3 Answers

As answered in:
Python dynamic class names

There is an easier way to do this if you know which module the classes are defined in, for example:

getattr(my_module, my_class_name)()
like image 62
laurentoget Avatar answered Oct 12 '22 21:10

laurentoget


classmap = {
  'foo': foo
}

obj = classmap[parser['name']]()
like image 44
Ignacio Vazquez-Abrams Avatar answered Oct 12 '22 19:10

Ignacio Vazquez-Abrams


The type(name, bases, dict) built-in function is the correct way to dynamically construct classes--especially when given strings for class names. See the documentation here: http://docs.python.org/library/functions.html#type

In you particular example, it might look like this:

>>> def init(self):
...     print 'Hello'
...
>>> Foo = type('Foo', (object,), {'__init__': init})
>>> foo = Foo()
Hello
like image 41
Brian Riley Avatar answered Oct 12 '22 19:10

Brian Riley