Search code examples
pythongetattr

can you use getattr to call a function within your scope?


I'm trying to do something like this, but I can't figure out how to call the function bar.

def foo():
    def bar(baz):
        print('used getattr to call', baz)
    getattr(bar, __call__())('bar')

foo()

Notice, that this is somewhat unusual. Normally you'd have an object and get an attribute on that, which could be a function. then it's easy to run. but what if you just have a function within the current scope - how to do getattr on the current scope to run the function?


Solution

  • You are close. To use getattr, pass the string value of the name of the attribute:

    getattr(bar, "__call__")('bar')
    

    i.e

    def foo():
      def bar(baz):
        print('used getattr to call', baz)
      getattr(bar, "__call__")('bar')
    
    foo()
    

    Output:

    used getattr to call bar