-2

I have a function func :

def func(a):
    print a

func.__name_ = "My_Function"

To get the name of the function I will just do func.__name__. But is there a way to call func() by using its name i.e. "My_Function"?

Edit: There are going to be large number of functions for which this has to be done. Is there any better solution apart from keeping a mapping of function.name to the function. ?

3
  • 1
    What are you actually trying to achieve with this? It's likely an XY problem. The __name__ is just a label, it's not the same as doing My_Function = func. Commented Jan 10, 2018 at 8:40
  • If you have name of function and name of your module/class, you can use getattr to get function and invoke it. Have a look at this Question Commented Jan 10, 2018 at 8:43
  • 1
    If you are desperate: [f for _,f in locals().items() if callable(f) and f.__name__=='My_Function' ][0]('Hello'). Do try this at home, not in production. Use other option as Deepspace/johrsharpe suggested. Commented Jan 10, 2018 at 8:45

2 Answers 2

5

It will be much easier to use a dictionary:

def func():
    print('func')

func_dict = {"My_Function": func}

func_dict["My_Function"]()
# 'func'
Sign up to request clarification or add additional context in comments.

6 Comments

I think it should be func_dict[func.__name__]()?
@Laszlowaty No. This example never sets func.__name__.
@Laszlowaty: No, because, if func is already there why bother accessing it via func_dict?
Well you don't need to set func.__name__. But I think I didn't understand the question correctly, sorry :)
@Laszlowaty You can do func_dict = {func.__name__: func} ; func_dict[func.__name__]() but I don't see the point.
|
0

Assuming that you want to access functions that are defined in global scope (not part of any class/object):

def foo():
    print "foo"

def bar():
    print "bar"

foo.__name__ = "1"
bar.__name__ = "2"

# locals().items() will return the current local symbol table, which is an iterable and 
# it contains the globally defined functions.
symbol_table = locals().items()

# we will generate a list of functions that their __name__ == "1"
one_functions = [value for key, value in symbol_table if callable(value) and value.__name__ == "1"]

# now we can call the first item on the list - foo()
one_functions[0]()

Comments

Your Answer

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.