Why does not walrus assignment limit variable local to statement

if a := 0:
    print(a)  # a is limited to the statement

print(a)  # maybe reports Error: a is not defined

In C and C++, the scope of the variable in control expression in if and for statements is limited to the statements. Can Python do this too?

1 Like

I can’t reproduce the error you’re describing. When I execute

if a := 0:
    print(a)

print(a)

I see 0 printed to the screen, as expected.

That was the point the OP was making; the scope of a is NOT limited to the block in which it was defined.

No. In Python, if the code is executed, it sticks. To produce your desired behavior you would need something like:

if 0:
    a = 0
print(a)  # error
1 Like

Sorry that my post was not clear.

What about make the scope of a1 identical to a2. Both can not be used outside the control statement.

if a1 := 1
    a2 = 0
print(a1)  # maybe reports error too
print(a2)  # error

But I guess, maybe it does not matter. In Python, in many cases I can not even distinguish variable definition from assignment. And it seems that there will never be name collision.

a = 'abc'

if a := 1:
    print(a)

if a := True:
    print(a)

Aye. The scopes of names are deliberately few in Python. IMO this is a
good thing:

  • builtins
  • module
  • functions
    and that’s it!

While I am a fan of C’s:

for (int i=0; i<10; i++) {
    ... i defined only here ...
}

for trite things like loop counters, and also of C’s:

{ int i;
  ... i defined only here ...
}

subblocks, I’m generally against lots of scopes.

If you want a new scope, define a function. It can even be inside your
code as a closure if you need access to the outer scope.

In particular, scopes bring variable name shadowing, which can be a
confusing source of bugs sometimes. I’d be happier if some hypothetical
scope syntax fordade shadowing, but that is not normally the case.
(And it is problematic in a dynamic language like Python where names
only get defined when assigned to).

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like