A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-list/2003-September/201208.html below:

How to instatiate a class of which the name is only known at runtime?

How to instatiate a class of which the name is only known at runtime? How to instatiate a class of which the name is only known at runtime?Nick Welch mack at incise.org
Tue Sep 9 15:45:08 EDT 2003
On Tue, Sep 09, 2003 at 09:35:30PM +0200, Marco Herrn wrote:
> I am writing a program that has to instantiate a class from which I
> don't know the name until runtime. That leads to two problems for me.
> 
> 1. How to do the import? I didn't find a way to give a string to the
>    import statement.

exec("import %s" % modulename) ?

> 2. How to write such code to instantiate?

class = getattr(modulename, classname)
or
class = globals()[classname]

and then:

an_instance = class()

Although this all seems really dirty to me.  Maybe there are better ways
to do it.

> Is it possible to say 'import * from subdirectory' ?

If the directory is a python package (has an __init__.py), then you can
do 'from directoryname import *'

-- 
Nick Welch aka mackstann | mack @ incise.org | http://incise.org
The one good thing about repeating your mistakes is that you know when
to cringe.



More information about the Python-list mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4