Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Can you create a class from a string name

5 views
Skip to first unread message

Vivek Sawant

unread,
Mar 1, 2003, 3:45:31 PM3/1/03
to
Hi,

is there a way to create a class object or an instance object for a
class if you have the name of the class as a string at the runtime.

For example, in Java you can create a 'Class' object as:

Class.forname ('<classname>')

Thanks.

\vivek

Anna

unread,
Mar 1, 2003, 4:36:43 PM3/1/03
to

I don't know about Java.... But, from your question, it sounds like you're
asking about an object factory.

def factory(aClass, *args):
return apply(aClass,args)

so if you have a class Spam, that takes 2 args, during runtime, you can
tell it:

newobject=factory(Spam, arg1, arg2)

HTH
Anna

Mark McEahern

unread,
Mar 1, 2003, 4:21:38 PM3/1/03
to
[Vivek Sawant]

#!/usr/bin/env python

class Junk:

def __init__(self):
print "I am Junk"

s = 'Junk'

j = locals()[s]()

// m
-


Brian Quinlan

unread,
Feb 28, 2003, 4:58:22 PM2/28/03
to

class = eval('<classname>')
instance = eval('<classname>')(<constructor_args>)

Cheers,
Brian


Alex Martelli

unread,
Mar 1, 2003, 5:19:08 PM3/1/03
to
Anna wrote:
...

> def factory(aClass, *args):
> return apply(aClass,args)

Note that this needs aClass to be a class object, not a class name. And
in today's Python, apply's rather redundant -- the body of this factory
function might just as well be:

return aClass(*args)

since the * form can now be applied on calling, symmetrically to its
application in def (it expands any sequence of arguments). So you might
equally well define, in modern Python:

factory = aClass


Alex

Alex Martelli

unread,
Mar 1, 2003, 5:28:03 PM3/1/03
to
Vivek Sawant wrote:

In Python, what you load are *modules*, and classes (as well as
everything else) live in modules. This is somewhat different from the
Java approach where classes are "directly loaded".

So, to "load and access" a class from a name, in Python you need
two steps, and two names:

-- a module name, which you will use to load the module (or to
access it if it's already loaded);
-- a class name within the module.

def forname(modname, classname):
module = __import__(modname)
classobj = getattr(module, classname)
return classobj

Note that, while I've used "classname" and "classobj" here, this is
NOT at all limited to classes -- it will access just as well any module
attribute at all, be it a class, a function, a number, whatever.

In practice one might be less didactic and more concise and generic:

def forname(modname, attname):
return getattr(__import__(modname), attname)


Alex

Lenard Lindstrom

unread,
Mar 1, 2003, 7:23:46 PM3/1/03
to

"Vivek Sawant" <vivek-...@verizon.net> wrote in message
news:3E611ABE...@verizon.net...

> Hi,
>
> is there a way to create a class object or an instance object for a
> class if you have the name of the class as a string at the runtime.
>

You can use Python's dynamic execution features to do what you want. To
retrieve a reference to an existing class object use the built-in 'eval'
function.

classobj = eval('<classname>')

Create an instance of the class by calling the returned object.

classinstance = classobj(<constructor args>)

To define an entirely new class at run-time use the 'exec' statement. The
following example creates a minimal class, but the definition can be as
complicated as you need.

# Class name is defined by a string.
classname = 'mynewclass'

# The class definition is also a string. The '%s' will be replaced by the
class name later.
# When writing a compound statement as a string make sure the indentation
method
# is consistent, e.g. four spaces. See section 2.4.1 in Python Language
Manual
# for more on triple-quoted strings.
definition = """class %s:
pass
"""

# Execute the class definition statement. Insert the class name using a
# string formatting command '%' (section 2.2.6.2 in Python Library
Reference).
exec definition % classname

# Create an instance of the class.
newinstance = eval(classname)()

# This also works, but only when classname == 'mynewclass'.
newinstance = mynewclass()

> For example, in Java you can create a 'Class' object as:
>
> Class.forname ('<classname>')
>
> Thanks.
>
> \vivek
>

The Java Class.forName method returns a reference to an already existing
'Class' object. It does not create a new 'Class' object. It will not create
a new class at run time.

I hope this helps.

Lenard Lindstrom

Vivek Sawant

unread,
Mar 1, 2003, 7:58:16 PM3/1/03
to
Lenard,

Thanks!! That worked. I need the first method of creating class and object instances as I am not creating class definitions on the fly.

Another question though... To be able to use the method suggested by you (obj = eval ('<classname>'), I need to have already imported the class that I am trying to instantiate. Here's what I am really trying to do. I propose to support an applicaiton-specific configuration file which, along with other app-specific parameters, will also contain the names of the classes to be instantiated. This will enable the users of this application to use alternate implementations of a class by just changing the config file.

Given this, the '<classname>' string will come from this config file at the runtime. It would be nice, if the module that parses the config file does not have to know which all classes to import when I write the module.

I (naively) tried eval ('import <module>'). That produced syntax error :-(
Any suggestions?

\vivek

Vivek Sawant

unread,
Mar 1, 2003, 8:17:39 PM3/1/03
to
My apologies. Didn't notice the reply from Alex Martelli, which already answers the following question. Now, I am able to do entirely what I describe below using __import__ followed by class and object instantiation.

Thanks a lot to all who replied.

\vivek

Michael Ströder

unread,
Mar 2, 2003, 10:01:49 AM3/2/03
to
Lenard Lindstrom wrote:
>
> classobj = eval('<classname>')

For security reasons don't forget to check each input string for eval()
thoroughly.

Ciao, Michael.

0 new messages