使用变量"interpolation"创建导入语句. [英] Create an import statement using variable "interpolation"
问题描述
我有一长串可能需要导入的文件.我将只需要其中的1个,它们都具有相同的界面. (选择付款网关处理付款)
I have a long list of possible files I need to import. I will only ever need 1 of them and they all have the same interface. (Choosing a payment gateway to process a payment)
假设我有一个字典,代表所有网关文件的名称.
Suppose I have a dictionary that represents the name of all the gateway files.
即
gateways = {
'1' : 'authorize',
'2' : 'paysimple',
'3' : 'braintreepayments',
'4' : 'etc',
}
基于数据库中的信息,我知道该词典的关键字.因此,如果我收到网关值为1的付款过程请求,我知道它需要由Authorize.net处理. 2将由简单付款"处理.等等.
I know the keys to this dictionary based on information from a database. So, if I receive a payment process request with a gateway value of 1 I know it needs to be handled by Authorize.net. A 2 is to be processed by Pay Simple. Etc.
我希望能够创建一个导入语句,该导入语句是用我所知道的信息构建的,而不是一个可怕的elif
语句列表.
I'd like to be able to create an import statement that is built with the information I know rather than a horrible list of elif
statements.
考虑以下简单方法:
# 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)
gogo
是导致import语句实际导入的一种方式.
Where gogo
is a way to cause the import statement to actually import.
这有可能吗?
推荐答案
最简单
process = __import__('gateway_interface.'+gateway_file,fromlist=['foo']).process
编辑:只要fromlist不是空列表,fromlist中的'foo'可以是任何东西. 为什么Python的__import__需要fromlist?解释了一点奇怪.
EDIT: 'foo' in the fromlist can be anything, as long as fromlist is not an emptylist. That little bit of strangeness is explained in Why does Python's __import__ require fromlist?.
我还必须进行编辑,因为在我的第一篇文章__import__
中,它没有按预期工作,如
I also had to edit because in my first post __import__
didn't work as expected as further described in Python's __import__ doesn't work as expected.
如果您使用的是python 2.7
if you have python 2.7
import importlib
process = importlib.import_module('gateway_interface.'+gateway_file).process
WAAAAY很酷,那就是使用package_tools(例如from pkg_resources import iter_entry_points
)
WAAAAY cool would be to use package_tools (e.g. from pkg_resources import iter_entry_points
)
这可以为您提供一种找到正确功能的解决方案,即使它们是位于gateway_interface之下的奇特软件包中也是如此.如果它们都集中在一个地方,而您又不需要过分的控制点,那么...是的,只是__import__
That could give you a solution to find the right function even if they are in odd packages not under gateway_interface. If they are all on one place and you don't need the sytle-point that is overkill so ... yeah just __import__
这篇关于使用变量"interpolation"创建导入语句.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!