Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #30675

Re: local variable 'a' referenced b

Date 2012-10-02 22:54 -0700
From Demian Brecht <demianbrecht@gmail.com>
Subject Re: local variable 'a' referenced b
References <CA+YdQ_63BCEqjVd0W5vTK+r2K0K8JPdfDptFUXLc2jFESZ8Sgg@mail.gmail.com> <506BA24F.8060409@davea.name>
Newsgroups comp.lang.python
Message-ID <mailman.1754.1349243658.27098.python-list@python.org> (permalink)

Show all headers | View raw


On 12-10-02 07:26 PM, Dave Angel wrote:
>
> if you're stuck with Python2.x, you can use a mutable object for a, and
> mutate it, rather than replace it.  For example,
>
>
> def foo():
>       a = [3]
>       def bar():
>           b=2
>           a.append(b)   #this mutates a, but doesn't assign it
>           print (a)
>           a[0] += b  #likewise, for a number within the list
>           print (a)
>       bar()
>
> That should work in either 2.x or 3.2
>

Alternatively, you can restructure your code by simply adding a 
parameter to bar(). Nice thing about this is that if you ever move bar() 
out into another module, then you don't have to worry about documenting 
the side effects on 'a' so users (including yourself) aren't confused later:

 >>> def foo():
...     a = 1
...     def bar(n):
...             b = 2
...             return n + b
...     a = bar(a)
...     print a
...
 >>> foo()
3


-- 
Demian Brecht
@demianbrecht
http://demianbrecht.github.com

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: local variable 'a' referenced b Demian Brecht <demianbrecht@gmail.com> - 2012-10-02 22:54 -0700

csiph-web