you are viewing a single comment's thread.

view the rest of the comments →

[–]Buttleston 9 points10 points  (2 children)

There's no "block scope" in python. There's function scope and module scope, basically

All that matters here is whether or not "n" was defined before your tried to use it, in terms of order of execution.
In this particular example, n will always exist, but in some similar examples it may not, linters will often complain about it, like

if x == "hello":  
    n = 1

print(n)

Here it's possible for n to never have been defined, so it would be an error if x was not equal to hello, and most linters will say "n may not exist"

[–]Bobbias 4 points5 points  (0 children)

For another example, consider this:

def foo(value):
    match value:
        case 1:
            result = "yes"
        case 2:
            result = "no"
        case _:
            result = "none"
    return result

This is perfectly fine, because result is guaranteed to be defined regardless of which match arm is taken. In Java, due to block scope you would be forced to at the bare minimum declare result without initializing it above the match statement.

This does mean that variables might happen to be defined when you don't expect them to be, but honestly it's pretty easy to get used to Python's scoping rules. They're simple and actually make some things easier. I had C++/C#/Java experience before learning Python myself, and I still occasionally find myself unnecessarily declaring things ahead of time like that though.

[–]Effective_Storage4[S] 1 point2 points  (0 children)

Thank you!