variable scope in try ... EXCEPT block.

aleiphoenix aleiphoenix at gmail.com
Thu Jul 12 04:37:24 EDT 2018


suppose following code running with Python-3.4.8 and Python-3.6.5


# -*- coding: utf-8 -*-


def hello():
    err = None
    print('0: {}'.format(locals()))
    try:
        b = 2
        print('1: {}'.format(locals()))
        raise ValueError()
        print('2: {}'.format(locals()))
    except ValueError as err:
        print('3: {}'.format(locals()))
        pass
    print('4: {}'.format(locals()))
    return '', err


hello()



got output:

0: {'err': None}
1: {'err': None, 'b': 2}
3: {'err': ValueError(), 'b': 2}
4: {'b': 2}
Traceback (most recent call last):
  File "err.py", line 19, in <module>
    hello()
  File "err.py", line 16, in hello
    return '', err
UnboundLocalError: local variable 'err' referenced before assignment


But without this UnboundLocalError with Python-2.7.14


My question is, does except ... as ... create a new scope from outer block, causing 'err' be hidden from outer scope? Is this intentional?

Thanks.


More information about the Python-list mailing list