[Python-ideas] SyntaxWarning for for/while/else without break or return?

Steven D'Aprano steve at pearwood.info
Sat Oct 10 14:36:13 CEST 2009


On Sat, 10 Oct 2009 10:32:55 pm Nick Coghlan wrote:
> Steven D'Aprano wrote:
> >> The point of a warning is very much that the code works and is
> >> legal, but *in most case* is not what people would want.
> >
> > Can you give any examples in the Python standard library where code
> > raises a warning on such a basis?
> >
> > I would be shocked if you can give any examples.
>
> See my other post - there are currently 3 in the 2.x branch. 

See my previous response.


> Two of 
> them are pure style warnings strongly encouraging people to put their
> global statements at the beginning of the function, 

That's fundamentally the same warning: don't access a global before you 
declare it global. Whether that access is an assignment or a lookup is 
trivial.


> while the third 
> is a warning issued due to the fact that using "import *" inside a
> function is a really bad idea (at the very least, it forces the
> compiler to disable all of its normal local variable optimisations,
> as it has no idea what local variable names are going to exist after
> that import statement executes).

It's actually a warning that the functionality is in the process of 
being removed.


> I just checked the Py3k branch, and that adds a few more:
>
> - A warning for assert statements with a non-empty tuple as the first
> argument (i.e. cases where the assert will never fail)

But only if the first argument is a tuple:

>>> assert 1
>>> assert 1, "error"
>>> assert (1, "error")
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove 
parentheses?

And ridiculously:

>>> assert (1, 2), "error"
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove 
parentheses?

Why single out always-true tuples for a warning, when other always-true 
items are considered legitimate, even when there is no ambiguity about 
what the programmer meant? This sort of inconsistency makes little 
sense and should stand as a cautionary tale for people putting warnings 
in the compiler: sometimes the warning is *bad advice*:

>>> assert 1, 2, "error"  # remove the () like the compiler said
  File "<stdin>", line 1
    assert 1, 2, "error"  # remove the () like the compiler said
               ^
SyntaxError: invalid syntax


> - Another two extending the global statement warnings to cover
> nonlocal statements as well.

Given that Python warns about global, it makes sense to warn about 
nonlocal. Its all the same thing really, just the details change: 
whether the declaration is global or nonlocal, whether it is an 
assignment or a lookup, it's the same fundamental warning: don't use a 
non-local variable before declaring it as such.




-- 
Steven D'Aprano



More information about the Python-ideas mailing list