Skip to content

Statement 'if 0: yield' not failing with error

ebranca edited this page Jun 14, 2014 · 2 revisions

Classification

  • Affected Components : builtins

  • Operating System : Linux

  • Python Versions : 2.6.x, 2.7.x, 3.1.x, 3.2.x

  • Reproducible : Yes

Source code

# TEST1
# should return sintax error as yield is outside a function
try:
    if 0:
        yield 5
    print("TEST1-FAIL")
except Exception as e:
    print("TEST1-PASS")
    pass

# TEST2
# should return sintax error as yield is outside a function
try:
    if False: 
        yield 5
    print("TEST2-FAIL")
except Exception as e:
    print(repr(e))
    pass

Steps to Produce/Reproduce

To reproduce the problem copy the source code in a file and execute the script using the following command syntax:

$ python -OOBRtt test.py

Alternatively you can open python in interactive mode:

$ python -OOBRtt <press enter>

Then copy the lines of code into the interpreter.

Description

Python has different behaviors based on how conditions are expressed and on which version of python is used.

The source code used for this example has been tailored to test python behavior in two conditions:

  1. if 0: yield
  2. if False: yield

In both cases the code is a bad example of broken code and should generate "SyntaxError" but this is not the case.

TEST 1

Should return SyntaxError as yield is outside a function.

*** Expected: *** SyntaxError: 'yield' outside function

  • Python 2.6.5 32bit --> "Returns nothing" (WRONG)

  • Python 2.7.4 32bit --> "TEST1-FAIL" (WRONG)

  • Python 3.1.2 32bit --> "TEST1-FAIL" (WRONG)

TEST 2

Should return SyntaxError as yield is outside a function.

*** Expected: *** SyntaxError: 'yield' outside function

  • Test Results:

-- Python 2.6.5 32bit --> "SyntaxError: 'yield' outside function" (CORRECT)

-- Python 2.7.4 32bit --> "SyntaxError: 'yield' outside function" (CORRECT)

-- Python 3.1.2 32bit --> "TEST2-FAIL" (WRONG)

The interpreter eliminates the block if 0 and correctly emits the else clause if present, but the yield statement is still optimized away.

In Python 3.x this condition has not been fixed but the problem has been ignored, "if 0: yield" at module level is plainly ignored and does not raises a Syntaxerror but is still there.

Workaround

We are not aware on any easy solution other than trying to avoind using constructs like if 0: or while 0:.

Secure Implementation

WORK IN PROGRESS

References

[Simple Statements][01] [01]:https://docs.python.org/2/reference/simple_stmts.html

[Compound Statements][02] [02]:https://docs.python.org/2/reference/compound_stmts.html

[Python bug 1875][03] [03]:http://bugs.python.org/issue1875

[Control Flow][04] [04]:https://docs.python.org/2/tutorial/controlflow.html

[Python bug 1920][05] [05]:http://bugs.python.org/issue1920

  • Home
  • [Security Concerns](Security Concerns)
Clone this wiki locally