PyCharm false syntax error using turtle

2020-04-11 09:27发布

问题:

The code below works perfectly, however, PyCharm complains about syntax error in forward(100)

#!/usr/bin/python
from turtle import *

forward(100)

done()

Since turtle is a stanrd library I don't think that I need to do additional configuration, am I right?

回答1:

The forward() function is made available for importing by specifying __all__ in the turtle module, relevant part from the source code:

_tg_turtle_functions = [..., 'forward', ...]
__all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
           _tg_utilities + _math_functions)

Currently, pycharm cannot see objects being listed in module's __all__ list and, therefore, marks them as an unresolved reference. There is an open issue in it's bugtracker:

Make function from method: update __all__ if existing for starred import usage

See also: Can someone explain __all__ in Python?


FYI, you can add the noinspection comment to tell Pycharm not to mark it as an unresolved reference:

from turtle import *

#noinspection PyUnresolvedReferences
forward(100)

done()

Or, disable the inspection for a specific scope.


And, of course, strictly speaking, you should follow PEP8 and avoid wildcard imports:

import turtle

turtle.forward(100)
turtle.done()


回答2:

Another solution would be to explicitly create a Turtle object. Then autocomplete works just as it should and everything is a bit more explicit.

import turtle

t = turtle.Turtle()

t.left(100)
t.forward(100)

turtle.done()

or

from turtle import Turtle

t = Turtle()