from … import * with __import__ function [duplicat

2019-05-04 00:14发布

问题:

Possible Duplicate:
How does one do the equivalent of “import * 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.

回答1:

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.



回答2:

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 :)



标签: python import