Python: how can I use a variable from the main file in a module?

I have 2 files main.py and irc.py.
main.py

import irc var = 1 func() 

irc.py

 def func(): print var 

When I try to run main.py, I get this error

NameError: global name 'var' not defined

How to make it work?

@Edit
I thought there was a better solution, but unfortunately the only thing I found was to make another file and import it into both files
main.py

 import irc import another another.var = 1 irc.func() 

irc.py

 import another def func(): print another.var 

another.py

 var = 0 
+7
source share
4 answers

not to do. Pass it on. Try to keep your code as free as possible: one module should not rely on the internal work of another. Instead, try to expose as little as possible. Thus, you protect yourself from the need to change the world every time you want everything to be a little different.

main.py

 import irc var = 1 func(var) 

irc.py

 def func(var): print var 
+10
source

Good thing my code is working fine:

func.py:

 import __main__ def func(): print(__main__.var) 

main.py:

 from func import func var="It works!" func() var="Now it changes!" func() 
+5
source

Two options.

 from main import var def func(): print var 

This will copy the link to the original name of the import module.

 import main def func(): print main.var 

This will allow you to use a variable from another module and let you change it if you wish.

+1
source

Well, var is not declared in a function. You can pass this as an argument. main.py

 import irc var = 1 func(var) 

irc.py

 def func(str): print str 
0
source

All Articles