Home > Back-end >  Is it possible to assign the local variable after calling a global function with the same name?
Is it possible to assign the local variable after calling a global function with the same name?

Time:02-14

Suppose I have defined a function foo:

def foo():
    print('hi')
    return np.array([1,2,3])

I want to use the result it provides inside another function called 'execute', and assign that result to local variable having the same name 'foo':

def execute():
    foo = foo()
    foo -= 1
    print(foo)

execute()

The above will result in "local variable 'foo' referenced before assignment".

Now if I use global inside my execute function:

def execute():
    global foo
    foo = foo()
    ...

It will work but after calling it once it will rewrite the global function, which isn't what we want.

CodePudding user response:

In this example, it would perhaps be best to rename the function to get_foo() or make_foo() or generate_foo(), to disambiguate from the object foo it returns.

CodePudding user response:

You could use globals() directly:

def execute():
    foo = globals()["foo"]()
    foo -= 1
    print(foo)

But really I think you should avoid the name conflict in the first place, which would be less confusing to readers:

def execute():
    foo_result = foo()
    foo_result -= 1
    print(foo_result)
  • Related