Formatted string to object

Steven Bethard steven.bethard at gmail.com
Mon Jun 19 12:56:34 EDT 2006


janama wrote:
> can such a thing be done somehow?
> 
> aaa = self.aaa
> bbb = %s.%s % ('parent', 'bbb')
> 
> Can you use strings or %s strings like in the above or
> 
> aaa = 'string'
> aaa.%s() % 'upper'

Use the getattr() function::

     >>> class parent(object):
     ...     class bbb(object):
     ...         pass
     ...
     >>> module_ns = __import__(__name__)
     >>> getattr(getattr(module_ns, 'parent'), 'bbb')
     <class '__main__.bbb'>
     >>> import string
     >>> getattr(getattr(module_ns, 'string'), 'upper')
     <function upper at 0x00B502B0>

I've imported the module itself here so you can use getattr, but you 
could also use globals() instead of the inner getattr() call::

     >>> getattr(globals()['parent'], 'bbb')
     <class '__main__.bbb'>
     >>> getattr(globals()['string'], 'upper')
     <function upper at 0x00B502B0>

HTH,

STeVe



More information about the Python-list mailing list