0

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.

4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by woooee
0

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
>>>

Edited by snippsat: n/a

1

Pass x to the file2 function.

from file2 import *
x = 6
file2Funct(x)
##
##file2.py
##
def file2Function(x):
    print x
Votes + Comments
More proper usage advice
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.