【问题标题】:Calling a function of a module by using its name (a string)使用模块名称(字符串)调用模块的函数
【发布时间】:2010-09-05 09:46:59
【问题描述】:

在 Python 程序中给定一个带有函数名称的字符串,调用函数的最佳方法是什么。例如,假设我有一个模块foo,我有一个内容为"bar" 的字符串。拨打foo.bar() 的最佳方式是什么?

我需要获取函数的返回值,这就是为什么我不只使用eval。我想出了如何通过使用eval 定义一个返回该函数调用结果的临时函数来做到这一点,但我希望有一种更优雅的方法来做到这一点。

【问题讨论】:

  • 使用 eval 可能会带来一些安全问题!
  • 仅供参考:通过动态名称访问字段、类和方法的语言特性称为reflection。可能会使将来的搜索更容易。

标签: python object


【解决方案1】:

假设模块foo 使用方法bar

import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()

您可以将第 2 行和第 3 行缩短为:

result = getattr(foo, 'bar')()

如果这对您的用例更有意义。

您可以以这种方式在类实例绑定方法、模块级方法、类方法上使用getattr...不胜枚举。

【讨论】:

  • hasattr 或 getattr 可用于确定是否定义了函数。我有一个数据库映射(eventType 和处理函数名称),我想确保我永远不会“忘记”在我的 python 中定义一个事件处理程序
  • 如果您已经知道模块名称,则此方法有效。但是,如果您希望用户以字符串形式提供模块名称,这将不起作用。
  • 如果您需要避免 NoneType is not callable 异常,您还可以使用 getattr 的三参数形式:getattr(foo, 'bar', lambda: None)。我为格式道歉; stackexchange android 应用程序显然很糟糕。
  • 如果您只关心本地/当前模块的功能,另请参阅@sastinin 提供的答案。
  • @akki 是的,如果你 foo 模块,你可以使用globals() 来做到这一点:methodToCall = globals()['bar']
【解决方案2】:
locals()["myfunction"]()

globals()["myfunction"]()

locals 返回带有当前本地符号表的字典。 globals 返回带有全局符号表的字典。

【讨论】:

  • 如果您需要调用的方法是在您调用的同一模块中定义的,那么这种带有全局/局部变量的方法很好。
  • @Joelmob 还有其他方法可以通过字符串从根命名空间中获取对象吗?
  • @NickT 我只知道这些方法,我认为没有其他方法可以实现与这些相同的功能,至少我想不出应该有更多的原因。
  • 我给你一个理由(实际上是什么让我来到这里):模块 A 有一个函数 F,它需要按名称调用一个函数。模块 B 导入模块 A,并调用函数 F 并请求调用模块 B 中定义的函数 G。此调用失败,因为显然,函数 F 仅使用模块 F 中定义的全局变量运行 - 所以 globals() ['G'] = 无。
【解决方案3】:

Patrick 的解决方案可能是最干净的。 如果你还需要动态获取模块,你可以像这样导入它:

module = __import__('foo')
func = getattr(module, 'bar')
func()

【讨论】:

  • 我不明白最后的评论。 __import__ 有它自己的权利,在提到的文档中的下一句说:“直接使用 __import__() 是很少见的,除非你想导入一个名称只在运行时知道的模块”。所以:给定答案+1。
  • 使用importlib.import_module。官方文档对__import__ 说:“这是日常 Python 编程中不需要的高级函数,与 importlib.import_module() 不同。” docs.python.org/2/library/functions.html#__import__
  • @glarrain 只要你没问题,只支持 2.7 及更高版本。
  • @Xiong Chaimiov, importlib.import_module 在 3.6 中被支持。见docs.python.org/3.6/library/…
  • @cowlinator 是的,3.6 是“2.7 及更高版本”的一部分,无论是在严格的版本控制语义还是在发布日期(大约六年后)。在我发表评论后三年内它也不存在。 ;) 在 3.x 分支中,该模块自 3.1 以来一直存在。 2.7 和 3.1 现在已经很古老了;你仍然会发现只支持 2.6 的服务器,但现在可能值得将 importlib 作为标准建议。
【解决方案4】:

只是一个简单的贡献。如果我们需要实例化的类在同一个文件中,我们可以这样使用:

# Get class from globals and create an instance
m = globals()['our_class']()

# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')

# Call it
func()

例如:

class A:
    def __init__(self):
        pass

    def sampleFunc(self, arg):
        print('you called sampleFunc({})'.format(arg))

m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')

# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')

而且,如果不是一个类:

def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

globals()['sampleFunc']('sample arg')

【讨论】:

  • 如果在类函数中调用这个函数会怎样?
【解决方案5】:

给定一个字符串,一个函数的完整 python 路径,这就是我如何获取所述函数的结果:

import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()

