bitteneite
bitteneite

Reputation: 1

Python - How do I return a variable defined from an imported python function?

I've recreated this error in a simpler file.

main.py

from funcA import *

test()
print(x)

funcA.py

def test():
    global x
    y = 2
    return x

I receive "NameError: name 'x' is not defined", what am I missing?

Upvotes: 0

Views: 61

Answers (2)

chepner
chepner

Reputation: 531798

from funcA import * creates a new variable named x in the global scope of main.py. Its initial value comes from funcA.x, but it is a distinct variable that isn't linked to funcA.x.

When you call test, you update the value of funcA.x, but main.x remains unchanged.

After you call test, you can see the change by looking at funcA.x directly.

from funcA import *
import funcA


test()
print(funcA.x)

Upvotes: 1

user15256253
user15256253

Reputation:

You have to create a global variable outside the function.
The global keyword cannot be used like that.
There's must be x outside the function.

# funcA.py
x = "something"

def test():
    global x
    y = 2
    return x

Upvotes: 0

Related Questions