variable scope in try ... EXCEPT block.

Ed Kellett e+python-list at kellett.im
Thu Jul 12 08:31:57 EDT 2018


On 2018-07-12 10:59, Steven D'Aprano wrote:
> On Thu, 12 Jul 2018 01:37:24 -0700, aleiphoenix wrote:
> 
>> My question is, does except ... as ... create a new scope from outer
>> block, causing 'err' be hidden from outer scope? Is this intentional?
> 
> No, it is not a new scope, and yes, it is intentional. It's a nasty hack, 
> but a *necessary* nasty hack: when the except block exits, the "err" 
> local variable (or whatever it happens to be called) is implicitly 
> deleted.
> 
> You can work around this by explicitly assigning to another local 
> variable:
> 
>     try:
>         ...
>     except Exception as e:
>         err = e  # only "e" will be deleted when we exit the block
> 
> 
> This is necessary in Python 3 [...]

"necessary" is debatable. When we have reference counting, general
garbage collection, *and* nasty hacks like this, one could be forgiven
for thinking Python has chosen the worst of all memory-management worlds.

That said, in this case it's entirely livable-with once one knows about it.

Unrelatedly, having stared at this email for a moment, I really wish
Thunderbird had an option to avoid orphan
words

Ed



More information about the Python-list mailing list