turning a string into an object name

Mark McEahern marklists at mceahern.com
Wed Apr 3 22:46:37 EST 2002


[Marco Herrn]
> [...]what I want to achieve is turning a string into an object name.

Short answer:

Use a dictionary to store a mapping between strings and object names, like
this:

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

  dict = {'foo': foo}
  className = 'foo'
  # Avoid using class, since that's reserved.
  cls = dict.get(className, None)
  if cls:
    x = cls()

Longer answer:

Checkout the inspect module.

Cheers,

// mark






More information about the Python-list mailing list