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.

file1.py

from file2 import *
x = 6
file2Funct()

file2.py

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 file2.py as follows,

def file2Function():
    global x
    print x

produces the same error, same point.

What am I missing here? Thanks.

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 file1.py 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.