PyCharm false syntax error using turtle

旧街凉风 提交于 2019-12-20 01:55:12

问题


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()


来源:https://stackoverflow.com/questions/25588642/pycharm-false-syntax-error-using-turtle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!