0

I am having hard time trying to move variable around two files.

At first it is defined in file1.py. The function using this variable is stored in file2.py. In the end the function is called in file1.py.

As you can see the final result is NameError. What am I doing wrong?

# file1.py

from file2 import myFunct

x = 1
myFunct()

# file2.py

def myFunct():
    test = f'some string {x} some string'
    print(test)

# NameError: name 'x' is not defined
Krzysztof
  • 11
  • 1
  • 3
    Local (or even global) variables are not magically transferred to the scope of imported files/functions. Just pass the variable to the function: `myFunct(x) ... def myFunct(x):` And no, the variable does not need to be called `x` in both palces – DeepSpace Nov 26 '21 at 23:21
  • 2
    Think about it: If this worked, you would have libraries that only worked if you had specially-named variables in the namespace you imported them into! That would be an awful mess, and it's better that the language doesn't allow it. When you refer to the global variable `x` in a module named `file2`, it's _file2's_ `x` that is referred to, no matter where you reference a function doing that reference from. Since file2 has no `x` in your example, you get the NameError. – Charles Duffy Nov 26 '21 at 23:23

0 Answers0