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.
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:
As other commenters have pointed out, not using globals is probably a better option.