from ... import * with __import__ function [duplicate]
Possible Duplicate:
from . import x
using__import__
? How does one do the equivalent ofimport * from module
with Python's__import__
function?
How would I do the from ... import * with the __import__
function?
The reason being that i only know the name of the file at runtime and it only has 1 class inside that file.
In case someone reading this wants an actual answer to the question in the title, you can do it by manipulating the vars()
dictionary. Yes, it is dumb to do this in most scenarios, but I can think of use cases where it would actually be really useful/cool (e.g. maybe you want a static module name, but want the contents of the module to come from somewhere else that's defined at runtime. Similar to and, IMO, better than the behavior of django.conf.settings
if you're familiar with it)
module_name = "foo"
for key, val in vars(__import__(module_name)).iteritems():
if key.startswith('__') and key.endswith('__'):
continue
vars()[key] = val
This imports every non-system variable in the module foo.py into the current namespace.
Use sparingly :)
Don't. Just don't. Do I need to explain just how horrible that it? Dynamically importing (though sometimes inevitable) and importing into global namespace (always avoidable, but sometimes the easier solution and fine withtrusted modules) are bad enough themselves. Dynamically importing into global namespace is... a nightmare (and avoidable).
Just do _temp = __import__(name, globals(), locals(), [name_of_class]); your_class = _temp.name_of_class
. According to the docs, this is about what from name import name_of_class would do.
精彩评论