Rilwan
Rilwan

Reputation: 2301

How to access a variable in a module which is being imported in the main function and which is defined inside main() in python

I am a newbie to python.I am trying to access a variable defined inside main() in a module which is being imported in the main function. I want a method to get this withput passing the deviceid variable to get_a()
main.py:-

global deviceid
import lib
deviceid=123
lib.get_a()

lib.py:-

def get_a():
    global deviceid
    prnit deviceid  

calling main or trying to access deviceid from python shell is returning

Traceback (most recent call last): File "<stdin>", line 1, in <module> File "t.py", line 4, in pp print a NameError: global name 'deviceid' is not defined

I tried giving global deviceid in many places inside and outside module and function.Nothing helps.

somebody please help.

Upvotes: 0

Views: 254

Answers (2)

Ned Batchelder
Ned Batchelder

Reputation: 375574

There are no names in Python that are global to the entire program. Globals in Python are global to a particular module. To use a value in more than one module, you import its name from one module to another, making it available in two modules:

# main.py
import lib
deviceid = 123
lib.get_a()

# lib.py
import main
def get_a():
    print main.deviceid

As other commenters have pointed out, not using globals is probably a better option.

# main.py
import lib
deviceid = 123
lib.get_a(deviceid)

# lib.py
def get_a(deviceid):
    print deviceid

Upvotes: 2

nathan
nathan

Reputation: 1119

You can put the deviceid variable in the lib module and use it via lib.deviceid

If you change the value of deviceid somewhere in your code by doing lib.deviceid = X, and if you reimport the lib module somewhere else and you request the deviceid again, it will have X as value.

Upvotes: 0

Related Questions