Lack of whitespace between contain operator ("in") and other expression tokens doesn't result in SyntaxError: bug or feature?

Garrett Cooper yanegomi at gmail.com
Thu May 3 14:49:29 EDT 2012


Hi Python folks!
 I came across a piece of code kicking around a sourcebase that
does something similar to the following:
>>> START >>>>
#!/usr/bin/env python
import sys
def foo():
 bar = 'abcdefg'
 foo = [ 'a' ]
 # Should throw SyntaxError?
 for foo[0]in bar:
 sys.stdout.write('%s' % foo[0])
 sys.stdout.write('\n')
 sys.stdout.write('%s\n' % (str(foo)))
 # Should throw SyntaxError?
 if foo[0]in bar:
 return True
 return False
sys.stdout.write('%r\n' % (repr(sys.version_info)))
sys.stdout.write('%s\n' % (str(foo())))
>>> END >>>>

 I ran it against several versions of python to ensure that it
wasn't a regression or fixed in a later release:
$ /scratch/bin/bin/python ~/test_bad_in.py
"(2, 3, 7, 'final', 0)"
abcdefg
['g']
True
$ python2.7 ~/test_bad_in.py
"sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0)"
abcdefg
['g']
True
$ python3.2 ~/test_bad_in.py
"sys.version_info(major=3, minor=2, micro=3, releaselevel='final', serial=0)"
abcdefg
['g']
True
$ uname -rom
FreeBSD 9.0-STABLE amd64
$
 And even tried a different OS, just to make sure it wasn't a
FreeBSD thing...
% python test_bad_in.py
"(2, 6, 5, 'final', 0)"
abcdefg
['g']
True
% uname -rom
2.6.32-71.el6.x86_64 x86_64 GNU/Linux
 I was wondering whether this was a parser bug or feature (seems
like a bug, in particular because it implicitly encourages bad syntax,
but I could be wrong). The grammar notes (for 2.7 at least [1]) don't
seem to explicitly require a space between 'in' and another parser
token (reserved work, expression, operand, etc), but I could be
misreading the documentation.
Thanks!
-Garrett
1. http://docs.python.org/reference/grammar.html


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /