-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. ?

  • 1
    What are you actually trying to achieve with this? It's likely an [XY problem](http://xyproblem.info). The `__name__` is just a label, it's not the same as doing `My_Function = func`. – jonrsharpe Jan 10 '18 at 08: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](https://stackoverflow.com/questions/11781265/python-using-getattr-to-call-function-with-variable-parameters) – Sohaib Farooqi Jan 10 '18 at 08: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. – mshsayem Jan 10 '18 at 08:45

2 Answers2

5

It will be much easier to use a dictionary:

def func():
    print('func')

func_dict = {"My_Function": func}

func_dict["My_Function"]()
# 'func'
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
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]()