【讨论】:

  • 这对我有帮助。它是__import__ 函数的轻量级版本。
  • 我认为这是最好的答案。
【解决方案6】:

根据Python programming FAQ 的最佳答案是:

functions = {'myfoo': foo.bar}

mystring = 'myfoo'
if mystring in functions:
    functions[mystring]()

这种技术的主要优点是字符串不需要匹配函数的名称。这也是用于模拟案例构造的主要技术

【讨论】:

    【解决方案7】:

    答案(我希望)没人想要

    类似评估的行为

    getattr(locals().get("foo") or globals().get("foo"), "bar")()
    

    为什么不添加自动导入

    getattr(
        locals().get("foo") or 
        globals().get("foo") or
        __import__("foo"), 
    "bar")()
    

    如果我们有额外的字典要检查

    getattr(next((x for x in (f("foo") for f in 
                              [locals().get, globals().get, 
                               self.__dict__.get, __import__]) 
                  if x)),
    "bar")()
    

    我们需要更深入

    getattr(next((x for x in (f("foo") for f in 
                  ([locals().get, globals().get, self.__dict__.get] +
                   [d.get for d in (list(dd.values()) for dd in 
                                    [locals(),globals(),self.__dict__]
                                    if isinstance(dd,dict))
                    if isinstance(d,dict)] + 
                   [__import__])) 
            if x)),
    "bar")()
    

    【讨论】:

    • 这可以通过递归扫描目录树和自动挂载 USB 驱动器来改善
    • 这绝对是我想要的答案。完美。
    【解决方案8】:

    对于它的价值,如果您需要将函数(或类)名称和应用程序名称作为字符串传递,那么您可以这样做:

    myFnName  = "MyFn"
    myAppName = "MyApp"
    app = sys.modules[myAppName]
    fn  = getattr(app,myFnName)
    

    【讨论】:

    • 更通用一点的是handler = getattr(sys.modules[__name__], myFnName)
    • 如果函数是类函数,它是如何工作的?
    【解决方案9】:

    试试这个。虽然这仍然使用 eval,但它仅使用它来从当前上下文中调用函数。然后,您就可以随意使用真正的功能了。

    这样做对我的主要好处是,在调用函数时,您将收到任何与 eval 相关的错误。然后你会在调用时得到函数相关的错误。

    def say_hello(name):
        print 'Hello {}!'.format(name)
    
    # get the function by name
    method_name = 'say_hello'
    method = eval(method_name)
    
    # call it like a regular function later
    args = ['friend']
    kwargs = {}
    method(*args, **kwargs)
    

    【讨论】:

    • 这会有风险。 string 可以包含任何内容,而 eval 最终会不加考虑地对其进行 eval-ling。
    • 当然,考虑到这些风险,您必须注意使用它的环境,无论这是否合适。
    • 一个函数不应该负责验证它的参数——这是另一个函数的工作。说对字符串使用 eval 是有风险的,就是说使用每个函数都是有风险的。
    • 除非绝对必要,否则永远不要使用eval。在这种情况下,getattr(__module__, method_name) 是一个更好的选择。
    【解决方案10】:

    任何建议都没有帮助我。不过我确实发现了这一点。

    <object>.__getattribute__(<string name>)(<params>)
    

    我正在使用 python 2.66

    希望对你有帮助

    【讨论】:

    • 这在哪些方面比 getattr() 更好?
    • 正是我想要的。奇迹般有效!完美的!! self.__getattribute__('title') 等于 self.title
    • self.__getattribute__('title') 毕竟在任何情况下都不起作用(不知道为什么),但 func = getattr(self, 'title'); func(); 起作用。所以,也许改用getattr() 会更好
    • 不懂python的人能不能别点赞这个垃圾了?请改用getattr
    【解决方案11】:

    由于此问题How to dynamically call methods within a class using method-name assignment to a variable [duplicate] 标记为与此问题重复,因此我在此处发布相关答案:

    场景是,一个类中的一个方法想要动态调用同一个类上的另一个方法,我在原始示例中添加了一些细节,提供了一些更广泛的场景和清晰度:

    class MyClass:
        def __init__(self, i):
            self.i = i
    
        def get(self):
            func = getattr(MyClass, 'function{}'.format(self.i))
            func(self, 12)   # This one will work
            # self.func(12)    # But this does NOT work.
    
    
        def function1(self, p1):
            print('function1: {}'.format(p1))
            # do other stuff
    
        def function2(self, p1):
            print('function2: {}'.format(p1))
            # do other stuff
    
    
    if __name__ == "__main__":
        class1 = MyClass(1)
        class1.get()
        class2 = MyClass(2)
        class2.get()
    

    输出(Python 3.7.x)

    函数1:12

    函数2:12

    【讨论】:

      【解决方案12】:

      虽然 getattr() 是优雅的(大约快 7 倍)方法,但您可以使用 eval 从函数(本地、类方法、模块)获取返回值,就像 x = eval('foo.bar')() 一样优雅。并且当您实现一些错误处理时,就会非常安全(相同的原理可以用于 getattr)。模块导入和类示例:

      # import module, call module function, pass parameters and print retured value with eval():
      import random
      bar = 'random.randint'
      randint = eval(bar)(0,100)
      print(randint) # will print random int from <0;100)
      
      # also class method returning (or not) value(s) can be used with eval: 
      class Say:
          def say(something='nothing'):
              return something
      
      bar = 'Say.say'
      print(eval(bar)('nice to meet you too')) # will print 'nice to meet you' 
      

      当模块或类不存在(拼写错误或其他更好的东西)时,会引发 NameError。当函数不存在时,会引发 AttributeError。这可用于处理错误:

      # try/except block can be used to catch both errors
      try:
          eval('Say.talk')() # raises AttributeError because function does not exist
          eval('Says.say')() # raises NameError because the class does not exist
          # or the same with getattr:
          getattr(Say, 'talk')() # raises AttributeError
          getattr(Says, 'say')() # raises NameError
      except AttributeError:
          # do domething or just...
          print('Function does not exist')
      except NameError:
          # do domething or just...
          print('Module does not exist')
      

      【讨论】:

        【解决方案13】:

        在python3中,可以使用__getattribute__方法。请参阅以下带有列表方法名称字符串的示例:

        func_name = 'reverse'
        
        l = [1, 2, 3, 4]
        print(l)
        >> [1, 2, 3, 4]
        
        l.__getattribute__(func_name)()
        print(l)
        >> [4, 3, 2, 1]
        

        【讨论】:

          【解决方案14】:

          getattr 从对象中按名称调用方法。 但是这个对象应该是调用类的父对象。 父类可以通过super(self.__class__, self)获取

          class Base:
              def call_base(func):
                  """This does not work"""
                  def new_func(self, *args, **kwargs):
                      name = func.__name__
                      getattr(super(self.__class__, self), name)(*args, **kwargs)
                  return new_func
          
              def f(self, *args):
                  print(f"BASE method invoked.")
          
              def g(self, *args):
                  print(f"BASE method invoked.")
          
          class Inherit(Base):
              @Base.call_base
              def f(self, *args):
                  """function body will be ignored by the decorator."""
                  pass
          
              @Base.call_base
              def g(self, *args):
                  """function body will be ignored by the decorator."""
                  pass
          
          Inherit().f() # The goal is to print "BASE method invoked."
          

          【讨论】:

            【解决方案15】:

            还没有人提到operator.attrgetter

            >>> from operator import attrgetter
            >>> l = [1, 2, 3]
            >>> attrgetter('reverse')(l)()
            >>> l
            [3, 2, 1]
            >>> 
            

            【讨论】:

              【解决方案16】:

              我之前也遇到过类似的问题,就是将字符串转换为函数。 但我不能使用eval()ast.literal_eval(),因为我不想立即执行此代码。

              例如我有一个字符串"foo.bar",我想将它作为函数名而不是字符串分配给x,这意味着我可以通过x()调用该函数ON DEMAND。。 p>

              这是我的代码:

              str_to_convert = "foo.bar"
              exec(f"x = {str_to_convert}")
              x()
              

              至于你的问题,你只需要在{}之前加上你的模块名称foo.如下:

              str_to_convert = "bar"
              exec(f"x = foo.{str_to_convert}")
              x()
              

              警告!!! eval()exec() 都是危险方法,请确认安全。 警告!!! eval()exec() 都是危险方法,请确认安全。 警告!!! eval()exec() 都是危险方法,请确认安全。

              【讨论】:

                【解决方案17】:

                您的意思是从模块中获取指向内部函数的指针

                import foo
                method = foo.bar
                executed = method(parameter)
                

                这不是一个更好的pythonic方式,对于准时的情况确实是可能的

                【讨论】:

                  【解决方案18】:

                  这是一个简单的答案,例如,这将允许您清除屏幕。下面有两个示例,使用 eval 和 exec,在清理后将在顶部打印 0(如果您使用的是 Windows,请将 clear 更改为 cls,例如 Linux 和 Mac 用户保持原样)或执行分别。

                  eval("os.system(\"clear\")")
                  exec("os.system(\"clear\")")
                  

                  【讨论】:

                  • 这不是 op 要求的。
                  • 这段代码 sn-p 包含最严重的 2 个安全漏洞,嵌套。某种记录。
                  猜你喜欢
                  • 2010-09-05
                  • 1970-01-01
                  • 2019-11-21
                  • 2016-08-09
                  • 2019-04-22
                  • 1970-01-01
                  • 2017-07-24
                  • 2018-01-28
                  • 1970-01-01
                  相关资源
                  最近更新 更多