Search code examples
pythonvariablesassign

python: assign value to a variable whose name is stored in a variable


Maybe this question is very simple to answer, but after a long time of search in the internet I found badly no answer/workaround:

In Python (v3) I would like to do the following:

def func():
    pass

foo = "bar"

# Now I would like to make an assignment to a variable named
# based on the value of foo (i.e. effectively bar = func, but using foo)
# so that:
bar() == func()  # is True
bar is func  # is also True

How can I go about that? Thank you!


Solution

  • I am guessing what the question is, but are you looking for something like this:

    def func():
        pass
    
    foo = "bar"
    locals()[foo] = func
    
    bar() == func() # True
    # or better yet
    bar is func # also True