I really must have a general misunderstanding of import and global. I'm trying to call a function in an imported file and reference a variable.

from file2 import *
x = 6
file2Funct()

def file2Function():
    print x

executing file1 give the following error at the "print x" line in file2.py:
NameError: global name 'x' is not defined

If I change as follows,

def file2Function():
    global x
    print x

produces the same error, same point.

What am I missing here? Thanks.

Dani AI

Generated

The core issue is Python's module namespaces: a name you bind in file1 lives in file1's global namespace, while a function defined in file2 looks up globals inside file2. That is why assigning x in one file doesn't make it magically available inside another module's function. As pointed out, the name simply isn't defined where the function expects it.

Simplest, clearest fix (and best practice) is to pass the value explicitly. This keeps the function pure and avoids hidden dependencies:

# module_b.py
def show_value(val):
    print(val)

# caller.py
value = 6
show_value(value)

If you must share state across modules, import the module object (not from module import *) and store the shared name in a dedicated place. A small shared-config module keeps intent explicit and avoids surprising coupling:

# config.py
shared = 6

# mod.py
import config
def report():
    print(config.shared)

# main.py
import config, mod
config.shared = 42
mod.report()

Notes and troubleshooting tips:

  • from file2 import * copies names into the importer at import time and does not give you the file2 module object to mutate; use import file2 when you need to set file2.some_name.
  • A global declaration inside file2 refers to file2's globals, not file1's.
  • Prefer parameters/returns for testable, maintainable code. Use a module-level config or an object when shared mutable state is unavoidable, and use dir() or module.__dict__ to inspect what names a module actually defines.

Recommended Answers

All 3 Replies

You dont define x,so then it will of course not have an value.

>>> x

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    x
NameError: name 'x' is not defined
>>>

def file2Function():
    x = 5
    print x
    
file2Function()  #5
#file1.py
def file2Function():
    x = 5
    return 5


>>> import file1
>>> dir(file1)
['__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 'file2Function']
>>> print file1.file2Function()
5
>>>

To get it work you need of course change to say

import file2
file2.x = 6
file2.file2Funct()

Pass x to the file2 function.

from file2 import *
x = 6
file2Funct(x)
##
##file2.py
##
def file2Function(x):
    print x
commented: More proper usage advice +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.