ToolChimp
ToolChimp

Reputation: 1

How to access a global variable in a function?

I have a module in which there is a function that takes an input, processes it, then returns an output. When I call this module's function it appears to work, but I am unable to access the 'result' variable from the main program.

file_a.py:

result = False
def test(incoming):
    if incoming > 3:
        result = True
    else:
        result = False
    print(result)
    return result

file_b.py:

import file_a
for i in range(5):
    file_a.test(i)
    print(i, file_a.result)

interrogating result from within test() produces the desired result (i.e. it changes to True when expected), but from the main loop file_a.result is always False.

Upvotes: 0

Views: 148

Answers (3)

Joe
Joe

Reputation: 2437

The answer you are looking for is to use global result inside the method in file_a, to tell python that you mean the global one. However, this only makes it work for your code. I would say that your implementation is wrong (and dangerous).

In this scenario, why would you use not assign the variable during the function call? You are providing a return and never using it.

file_a.py

def test(incoming):
    if incoming > 3:
        result = True
    else:
        result = False
    print(result)
    return result

file_b.py

import file_a
for i in range(5):
    result = file_a.test(i)
    print(i, result)

There seems to be no reason to pollute global variable space. If you truly want this type of functionality, you should be using a class. As soon as you have two modules using this module, things could go really bad. You start using the results of someone else's call.

Also, your test is testing a Boolean to return the same value of that test. This is redundant and requires more brain power to parse than if you write it simpler:

def test(incoming):
    return incoming > 3

Upvotes: 0

Johnny Logan
Johnny Logan

Reputation: 21

You should have a look at global v. local namespaces in python, eg. this random site I found.

The main point is, you define a local variable 'results' in your function. Changing this will not change the outside (global) variable result. You can change this by telling the function that the variable 'result' is supposed to be the global one. Simply put 'global result' as the first line in the function.

result = False    
    def test(incoming):
    global result
    ...

That should fix it.

Upvotes: 1

Aiman Al-Eryani
Aiman Al-Eryani

Reputation: 709

What's happening is that the variable result inside the function is a version which only exists in this function's scope. Try declaring result as global, like so:

result = False
def test(incoming):
    global result # declare result as global 
    if incoming > 3:
        result = True
    else:
        result = False
    print(result)
    return result

Upvotes: 0

Related Questions