gr56
gr56

Reputation: 101

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

Upvotes: 10

Views: 24939

Answers (5)

John Carr
John Carr

Reputation: 87

What Samir said works for Python 2

For python 3 you need to do it this way.

main.py

import irc
from irc import func

var = 1
func(var)
irc.py

irc.py

def func(var):
    print(var)

Upvotes: 0

Kabie
Kabie

Reputation: 10673

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

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Two options.

from main import var

def func():
    print var

This will copy a reference to the original name to the importing module.

import main

def func():
    print main.var

This will let you use the variable from the other module, and allow you to change it if desired.

Upvotes: 4

tlunter
tlunter

Reputation: 724

Well, var in the function isn't declared. You could pass it as an argument. main.py

import irc
var = 1
func(var)

irc.py

def func(str):
    print str

Upvotes: 0

Samir Talwar
Samir Talwar

Reputation: 14330

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

Upvotes: 11

Related Questions