[Python-Dev] Add more SyntaxWarnings?

Steven D'Aprano steve at pearwood.info
Thu Jan 24 17:40:35 EST 2019


On Thu, Jan 24, 2019 at 04:01:26PM -0600, Neil Schemenauer wrote:
> On 2019-01-24, Terry Reedy wrote:
> > Serhiy Storchaka suggested a compiler SyntaxWarning and uploaded a
> > proof-of-concept diff that handled the above and many similar cases.
> 
> I believe that in general we should give better errors or warnings
> if we can do it without huge difficulty.  Serhiy's patch is quite
> simple.  The same check *could* be done by a linting tool.  Putting
> it in CPython will make it more widely available.  These checks
> could be helpful to beginners who probably won't have linting tools
> setup.

+1 to what Neil says here.

> I think we should not make it an error, otherwise we have changed
> Python "the language".

We're allowed to, we're the ones who say what the language is :-)


The remainder of my comments are more speculative.

> We don't want to force other Python
> implementations to do the same check.  It might be hard for them to
> implement.  So, SyntaxWarning seems like a reasonable compromise.

We could say that implementations are allowed to raise errors at compile 
time instead of run time, but aren't required to. Then it becomes a 
matter of "quality of implementation".

For literal ints, strings, None, etc we can tell at compile time that an 
error will occur. All of these cannot fail to raise (short of changing 
the interpreter, in which case you're not using Python anymore):

    1 + "1"  # raises TypeError
    None[x]  # TypeError
    1.234(x)  # TypeError
    "spam".idnex("a")  # AttributeError

In these specific cases, there is nothing wrong with the *syntax*, but a 
compiler should be permitted to immediately raise the same exception 
that would otherwise occur at run time. This is a form of peephole 
optimization, I guess.

If people truly wanted to delay the exception, they could either turn 
off the peephole optimizer, or work around it:

    a = 1; a + "1"

Thoughts?


-- 
Steve


More information about the Python-Dev mailing list