Ric*_*ico 1 python import string-interpolation
我有一长串需要导入的可能文件.我只需要其中一个,它们都有相同的界面.(选择付款网关处理付款)
假设我有一个代表所有网关文件名称的字典.
即
gateways = {
'1' : 'authorize',
'2' : 'paysimple',
'3' : 'braintreepayments',
'4' : 'etc',
}
Run Code Online (Sandbox Code Playgroud)
我根据数据库中的信息知道了这本词典的关键.因此,如果我收到网关值为1的付款流程请求,我知道它需要由Authorize.net处理.Pay 2将由Pay Simple处理.等等.
我希望能够创建一个使用我所知道的信息构建的import语句,而不是一个可怕的elif语句列表.
考虑下面的简单方法:
# For the purposes of this example assume payment_gateway is defined
# elsewhere and represents the key to the dictionary
gateway_file = gateways.get(payment_gateway)
import_str = "from gateway_interface.%s import process" % gateway_file
gogo(import_str)
Run Code Online (Sandbox Code Playgroud)
gogo导致import语句实际导入的方法在哪里.
这样的事情可能吗?
简单
process = __import__('gateway_interface.'+gateway_file,fromlist=['foo']).process
Run Code Online (Sandbox Code Playgroud)
编辑:fromlist中的'foo'可以是任何东西,只要fromlist不是空列表.为什么Python的__import__需要fromlist?中解释了一点点奇怪之处?.
我还必须编辑,因为在我的第一篇文章 __import__没有按预期工作,因为在Python的__import__中进一步描述不能按预期工作.
如果你有python 2.7
import importlib
process = importlib.import_module('gateway_interface.'+gateway_file).process
Run Code Online (Sandbox Code Playgroud)
WAAAAY酷将使用package_tools(例如from pkg_resources import iter_entry_points)
即使它们位于不在gateway_interface下的奇数包中,这也可以为您提供找到正确功能的解决方案.如果他们都在一个地方而且你不需要那些过度杀戮的点,那么......是的__import__