Question regarding naming convention
Hans Nowak
zephyr01 at alltel.net
Wed Jul 2 22:58:30 EDT 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 c.l.py 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 MyClass.py ?
>
> 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.
Cheers,
More information about the Python-list
mailing list