简体   繁体   中英

Why am I able to access a variable that was defined in a try-except in Python from outside the try-catch?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM