Calling a function from string inside the same module in Python?

后端 未结 2 452
庸人自扰
庸人自扰 2020-12-16 14:11

Lets say I have a function bar inside a module called foo.py . Somewhere inside foo.py, I want to be able to call bar() from the string \"bar\". Ho

相关标签:
2条回答
  • 2020-12-16 14:44

    globals is probably easier to understand. It returns the current module's __dict__, so you could do:

    func_I_want = globals()['bar']  #Get the function
    func_I_want()    #call it
    

    If you really want the module object, you can get it from sys.modules (but you usually don't need it):

    import sys.modules
    this_mod = sys.modules[__name__]
    func = getattr(this_mod,'bar')
    func()
    

    Note that in general, you should ask yourself why you want to do this. This will allow any function to be called via a string -- which is probably user input... This can have potentially bad side effects if you accidentally give users access to the wrong functions.

    0 讨论(0)
  • 2020-12-16 14:46

    Use a dictionary that keeps the mapping of functions you want to call:

    if __name__ == '__main__':
      funcnames = {'bar': bar}
      funcnames['bar']()
    
    0 讨论(0)
提交回复
热议问题