Question regarding naming convention

Hans Nowak zephyr01 at
Thu Jul 3 04:58:30 CEST 2003

michael wrote:

> Both of the above seem to overcomplicate the syntax. Of the two, I 
> prefer the second, but I'm sure I've read on that the 
> from..import.. version is not a preferred way of doing things.
> Is there no way to write a class, such that the statement:
>     import MyClass
> would dynamically import the MyClass class from ?
> It just surprises me that there isn't a neater way around this, as 
> Python seems to encapsulate most everything else in a simple way.

Not sure if this is what you're after, but:

 >>> def importobj(name):
	mod = __import__(name)
	obj = getattr(mod, name)
	globals()[name] = obj
# import the StringIO object from the StringIO module
 >>> importobj('StringIO')

# is it in the global namespace? yes:
 >>> dir()
['StringIO', '__builtins__', '__doc__', '__name__', 'importobj']

Putting something into globals() is a bit of a kludge, though.  You're probably 
better off using from x import x.


More information about the Python-list mailing list