turning a string into an object name

Mark McEahern marklists at mceahern.com
Wed Apr 3 23:50:18 EST 2002


Here's some sample code using inspect.  There are two files:

	factory.py
	classes.py

Run factory.py and watch the results.

Bad names, I know.  Oh well.  Here they are:

#! /usr/bin/env python

import inspect
import classes

def getClassByName(module, className):
    all = [x[1] for x in inspect.getmembers(module) if inspect.isclass(x[1])
and x[0] == className]
    if all:
        return all[0]
    else:
        return all

x = getClassByName(classes, "foo")
if x:
    x()

y = getClassByName(classes, "bar")
if y:
    y()

# classes.py
class foo:
  def __init__(self):
    print "Hi, I'm an instance of foo."

class bar:
  def __init__(self):
    print "Hi, I'm an instance of bar."







More information about the Python-list mailing list