Search code examples
pythonenvironment-variablesnameerror

Python: NameError: name 'myvar' is not defined, when importing a library


I'm trying to create a function within a library, to be called from the main script, where the variables are established

Main script (\project1\script.py):

from mylib.dosum import *
myvar = 10
print(dosum(1000))

\project1\mylib\dosum.py:

def dosum(x):
    global myvar
    valuetoreturn = x+myvar
    return valuetoreturn

However, I get the following error message

NameError                                 Traceback (most recent call last)
<ipython-input-2-5c2b1d2cc456> in <module>
      1 from mylib.dosum import *
      2 myvar = 10
----> 3 print(dosum(1000))

~\Python-scripts\project1\mylib\dosum.py in dosum(x)
      1 def dosum(x):
      2     global myvar
----> 3     valuetoreturn = x+myvar
      4     return valuetoreturn

NameError: name 'myvar' is not defined

Solution

  • Every module has its own global namespace. The myvar used by dosum is mylib.dosum.dusum; you are defining a new global in your script named myvar, not assigning to mylib.dosum.myvar.

    Do this instead:

    # Avoid "from ... import *"
    import mylib.dosum
    
    mylib.dosum.myvar = 10
    print(mylib.dosum.dosum(1000))