Dynamic creation of an object instance of a class by name

John Roth newsgroups at jhrothjr.com
Wed Apr 7 19:57:26 EDT 2004


"Andre Meyer" <meyer at acm.org> wrote in message
news:mailman.435.1081378579.20120.python-list at python.org...
> Right, ok, well, I do not assume to know what classes can be instantiated,
thus
> anything like accessing globals() is not likely to help, sorry. The eval()
> version works pretty ok so far. I am develpoing a module of which other
people
> can make use of by developing their own subclasses, but they need to be
> instantiated by my code. Eval() does the trick for me or is there a better
way,
> assuming you do not need to know which class it might be beforehand?
> btw I LOVE dynamicity... ;-)
>
> kind regards
> Andre

As long as you know where the class is (and I presume you do,
since eval() is working), you can use getattr() to find the class,
and then instantiate it the usual way. It's a good deal faster.

The thing to remember is that eval() is not magic: it still needs
to find the class you're referencing by the usual lookup path.

For example, if you know it's in the current module, you
could say:

obj = getattr(globals(), "theClass")()

If it's in another module, then the incantation
becomes:

obj = getattr(module, "theClass")()

The moral of the story is that you do have to know where
the class object resides.

John Roth
>
>





More information about the Python-list mailing list