Import by filename with __import__ ?
Today I stumbled about an unknown and undocumented (?) feature. At least it's not documented in our docs. __import__ can import a module by file name:
open("/tmp/example.py", "w").write("test = 23\n") mod = __import__("/tmp/example") mod <module '/tmp/example' from '/tmp/example.py'> mod.__name__ '/tmp/example' mod.__file__ '/tmp/example.py' mod.test 23
Is it just a coincidence? Is it a desired feature? Why isn't it documented? Christian
Sounds like a coincidence. Looks like it's using os.path.join(X, name + ".py") where X is a member of sys.path, e.g. the initial ".". This gives good results for valid module names (which never contain slashes) but in this example, os.path.join() ignores the first component if the second starts with '/'. Feel free to add a check that the module name doesn't contain '/', '\\' or '.'. (I think that silently accepting other non-identifier characters is fine, since it doesn't interfere with parsing either the module name or the filename.) On Jan 8, 2008 9:09 PM, Christian Heimes <lists@cheimes.de> wrote:
Today I stumbled about an unknown and undocumented (?) feature. At least it's not documented in our docs. __import__ can import a module by file name:
open("/tmp/example.py", "w").write("test = 23\n") mod = __import__("/tmp/example") mod <module '/tmp/example' from '/tmp/example.py'> mod.__name__ '/tmp/example' mod.__file__ '/tmp/example.py' mod.test 23
Is it just a coincidence? Is it a desired feature? Why isn't it documented?
Christian
_______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (home page: http://www.python.org/~guido/)
participants (2)
-
Christian Heimes -
Guido van Rossum