[英]Is it possible to import a Python module (.py file) into a dict?
類似於以下內容:
在一個文件中:
FOO_CONST = 'bar'
def some_function(baz)
return do_something_with(baz)
from somewhere import something
blah = something()
在另一個文件中:
my_stuff = import_as_dict("module")
my_stuff
本質上等效於:
{
'FOO_CONST': 'bar',
'some_function': <function my_function at ...>,
'blah': 'I am the result of calling the function "somewhere.something".',
}
有沒有可以做到這一點的圖書館?
更新:
由於vars(module) == module.__dict__
我贊成兩個答案,但是接受了一個多一點的數據。 這是幾乎完全返回我所想的代碼:
my_stuff = {(key, var) for key, var in vars(module).items() if not key.startswith('__')}
使用vars
怎么樣?
import module
my_stuff = vars(module)
import module
my_stuff = module.__dict__
請注意,此字典是模塊用於保存其屬性的實際字典。 如果您執行my_stuff['foo'] = 3
,則module
具有等於3
的新foo
屬性。
如果只想通過在運行時確定的名稱來獲取屬性,則不需要dict。 你可以做
thing = getattr(module, thingname)
如果只關心訪問模塊成員的方式,則可以使用:
my_sys = import_as_dict("sys")
print my_os["sys"]
使用以下代碼:
import imp
class DictProxy(object):
def __init__(self, target):
super(DictProxy, self).__init__()
self.target = target
def __getitem__(self, key):
return getattr(self.target, key)
def __setitem__(self, key, value):
setattr(self.target, key, value)
def import_as_dict(module_name):
file_, pathname, description = imp.find_module(module_name)
module = imp.load_module(module_name, file_, pathname, description)
dict_module = DictProxy(module)
return dict_module
使用imp
進行導入將使您的全局上下文保持整潔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.