'local' var in module

Josiah Carlson jcarlson at uci.edu
Thu Oct 7 11:36:40 EDT 2004


> lobingera at 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




More information about the Python-list mailing list