close

How to use a variable as function name in Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to use a variable as function name in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to use a variable as function name in Python?

  1. How to use a variable as function name in Python?

    You can't define a function using a variable but you can rebind the function to the variable name. Here is an example to add them to the module's global namespace.

  2. use a variable as function name in Python

    You can't define a function using a variable but you can rebind the function to the variable name. Here is an example to add them to the module's global namespace.

Method 1

You can’t define a function using a variable but you can rebind the function to the variable name. Here is an example to add them to the module’s global namespace.

one = 'one'
two = 'two'
three = 'three'
l = [one, two, three]
def some_stuff():
    print("i am sure some stuff")
for item in l:
    def _f():
        some_stuff()
    globals()[item] = _f
    del _f

one()
two()
three()

Method 2

Functions in Python are objects that have a name referencing them, so you can pass them around, store in lists and dictionaries (common use when creating jump-tables).

I.e. this works:

   def one():
        print "1"

    def two():
        print "2"

    def three():
        print "3"

    l = [one, two, three]

    for item in l:
        item()

Will print:

1
2
3

Don’t use list as variable name, because this way you redefine buildin.

def is the statement that is also executed, unlike function defenitions in compiled languages. So when you call def item(): you don’t define function for onetwothree, but redefine item name.

In general it is not quite clear what you’re trying to do, but it doesn’t look like a good idea. May be explain what you try to accomplish, or rethink the way you want to do it.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read