[Zope3-Users] Convert from string to class

Gary Poster gary at zope.com
Tue Jan 17 17:26:07 EST 2006


On Jan 17, 2006, at 5:10 PM, Florian Lindner wrote:

> Hello,
> I've a string like "zope.app.folder.Folder" and I want to get the  
> class
> zope.app.folder.Folder from this string. How can I do that?
> It's probably more a python problem that Zope... but I hope you  
> excuse.

Was just rewriting this for myself, as a matter of fact--something I  
need now and then.  This is today's spelling:

 >>> def getImport(s):
...     try:
...         return __import__(s, globals(), {}, ['ignored'])
...     except ImportError:
...         elements = s.split('.')
...         last = elements.pop()
...         mod = '.'.join(elements)
...         mod_obj = __import__(mod, globals(), {}, [last])
...         return getattr(mod_obj, last)
...
 >>> getImport('xml.sax.saxutils.unescape')
<function unescape at 0x28b630>
 >>> getImport('xml.sax.saxutils')
<module 'xml.sax.saxutils' from '/Library/Frameworks/Python.framework/ 
Versions/2.4/lib/python2.4/xml/sax/saxutils.pyc'>

Could be refined a bit, but that's the idea.

Gary


More information about the Zope3-users mailing list