470,849 Members | 1,469 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,849 developers. It's quick & easy.

Global name "userid" not defined??

How do I rectify this?

------vars.py------

#!/usr/local/bin/python

def setUserid(value):
userid = value

def getUserid():
return userid

--------------------
import vars
vars.setUserid("Sean")
vars.getUserid()


Then I get a Traceback error and the last line says:
NameError: name 'userid' is not defined

How do I make a variable global?

Sorry about the easy question... but I don't have all that much experience
in Python.
Jul 18 '05 #1
3 11754
Sean Berry wrote:
#!/usr/local/bin/python

def setUserid(value):
userid = value

def getUserid():
return userid

How do I make a variable global?


You need to use the "global" keyword (check the docs for more
information) with the name of the variable at the top of each
function which wants to *modify* the global variable (including by
creating it in the first place).

Although you don't need to include this ("global userid") in
the second function, it would probably be considered "good style".
Of course, using globals at all is pretty bad style, but as you're
just learning it's not the worst thing to do. (Close, but not
the worst... just consider learning how to avoid them, generally
by making things more object-oriented.)

-Peter
Jul 18 '05 #2
In message <Uqiac.1044$zh.796@fed1read07>, Sean Berry wrote:
How do I rectify this? def setUserid(value): global userid userid = value

def getUserid(): global userid return userid


--
Garry Knight
ga*********@gmx.net ICQ 126351135
Linux registered user 182025
Jul 18 '05 #3
On Tue, 30 Mar 2004 09:53:47 -0600, Sean Berry wrote:
How do I make a variable global?


Mu. (You're asking the wrong question.)

Why do you need to make a variable global? Global variables are bad
style in almost every instance; an object to manage the variable gives
you readability and protection from unexpected side-effects.

If you explain what it is you want to achieve with a global variable,
it's likely a better solution can be proposed.

--
\ "Giving every man a vote has no more made men wise and free |
`\ than Christianity has made them good." -- Henry L. Mencken |
_o__) |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Ferd Biffle | last post: by
2 posts views Thread by mike | last post: by
reply views Thread by mc kim via .NET 247 | last post: by
3 posts views Thread by Peter Theill | last post: by
9 posts views Thread by Patrick | last post: by
3 posts views Thread by kang jia | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.