Skip to content Skip to sidebar Skip to footer

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,

Solution 1:

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

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

i.e

deffoo():
  defbar(baz):
    print('used getattr to call', baz)
  getattr(bar, "__call__")('bar')

foo()

Output:

used getattr tocall bar

Solution 2:

alternatively, you can also use the locals() function which returns a dict of local symbols:

deffoo():
  defbar(baz):
    print('used getattr to call', baz)
  locals()['bar']('pouet')

foo()

It also allows you to get the function by its name instead of its reference without need for a custom mapping.

Post a Comment for "Can You Use Getattr To Call A Function Within Your Scope?"