Python Forum

Full Version: indentation in try/except
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i coded a try/except clause and accidentally had a different indentation in the except part. i noticed this quickly but was not sure if it was allowed. so i tried it and it worked. but is it really a requirement for code, in general (and just overlooked by CPython)?
...
try:
    foobar()
except OSError:
        bummer()
...
are compliant implementations of Python3 required to accept that?
(Sep-24-2023, 01:25 AM)Skaperen Wrote: [ -> ]are compliant implementations of Python3 required to accept that?
This is handled at lexical level by Python's tokener which generates INDENT or DEDENT tokens, so I think you can assume confidently that every implementation of Python will accept it
>>> print(s)
try:
    foobar()
except OSError:
        bummer()
>>> for token in generate_tokens(io.StringIO(s).readline):
...     print(token)
... 
TokenInfo(type=1 (NAME), string='try', start=(1, 0), end=(1, 3), line='try:\n')
TokenInfo(type=54 (OP), string=':', start=(1, 3), end=(1, 4), line='try:\n')
TokenInfo(type=4 (NEWLINE), string='\n', start=(1, 4), end=(1, 5), line='try:\n')
TokenInfo(type=5 (INDENT), string='    ', start=(2, 0), end=(2, 4), line='    foobar()\n')
TokenInfo(type=1 (NAME), string='foobar', start=(2, 4), end=(2, 10), line='    foobar()\n')
TokenInfo(type=54 (OP), string='(', start=(2, 10), end=(2, 11), line='    foobar()\n')
TokenInfo(type=54 (OP), string=')', start=(2, 11), end=(2, 12), line='    foobar()\n')
TokenInfo(type=4 (NEWLINE), string='\n', start=(2, 12), end=(2, 13), line='    foobar()\n')
TokenInfo(type=6 (DEDENT), string='', start=(3, 0), end=(3, 0), line='except OSError:\n')
TokenInfo(type=1 (NAME), string='except', start=(3, 0), end=(3, 6), line='except OSError:\n')
TokenInfo(type=1 (NAME), string='OSError', start=(3, 7), end=(3, 14), line='except OSError:\n')
TokenInfo(type=54 (OP), string=':', start=(3, 14), end=(3, 15), line='except OSError:\n')
TokenInfo(type=4 (NEWLINE), string='\n', start=(3, 15), end=(3, 16), line='except OSError:\n')
TokenInfo(type=5 (INDENT), string='        ', start=(4, 0), end=(4, 8), line='        bummer()')
TokenInfo(type=1 (NAME), string='bummer', start=(4, 8), end=(4, 14), line='        bummer()')
TokenInfo(type=54 (OP), string='(', start=(4, 14), end=(4, 15), line='        bummer()')
TokenInfo(type=54 (OP), string=')', start=(4, 15), end=(4, 16), line='        bummer()')
TokenInfo(type=4 (NEWLINE), string='', start=(4, 16), end=(4, 17), line='')
TokenInfo(type=6 (DEDENT), string='', start=(5, 0), end=(5, 0), line='')
TokenInfo(type=0 (ENDMARKER), string='', start=(5, 0), end=(5, 0), line='')
>>> 
the amount of indent is there in the info of those INDENT and DEDENT tokens (difference from start to end or length of string). so it is possible to restrict it after tokenization. but restricting it, then, does not make sense.