Re: 'local' var in module

From: Josiah Carlson (jcarlson_at_uci.edu)
Date: 10/07/04


Date: Thu, 07 Oct 2004 08:36:40 -0700
To: Andreas Lobinger <andreas.lobinger@netsurf.de>, python-list@python.org


> lobingera@sibyl: cat flip.py
> import random
>
> paras = { 'flength' : 22,
> 'cset' : 'abcdefghijkl' }
> rstate = 1
>
> def f():
> random.seed(rstate)
> s = list()
>
> for i in range(paras['flength']):
> s.append(random.choice(paras['cset']))
>
> return "".join(s)

When you are only reading things, Python will pull variables from the
local or global scope as necessary.

> def g():
> random.seed(rstate)
> s = list()
>
> for i in range(paras['flength']):
> s.append(random.choice(paras['cset']))
>
> rstate = random.getseed()
> return "".join(s)

If you try to write to a variable in a scope, Python believes that the
variable is local to this scope, so doesn't attempt to fetch it from
globals, and will only write to the local copy.

That is, unless you include the 'global' keyword. Add:
    global rstate
to g() and watch everything work the way you expect.

 - Josiah



Relevant Pages

  • PyRun_String and related functions causing garbage when calling a parsed function from C.
    ... python integration (it embeds python, ... def doConstraint(inmat, tarmat, prop): ... PyObject *RunPython2(Text * text, PyObject * globaldict, PyObject ... PyObject *globals, *locals; ...
    (comp.lang.python)
  • Re: Nested scopes, and augmented assignment
    ... That is what I understand with your statement that [python] always ... search stops in the local scope. ... care, similar to globals. ... scopes is a sound principle (`Nested variables considered harmful'). ...
    (comp.lang.python)
  • Re: global/local variables
    ... Python "goto" module, and use goto and comefrom in your code. ... Globals aren't as harmful as goto. ... programming at all. ...
    (comp.lang.python)
  • explicit variable scoping
    ... regard to its variable namespacing. ... rules are ancient remnants of a different Python. ... This allows accessing globals, and IMO serves for ... Finance Tax Center - File online. ...
    (comp.lang.python)
  • Re: private variables/methods
    ... I can't think of ANY "feechur" from other popular languages that hasn't ... requesting these features are typically NOT experienced with Python: ... writing globals is a delicate decision that is well worth ...
    (comp.lang.python)