Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like 'nonlocal' in Python < 3? [duplicate]

I got a piece of 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 defined in the outermost scop, I would prefer to have it only in outer function. As I understand correctly, in Python3 this is done by nonlocal. Is there a better method for what I want to have? I would prefer to declare and assign foo in outer and maybe to delcare 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 work, foo seems to be searched in the outermost scope.

like image 529
wal-o-mat Avatar asked Mar 08 '26 18:03

wal-o-mat


2 Answers

I use 1-element 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 using nonlocal, at the cost of a slightly more cumbersome syntax (foo[0] instead of foo).

like image 173
luispedro Avatar answered Mar 11 '26 08:03

luispedro


No, have this as a parameter to your make_id function. Even better put your id in a class, and have make_id as an instance method, and have that instance as a global (if you must).

like image 25
Marcin Avatar answered Mar 11 '26 08:03

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!