By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,440 Members | 1,609 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,440 IT Pros & Developers. It's quick & easy.

Global name "userid" not defined??

P: n/a
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
Share this Question
Share on Google+
3 Replies


P: n/a
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

P: n/a
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

P: n/a
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.