On Apr 19, 2005, at 21:22, Tim Johnson wrote:
Hello Pythonmeisters:
Is it possible to dynamically compose a module name for import?
Pointers to documentation or other discussions would be sufficient at this time.
thanks
Ah, metaprogramming. I must admit I can't think of a way. Or rather, I did think of a few but they don't work:
- module isn't a built-in (yet importing a module and calling type on it returns <type 'module'>).
- eval("import os") raises a SyntaxError.
However, the __import__ built-in function seems promising, although I have trouble seeing how it is used. Witness:
>>> __import__("os")
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/os.pyc'>
>>> dir()
['__builtins__', '__doc__', '__name__']
>>>
>>> __import__("sys").version_info (2, 3, 0, 'final', 0)
So calling the function returns the module as an object, but it is not imported in the usual sense of the word. But you can use functions from it...
Oh, wait, I get it. It's so obvious I wonder why I didn't see it before.
>>> sys = __import__("sys") >>> sys.version_info (2, 3, 0, 'final', 0)
There you are. So yes, it can be done, and quite easily at that (although not as easily as in Ruby, IIRC, whose metaprogramming features truly frightened me last time I had a look at it).
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?"
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor