0

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?

1
  • You haven't defined x anywhere... I guess you.meany x = 2? In any case, that would not create x in main.py Commented Oct 17, 2021 at 16:31

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Greatly appreciated and well explained! That fixed it :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.