Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is there a Python counterpart for Java's class.forName('xxx')?

Status
Not open for further replies.

lyphard

Programmer
Jan 14, 2004
9
CA
Hello,

If I want to create an instance of a class from a string, in Java I can use class.forName() to achieve it. How can I do it in Python?

Thanks.

-Kevin
 
There may be an easier way, but you can write a simple function to traverse the namespaces to do it. Here's an example:

myclass.py:
Code:
class first:
    def identify( self ):
        print "first"
simple enough...

if you wanted to use that you'd do:
Code:
import myclass

inst = myclass.first()
inst.identify()
Which would yield:
first

Now we simulate the ridiculous java class heirarchies...
indirection.py:
Code:
import myclass
elementary

use it:
Code:
import indirection

inst = indirection.myclass.first()
inst.identify()
now we're starting to look like Java:
first

Now try this:
Code:
import indirection

classname = "indirection.myclass.first"

def forName( fullname ):
    # I wish I didn't have to treat the top level
    # differently, maybe someone more familiar 
    # with namespaces could normalize this
    parts = fullname.split( "." )
    object = globals()[ parts[0] ]

    # Now that we have a module...
    for part in parts[1:]:
        object = getattr( object, part )

    # we've got it, so instantiate it
    return object()

# find it...
instance = forName( classname )
# prove it...
instance.identify()
And... tada!!!
first

It could use some more robust error checking, but that's be basic idea. Or you could leave it as it is and when you pass it an invalid class name and it would just throw a huge ugly traceback and die... just like Java!

Which goes full circle back to what I tell all my Java weenie friends about most things they don't understand: It ain't f***ing magic

However, this just absolutely screams to be asked: why on earth would you ever need to do this? I've been writing code for almost twenty years and I've *never* had the need to instantiate an object from its name. The only reason I even bothered figuring this out was as a purely academic exercise. And boredom.

Notice: The above code is copyright me, but released under the terms of the Gnu Public License ( for your use. (You think I'm joking, but I'm not).
 
Thank you very much for the post.

The reason why I asked was that I'm writing a program which involves file parsing, and there're different types of files so for each file format I write a parser class, and I want the user to specify which class they'd like to use in run time by passing in a class name or specifying it in a configuration file or so.
 
After thinking about it last night, I figured that was probably the case.

You'll have to do some validation on the class name, plus you'll probably want to do some type checking in the for loop as you're walking the modules. Either that or maintain a list of valid classes and just give labels to each of them and handle them case by case.

Hope it helps.
 
I also asked the question to python-help at the same time and they provided some helpful comments I'd like to share. Dont bash me if you already knew :)

Code:
>>> class A: pass
... 
>>> s = "A"
>>> b = eval(s)()
>>> b
<__main__.A instance at 0x01435FD0>
>>>
 
Actually, that's good to know. It was interesting delving into the internals, always good to learn something new.
 
Why not just build yourself a dictionary that maps file type to class? Then you don't have to expose your parser class names.

Code:
# map strings to corresponding classes
parserClassMap = {
    "FileType1" : File1Parser,
    "FileType2" : File2Parser,
    }
fileType = raw_input("Type of file:")
if fileType in parserClassMap:
    # invoke constructor
    parser = parserClassMap[ fileType ]()
else:
    print "unrecognized file type"

Also, if you are writing file parsers, please let me recommend that you take a look at pyparsing. I've used it for parsing many types of input files, including some especially tricky ones (variable structures, tabular data, source code, etc.). Download pyparsing at
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top