0

There are two py files. util.py

def add_sum():
    print(x + 3)

test.py

from util import *
x=3
add_sum()

When I run test.py, I get error:

Traceback (most recent call last):
File "test.py", line 45, in <module>
    add_sum()
File "util.py", line 10, in add_sum
    print(x + 3)
NameError: name 'x' is not defined

The variable x is global, why function cannot reach x and raise error?

6
  • Because its global within your file Commented Mar 12, 2020 at 8:16
  • 3
    Does this answer your question? Python importing variables from other file Commented Mar 12, 2020 at 8:17
  • 2
    Why is test.py importing itself? Commented Mar 12, 2020 at 8:19
  • @martineau already edited. Commented Mar 12, 2020 at 8:26
  • @ThomasSchillaci there are som differences. I can unterstand the Python importing variables from other file . really to know is after import, the add_sum function is not just like define in new file test? Commented Mar 12, 2020 at 8:38

1 Answer 1

2

Python's "globals" are only globals to the module they are defined in. That's by design - you should only use globals when you really can't avoid them, as it makes the code harder to understand, test and maintain.

In your case, the proper way is to explicitely pass x to your function:

 # util.py
 def add_sum(x):
     return x + 3

And

# test.py
# NB: star imports are evil too, for the very same reasons
from util import add_sum
x=3
print(add_sum(x))
Sign up to request clarification or add additional context in comments.

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.