Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #30676 > unrolled thread
| Started by | Dave Angel <d@davea.name> |
|---|---|
| First post | 2012-10-03 02:08 -0400 |
| Last post | 2012-10-03 02:08 -0400 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: local variable 'a' referenced b Dave Angel <d@davea.name> - 2012-10-03 02:08 -0400
| From | Dave Angel <d@davea.name> |
|---|---|
| Date | 2012-10-03 02:08 -0400 |
| Subject | Re: local variable 'a' referenced b |
| Message-ID | <mailman.1755.1349244548.27098.python-list@python.org> |
On 10/03/2012 01:54 AM, Demian Brecht wrote: > 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 > > One problem with short examples is they mask the reason for the code to be structured that way. I assumed that the OP was really talking about a closure, and that sharing that variable was deliberate. I seldom write nested functions otherwise. -- DaveA
Back to top | Article view | comp.lang.python
csiph-web