开发者

from ... import * with __import__ function [duplicate]

This que开发者_Go百科stion already has answers here: Closed 10 years ago.

Possible Duplicate:

from . import x using __import__?

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