3

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?

asked Oct 11, 2018 at 14:53

2 Answers 2

3

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
answered Oct 11, 2018 at 14:55
Sign up to request clarification or add additional context in comments.

3 Comments

what if I wanted to do getattr('bar', "__call__")('bar') ? when I try to make the function referenced via a string I get AttributeError: 'str' object has no attribute '__call__' Is there any way to reference the name of that dynamically?
I just used a map, this works for my purposes methods = {'bar': bar} ; getattr(methods['bar']...
just call the locals() function, it returns a dictionary of objects from the local scope
3

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

def foo():
 def bar(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.

answered Oct 11, 2018 at 15:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.