Home > other >  Why am I able to access a variable that was defined in a try-except in Python from outside the try-c
Why am I able to access a variable that was defined in a try-except in Python from outside the try-c

Time:05-11

Here is an example of some Python code:

try:
    x = l[4]
except Exception as e:
    x = 7
    
print(x)

I am wondering, what is the reason that I have access to x? I thought that I would need to do the following:

# Define x
x = ''
try:
    x = l[4]
except Exception as e:
    x = 7
    
print(x)

But for some reason, Python does not require that? Is this a scoping thing?

CodePudding user response:

It is a scoping thing, or rather, the lack of a scope. Python does not have block scopes; the only thing that defines a new scope in Python is a function definition. (Comprehensions do, too, but that's because they are implemented using anonymous functions.)

There is no "local" x in either the try block or the except block; both are the same x as defined before the try statement.

One exception: e is kind of local. It's still in the same scope as x, but it is unset by the try statement once it completes to avoid a reference cycle, just as if you had written del e immediately after the statement.

  • Related