flake8 — синтаксическая ошибка E999 с аргументом метакласса python3
Я использую vim для разработки python с flake8 как linter. Ниже приведен пример кода, содержащего метаклазы. Flake8 показывает ошибку E999 SyntaxError: недействительный синтаксис (E) в class Spam(metaclass=MyMeta) строк class Spam(metaclass=MyMeta) . Я использую python3, и это правильный синтаксис для указания пользовательских метаклассов в python3.
Есть ли способ исправить это?
1 ответ
Ну, вы редактируете код Python3, и ваш flake8, очевидно, проверяет синтаксис Python2.
Оглядываясь по Интернету, простой способ заставить flake8 проверить Python3 — запустить его с Python3.
Скорее всего, вы используете Linux или другой Unix (я взял подсказку из использования VIM), поэтому, если flake8 установлен в системном масштабе, удалите его и установите в Python3 (в Fedora и redhatish distros это dnf uninstall python2-flake8 dnf install python3-flake8 ).
Более подходящий подход может быть просто настроен на виртуальный процесс для вашего проекта Python, с желаемой версией Python, установить flake8 внутри этого виртуального сервера, с помощью pip install flake8 , а также запустить VIM изнутри вашего pip install flake8 , чтобы любые скрипты или программы Python прогоны находятся в одной среде, и даже такие вещи, как расширенный автозаполнение, могут проверять библиотеки, которые использует ваш проект.
Flake8 сообщает E999 SyntaxError Atom Flake 8
Я не могу решить проблему с синтаксической ошибкой flake8, хотя код работает нормально.
Код без комментариев
2 ответа
Как говорит @jonrsharpe, и я согласен, это связано с тем, что код выполняется на Python 2, но добавлен в Python 3.
Мы сообщаем E999, когда нам не удается скомпилировать файл в абстрактное синтаксическое дерево для подключаемых модулей, которые этого требуют.
Итак, чтобы доказать, что это правильно, используя файл с именем bad_syntax.py и используя тот же синтаксис print , что и выше:
Когда я запускаю это с Python 2, все в порядке:
Линтинг с flake8 , запущенным в среде Python 2, также проходит.
Но когда я использую Python 3 (он работает в virtualenv venv с установленным Python 3), возвращается E999 :
Я не думаю, что это параметр, который нужно менять внутри linter-flake8 , потому что Flake8 будет использовать версию Python, через которую он запускается. Я предполагаю, что Flake8 работает на Python 3, потому что он был установлен внутри среды Python 3, хотя код выполняется на Python 2.
В программе запуска Flake8 Python3 жестко запрограммирован как основной питон.
1) установите пакет flake8 с помощью pip
$ pip install flake8
Pip сообщит вам, что скрипт flake8 не был добавлен в путь и путь печати к нему ( /Library/Frameworks/Python.framework/Versions/2.7/bin/ в моем случае)
2) настройте свою IDE (Atom / PyCharm / etc), чтобы использовать этот скрипт с вашим Python 2.7 по умолчанию (мой пример взят из PyCharm @ MacOS):
Flake8 reports E999 SyntaxError
I am unable to solve the flake8 SyntaxError and although the code executes just fine.

Code without comments
![]()
![]()
2 Answers 2
As @jonrsharpe says, and I agree, this is because the code is being run in Python 2, but linted in Python 3.
We report E999 when we fail to compile a file into an Abstract Syntax Tree for the plugins that require it.
So to prove this is correct, using a file called bad_syntax.py and using the same print syntax as above:
When I run this with Python 2, everything is happy:
Linting with flake8 invoked with a Python 2 environment also passes.
But when I lint with Python 3 (this is running in a virtualenv venv with Python 3 installed), the E999 is returned:
I do not think that this is a setting that needs changing inside linter-flake8 because Flake8 will use the version of Python that it is run through. My guess would be that Flake8 is being run on Python 3 because it has been installed inside a Python 3 environment, even though the code is being run on Python 2.
Name already in use
flake8 / docs / source / user / error-codes.rst
- Go to file T
- Go to line L
- Copy path
- Copy permalink
6 contributors
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Error / Violation Codes
Flake8 and its plugins assign a code to each message that we refer to as an :term:`error code` (or :term:`violation` ). Most plugins will list their error codes in their documentation or README.
Flake8 installs pycodestyle , pyflakes , and mccabe by default and generates its own :term:`error code` s for pyflakes :
| Code | Example Message |
|---|---|
| F401 | module imported but unused |
| F402 | import module from line N shadowed by loop variable |
| F403 | ‘from module import *’ used; unable to detect undefined names |
| F404 | future import(s) name after other statements |
| F405 | name may be undefined, or defined from star imports: module |
| F406 | ‘from module import *’ only allowed at module level |
| F407 | an undefined __future__ feature name was imported |
| F501 | invalid % format literal |
| F502 | % format expected mapping but got sequence |
| F503 | % format expected sequence but got mapping |
| F504 | % format unused named arguments |
| F505 | % format missing named arguments |
| F506 | % format mixed positional and named arguments |
| F507 | % format mismatch of placeholder and argument count |
| F508 | % format with * specifier requires a sequence |
| F509 | % format with unsupported format character |
| F521 | .format(. ) invalid format string |
| F522 | .format(. ) unused named arguments |
| F523 | .format(. ) unused positional arguments |
| F524 | .format(. ) missing argument |
| F525 | .format(. ) mixing automatic and manual numbering |
| F541 | f-string without any placeholders |
| F601 | dictionary key name repeated with different values |
| F602 | dictionary key variable name repeated with different values |
| F621 | too many expressions in an assignment with star-unpacking |
| F622 | two or more starred expressions in an assignment (a, *b, *c = d) |
| F631 | assertion test is a tuple, which is always True |
| F632 | use ==/!= to compare str , bytes , and int literals |
| F633 | use of >> is invalid with print function |
| F634 | if test is a tuple, which is always True |
| F701 | a break statement outside of a while or for loop |
| F702 | a continue statement outside of a while or for loop |
| F703 | a continue statement in a finally block in a loop |
| F704 | a yield or yield from statement outside of a function |
| F706 | a return statement outside of a function/method |
| F707 | an except: block as not the last exception handler |
| F721 | syntax error in doctest |
| F722 | syntax error in forward annotation |
| F723 | syntax error in type comment |
| F811 | redefinition of unused name from line N |
| F821 | undefined name name |
| F822 | undefined name name in __all__ |
| F823 | local variable name . referenced before assignment |
| F831 | duplicate argument name in function definition |
| F841 | local variable name is assigned to but never used |
| F901 | raise NotImplemented should be raise NotImplementedError |
We also report one extra error: E999 . We report E999 when we fail to compile a file into an Abstract Syntax Tree for the plugins that require it.
mccabe only ever reports one :term:`violation` — C901 based on the complexity value provided by the user.