Reputation:
I wanted to import a variable defined in function to another python file
e1.py
def abc():
global a
a=10
e2.py
import e1
def defi():
c=e1.abc.a
print(c)
defi()
I have searched but didn't get the right answer
Following is the error-
Traceback (most recent call last):
File "C:\Users\gkaur\Documents\MSO Editor Tool\e2.py", line 1, in <module>
from e1 import abc
File "C:\Users\gkaur\Documents\MSO Editor Tool\e1.py", line 2
global a
SyntaxError: name 'a' is parameter and global
Upvotes: 1
Views: 334
Reputation:
You are not using the function in file 1 correctly it should be:
def abc():
a = 10
return a
You should be returning the value. for the second file it should be:
import e1
def defi():
c = e1.abc()
print(c)
defi()
without the ()
at the end of e1.abc()
it doesn't actually tell the function to perform it's specific task.
Upvotes: 1
Reputation: 6478
Your variable a
is not defined until you call abc()
.
As you can see with dir(e1)
or help(e1)
in a repl, e1
does not have a variable a
, only a function abc
. Then after a call to abc()
, a
is here and set to 10.
>>> import e1
>>> dir(e1)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'abc']
>>> e1.abc()
>>> dir(e1)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a', 'abc']
>>> e1.a
10
Upvotes: 1
Reputation: 531205
a
is a module global variable in e1
. Other than being set in abc
, it is unrelated to that function; abc.a
is an error.
import e1
def defi():
c = e1.a
print(c)
# This should produce an error
defi()
However, unless you give a
a value in the global scope of e1
, it does not exist until you call abc
.
import e1
def defi():
c = e1.a
print c
e1.abc()
defi()
Upvotes: 1