Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How can I use variable from main file in 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'm getting this error

NameError: global name 'var' is not defined

How to make it work?

@Edit
I thought there is a better solution but unfortunately the only one i found is to make another file and import it to 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
like image 991
gr56 Avatar asked May 15 '11 21:05

gr56


People also ask

How do you access variables from other classes in Python?

Variable defined inside the class: var_name. If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.

What is __ main __ file in Python?

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

Can Python modules have variables?

One of the strengths of Python is that there are many built-in add-ons - or modules - which contain existing functions, classes, and variables which allow you to do complex tasks in only a few lines of code.


2 Answers

Don't. Pass it in. Try and keep your code as decoupled as possible: one module should not rely on the inner workings of the other. Instead, try and expose as little as possible. In this way, you'll protect yourself from having to change the world every time you want to make things behave a little different.

main.py

import irc
var = 1
func(var)

irc.py

def func(var):
    print var
like image 173
Samir Talwar Avatar answered Nov 15 '22 20:11

Samir Talwar


Well, that's my code which works 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()
like image 38
Kabie Avatar answered Nov 15 '22 21:11

Kabie