Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to assign the local variable after calling a global function with the same name?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

You could just use a temporary, intermediate variable:

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

Or 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading