Re: local variable 'a' referenced b

Discussion in 'Python' started by Demian Brecht, Oct 3, 2012.

  1. 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
     
    Demian Brecht, Oct 3, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Moscatt
    Replies:
    2
    Views:
    9,826
    Peter Moscatt
    Mar 19, 2005
  2. Replies:
    2
    Views:
    5,312
    Diez B. Roggisch
    Feb 26, 2006
  3. Pete Bartonly
    Replies:
    10
    Views:
    813
    Dennis Lee Bieber
    Oct 25, 2007
  4. Wang, Harry
    Replies:
    2
    Views:
    317
  5. Gabriel Rossetti
    Replies:
    3
    Views:
    972
    Hrvoje Niksic
    Dec 9, 2009
Loading...

Share This Page