Is there something like "non-local" in Python <3?

I have a code like this:

foo = None

def outer():
    global foo
    foo = 0

    def make_id():
        global foo
        foo += 1
        return foo


    id1 = make_id() # id = 1
    id2 = make_id() # id = 2
    id3 = make_id() # ...

      

I find it ugly to have foo

it defined in an external scop, I would rather only use it in outer

. As I understand it correctly, in Python3 this is done using nonlocal

. Is there a better way for what I want to have? I'd rather declare and assign foo

to, outer

and perhaps consider it global

in inner

:

def outer():
    foo = 0

    def make_id():
        global foo
        foo += 1     # (A)
        return foo

    id1 = make_id() # id = 1
    id2 = make_id() # id = 2
    id3 = make_id() # ...

      

(A) does not seem to work foo

in the outermost area.

+3


source share


3 answers


No, the best alternative for it is function attributes.



0


source


I am using 1-item lists for this purpose:

def outer():
    foo = [0]
    def make_id():
        r = foo[0]
        foo[0] += 1
        return r
    return make_id

make_id = outer()
id1 = make_id()
id2 = make_id()
...

      



This is the same as when used, nonlocal

due to the slightly more cumbersome syntax ( foo[0]

instead of foo

).

+6


source


No, use this as a parameter to a function make_id

. Better yet, put your id in a class and make_id

as an instance method and that instance will be global (if needed).

+4


source







All Articles