Skip to main content
 首页 » 编程设计

python之使用变量 "interpolation"创建导入语句

2025年05月04日10arxive

我有一长串可能需要导入的文件。我将只需要其中的一个,它们都具有相同的界面。 (选择支付网关来处理支付)

假设我有一个代表所有网关文件名称的字典。

即

gateways = { 
   '1' : 'authorize', 
   '2' : 'paysimple', 
   '3' : 'braintreepayments', 
   '4' : 'etc', 
} 

我根据数据库中的信息知道这本字典的键。因此,如果我收到网关值为 1 的支付处理请求,我知道它需要由 Authorize.net 处理。 A 2 将由 Pay Simple 处理。等等

我希望能够创建一个导入语句,它是用我知道的信息构建的,而不是一个可怕的 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) 

gogo 是一种使导入语句实际导入的方法。

这样的事情可能吗?

请您参考如下方法:

最简单

process = __import__('gateway_interface.'+gateway_file,fromlist=['foo']).process 

编辑:发件人列表中的“foo”可以是任何内容,只要发件人列表不是空列表即可。 Why does Python's __import__ require fromlist? 中解释了这一点点奇怪之处。 .

我还必须进行编辑,因为在我的第一篇文章中,__import__ 没有像 Python's __import__ doesn't work as expected 中进一步描述的那样按预期工作。 .

如果你有 python 2.7

import importlib 
process = importlib.import_module('gateway_interface.'+gateway_file).process 

WAAAAY 很酷的方法是使用 package_tools(例如 from pkg_resources import iter_entry_points)

即使它们位于不在 gateway_interface 下的奇数包中,这也可以为您提供找到正确功能的解决方案。如果它们都在一个地方,而你不需要过度杀戮的 sytle-point 那么......是的只是 __import__