This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author bruno.dupuis
Recipients Horpner, bruno.dupuis, ikelly, python-dev, steven.daprano
Date 2012-12-05.19:28:30
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1354735711.68.0.957152871087.issue16619@psf.upfronthosting.co.za>
In-reply-to
Content
We found some strange behaviour of the compiler in this discussion on python-list: http://mail.python.org/pipermail/python-list/2012-December/636104.html

The fact is, `return` and `return None` result in inconsistent bytecode depending on the context.

Consider :

>>> import dis
>>> def f(x):
...     return None
... 
>>> dis.dis(f)
  2           0 LOAD_CONST               0 (None) 
              3 RETURN_VALUE         
>>> def g(x):
...     return None
...     print(x)
... 
>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (None) 
              3 RETURN_VALUE         

  3           4 LOAD_GLOBAL              1 (print) 
              7 LOAD_FAST                0 (x) 
             10 CALL_FUNCTION            1 (1 positional, 0 keyword pair) 
             13 POP_TOP              

`return None` statement results in LOAD_GLOBAL 0 if there is some unreachable code after it. I first saw that as an optimization issue, but Ian Kelly's message http://mail.python.org/pipermail/python-list/2012-December/636117.html gives an extensive analysis and some examples:

"""
  I think this should even be considered a bug, not just a missing
  optimization.  Consider:

  >>> globals()['None'] = 42
  >>> def f(x):
  ...     return None
  ...     print(x)
  ...
  >>> f('test')
  42

  The use of the LOAD_GLOBAL allows None to effectively be reassigned.

"""

Ian also points out in this message that `return` and `return None` don't result in the same bytecode when followed by trash code.
History
Date User Action Args
2012-12-05 19:28:31bruno.dupuissetrecipients: + bruno.dupuis, ikelly, Horpner, steven.daprano, python-dev
2012-12-05 19:28:31bruno.dupuissetmessageid: <1354735711.68.0.957152871087.issue16619@psf.upfronthosting.co.za>
2012-12-05 19:28:31bruno.dupuislinkissue16619 messages
2012-12-05 19:28:30bruno.dupuiscreate