如何在 lambda 中导入 python 模块?

How to import a python module inside lambda?

假设根据变量我想导入一些 类,创建它的对象并 return 它。 例如:

if x=='SomeThing':
  import something
  object = something's object
else:
  import nothing
  object = nothing's object
object.function()

我想使用 lambda 执行上述操作,我该怎么做?

你可以使用魔法__import__:

importer = lambda x: (__import__("pandas").DataFrame if x == 0 
                      else __import__('numpy').arange)

注意:这非常丑陋,完全不推荐,除非你绝对需要这样做。

简单地无条件地导入两个模块几乎不是问题,select稍后使用哪个模块。

import something
import nothing

(something if x == 'SomeThing' else nothing).object.function()

如果您需要执行条件导入,导入一个或另一个,但使用相同名称。

if x == 'SomeThing':
    import something as thingmodule
else:
    import nothing as thingmodule

thingmodule.object.function()