Title: Emit SyntaxWarning for code that risks UnboundLocalError
Type: enhancement Stage: resolved
Components: Versions: Python 3.5
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: asvetlov, daniel.urban, georg.brandl, ncoghlan
Priority: normal Keywords:

Created on 2012-11-07 14:59 by ncoghlan, last changed 2017-03-07 19:24 by serhiy.storchaka. This issue is now closed.

Messages (2)
msg175107 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2012-11-07 14:59
The compiler is actually in a fairly good position to tell when code is at risk of triggering UnboundLocalError at runtime: specifically, in the section of the code that checks for duplicated parameter names [1]

Now, we can't emit SyntaxError here for backwards compatibility reasons (if you have an early reference that is never executed, your code is dodgy but will still run OK).

However, we should be able to emit a Syntax *Warning* when we detect an existing symbol at function scope having DEF_LOCAL applied for the first time *after* it has already been referenced in a way which doesn't create a local variable.

Something like:

SyntaxWarning: Local variable NAME bound after earlier reference (risks UnboundLocalError when function is called)

msg228683 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2014-10-06 13:48
I seem to recall that this was rejected into the realm of linters in a python-dev discussion.

If there is a chance of false positives, having Python emit the warning would be annoying because there is no convenient way of telling it to shut up about it.  At least people can choose not to run linters, or configure them to their taste.
Date User Action Args
2017-03-07 19:24:04serhiy.storchakasetstatus: pending -> closed
stage: resolved
2014-10-06 13:48:28georg.brandlsetstatus: open -> pending

nosy: + georg.brandl
messages: + msg228683

resolution: rejected
2014-08-03 20:44:51BreamoreBoysettype: enhancement
versions: + Python 3.5, - Python 3.4
2013-05-04 09:55:28daniel.urbansetnosy: + daniel.urban
2012-11-15 15:52:03asvetlovsetnosy: + asvetlov
2012-11-07 14:59:26ncoghlancreate