Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access global variable within __main__ scope?

I'm confused about the namespace and scope of variables in python

Suppose I have a test.py:

# -*- coding: utf-8 -*-
"""
@author: jason
"""

if __name__ == '__main__':
    global strName
    print strName

and then, I define a variable named strName and try to access it in the test.py, but it throws an error:

In [9]: strName = "Joe"

In [10]: run test.py hello
---------------------------------------------------------------------------  NameError                              Traceback (most recent call last)  C:\Anaconda\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
    195             else:
    196                 filename = fname
--> 197             exec compile(scripttext, filename, 'exec') in glob, loc
    198     else:
    199         def execfile(fname, *where):

d:\playground\test.py in <module>()
     13         print "hello"
     14         global strName
---> 15         print strName
     16 

NameError: global name 'strName' is not defined

In [11]:

I was wondering why this happens and is there any way to access strName in test.py?

like image 226
Jason Yang Avatar asked Nov 26 '25 20:11

Jason Yang


1 Answers

global isn't global. global is module-level; truly global variables like min and int live in the __builtin__ module (builtins in Python 3). Using a global declaration at module level is redundant.

I strongly recommend you pass your data to test.py another way, such as by defining a function in there and passing your string as an argument:

test.py:

def print_thing(thing):
    print thing

other code that wants to use test.py:

import test
test.print_thing("Joe")
like image 124
user2357112 supports Monica Avatar answered Nov 28 '25 12:11

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!