Перейти к содержимому

E201 whitespace after как исправить

  • автор:

Whitespace after ‘(‘ (E201)

Open parentheses should not have any space before or after them.

Anti-pattern

# The space after open is unnecessary with open( 'file.dat') as f: contents = f.read() 

Best practice

with open('file.dat') as f: contents = f.read() 

Additional links

Flake8 Rules

  • View on GitHub
  • grantmcconnaughey
  • @gmcconnaughey

Descriptions and examples for each of the rules in Flake8 (pyflakes, pycodestyle, and mccabe).

From the creator of Postpone for Reddit.

Python-сообщество

[RSS Feed]

  • Начало
  • » Центр помощи
  • » Задача: Логи-2

#1 Окт. 4, 2014 18:57:31

nokados От: Ростов Зарегистрирован: 2013-10-15 Сообщения: 52 Репутация: 0 Профиль Отправить e-mail

Задача: Логи-2

Ограничение времени 1 секунда
Ограничение памяти 64Mb
Ввод стандартный ввод или input.txt
Вывод стандартный вывод или output.txt

Вася хочет проанализировать логи некоторой поисковой системы, в которых записан сам запрос, дата, регион пользователя и частота запроса. Вася хочет найти самые популярные запросы за каждую дату. Логи он уже достал, и теперь просит вас написать код для их анализа.
Формат ввода

Первая строка входного файла содержит одно число N от 0 до 1000. Затем идет не более 10000 строк с информацией о запросах в формате “дата\tзапрос\tрегион\tколичество”, причем для каждого региона каждый запрос встречается не более одного раза за день. Количество — натуральное число от 1 до 109. День, запрос и регион — строки длины не более 100, не содержащие символов табуляции.
Формат вывода

Для каждой даты рассмотрите N самых популярных запросов за эту дату. При равенстве частот запросов сравнивайте запросы лексикографически, и берите первые. Выведите получившиеся результаты в формате “дата\tзапрос”, отсортировав их лексикографически по дате, затем по популярности, и наконец лексикографически по запросу.
Пример

Ввод

2
01.01.2014 We love python HSE 1
01.01.2014 We love PEP8 too HSE 1
01.01.2014 E225 missing whitespace around operator Moscow 2
01.01.2014 E201 whitespace after '01.01.2014 E231 missing whitespace after ':' Moscow 5
02.01.2014 E225 missing whitespace around operator Moscow 3
02.01.2014 E225 missing whitespace around operat32[code python][/code]or Saint Petersburg 1312
02.01.2014 E501 line too long (80 > 79 characters) Moscow 4
02.01.2014 E203 whitespace before ':' Moscow 5
03.01.2014 E231 missing whitespace after ': Moscow 19
03.01.2014 E225 missing whitespace around operator New-York 12
04.01.2014 We will solve this problem HSE 1

Вывод

01.01.2014 E201 whitespace after '01.01.2014 E231 missing whitespace after ':'
02.01.2014 E225 missing whitespace around operator
02.01.2014 E203 whitespace before ':'
03.01.2014 E231 missing whitespace after ':
03.01.2014 E225 missing whitespace around operator
04.01.2014 We will solve this problem

Мое решение 1

import sys N = int(input()) requests = <> for line in sys.stdin: date, query, region, number = line.split('\t') number = int(number) if date in requests: if query in requests[date]: requests[date][query] += number else: requests[date][query] = number else: requests[date] = query: number> dates = list(requests.keys()) dates.sort() for date in dates: queries = requests[date] res_q = [] for i in range(N): max_val = 0 max_key = -1 for query in queries: if queries[query] > max_val: max_val = queries[query] max_key = query elif queries[query] == max_val: if query  max_key: max_key == query if max_key != -1: print(date, max_key, sep='\t') queries.pop(max_key) 

Решение в лоб. Работает, но из-за своей неэфективности превышает лимит по времени на одном из тестов.

Мое решение 2

import sys N = int(input()) requests = <> resinput = '' for line in sys.stdin: resinput += line date, query, region, number = line.split('\t') number = int(number) if date in requests: if query in requests[date]: requests[date][query] += number else: requests[date][query] = number else: requests[date] = query: number> dates = list(requests.keys()) dates.sort() for date in dates: queries = requests[date] res_q = [] l = 0 for query in queries: num = queries[query] if l == 0: res_q.append('num': num, 'query': query>) l = 1 else: i = 0 j = l-1 m = (i+j)//2 while i  j: if num > res_q[m]['num']: j = m-1 elif num  res_q[m]['num']: i = m+1 else: if query  res_q[m]['query']: j = m-1 else: i = m+1 m = (i+j)//2 res_q.insert(i, 'num': num, 'query': query>) l += 1 if l > N: res_q = res_q[:N] l = N for res in res_q: print(date, res['query'], sep='\t') 

Заменил полный перебор массива на бинарный поиск места, куда вставляется очередной запрос, в сортированном массиве (res_q). Но теперь ошибка в тесте раньше того, на котором был Time Limit в прошлом примере.

Отредактировано nokados (Окт. 4, 2014 18:58:28)

[Перевод] Как писать питонический код: три рекомендации и три книги 08.04.2022 01:31

Новички в Python часто спрашивают, как писать питонический код. Проблема — расплывчатое определение слова «питонический». Подробным материалом, в котором вы найдёте ответы на вопрос выше и три полезные книги, делимся к старту курса по Fullstack-разработке на Python.

Что значит «питонический»?

Python более 30 лет. За это время накоплен огромный опыт его применения в самых разных задачах. Этот опыт обобщался, и возникали лучшие практики, которые обычно называют «питоническим«кодом.

Философия Python раскрывается в The Zen of Python Тима Питерса, доступной в любом Python по команде import this в REPL:

>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

Начинающих в Python больше всего раздражает красота Zen of Python. В Zen передаётся дух того, что значит «питонический» — и без явных советов. Вот первый принцип дзена Python: «Красивое лучше, чем уродливое». Согласен на 100%! Но как сделать красивым мой некрасивый код? Что это вообще такое — «красивый код»?

Сколь бы ни раздражала эта неоднозначность, именно она делает Zen of Python таким же актуальным, как и в 1999 году, когда Тим Питерс написал этот набор руководящих принципов. Они помогают понять, как отличать питонический и непитонический код, и дают ментальную основу принятия собственных решений.

Каким же будет определение слова «питонический»? Лучшее найденное мной определение взято из ответа на вопрос «Что означает «питонический» В этом ответе питонический код описывается так:

Код, где правилен не только синтаксис, но соблюдаются соглашения сообщества Python, а язык используется так, как он должен использоваться.

Из этого делаем два ключевых вывода:

  1. Слово «питонический» связано скорее со стилем, чем с синтаксисом. Хотя идиомы Python часто имеют последствия за рамками чисто стилистического выбора, в том числе повышение производительности кода.
  2. То, что считается «питоническим», определяется сообществом Python.

Итак, у нас сложилось хотя бы какое-то представление о том, что имеют в виду программисты на Python, называя код «питоническим». Рассмотрим три конкретных и доступных способа написания более питонического кода.

1. Подружитесь с PEP8

PEP8 — это официальное руководство по стилю кода Python. PEP расшифровывается как Python Enhancement Proposal («Предложение по улучшению Python»). Это документы, предлагающие новые особенности языка. Они образуют официальную документацию особенности языка, принятие или отклонение которой обсуждается в сообществе Python. Следование PEP8 не сделает код абсолютно «питоническим», но способствует узнаваемости кода для многих Python-разработчиков.

В PEP8 решаются вопросы, связанные с символами пробелов. Например, использование четырёх пробелов для отступа вместо символа табуляции или максимальной длиной строки: согласно PEP8, это 79 символов, хотя данная рекомендация, вероятно, самая игнорируемая.

Первое, что стоит усвоить из PEP8 новичкам, — это рекомендации и соглашения по именованию. Например, следует писать имена функций и переменных в нижнем регистре и с подчёркиваниями между словами lowercase_with_underscores:

# Correct seconds_per_hour = 3600 # Incorrect secondsperhour = 3600 secondsPerHour = 3600

Имена классов следует писать с прописными первыми буквами слов и без пробелов, вот так: CapitalizedWords:

# Correct class SomeThing: pass # Incorrect class something: pass class some_thing: pass

Константы записывайте в верхнем регистре и с подчёркиваниями между словами: UPPER_CASE_WITH_UNDERSCORES:

# Correct PLANCK_CONSTANT = 6.62607015e-34 # Incorrect planck_constant = 6.6260715e-34 planckConstant = 6.6260715e-34

В PEP8 изложены рекомендации по пробелам: как использовать их с операторами, аргументами и именами параметров функций и для разбиения длинных строк. Хотя эти рекомендации можно освоить, годами практикуясь в чтении и написании совместимого с PEP8 кода, многое всё равно пришлось бы запоминать.

Запоминать все соглашения PEP8 не нужно: найти и устранить проблемы PEP8 в коде могут помочь такие инструменты, как flake8. Установите flake8 с помощью pip:

# Linux/macOS $ python3 -m pip install flake8 # Windows $ python -m pip install flake8

flake8 можно использовать как приложение командной строки для просмотра файла Python на предмет нарушений стиля. Допустим, есть файл myscript.py с таким кодом:

def add( x, y ): return x+y num1=1 num2=2 print( add(num1,num2) )

При запуске на этом коде flake8 сообщает, как и где именно нарушается стиль:

$ flake8 myscript.py myscript.py:1:9: E201 whitespace after '(' myscript.py:1:11: E231 missing whitespace after ',' myscript.py:1:13: E202 whitespace before ')' myscript.py:4:1: E305 expected 2 blank lines after class or function definition, found 1 myscript.py:4:5: E225 missing whitespace around operator myscript.py:5:5: E225 missing whitespace around operator myscript.py:6:7: E201 whitespace after '(' myscript.py:6:16: E231 missing whitespace after ',' myscript.py:6:22: E202 whitespace before ')'

В каждой выводимой строке flake8 сообщается, в каком файле и в какой строке проблема, в каком столбце строки начинается ошибка, номер ошибки и её описание. Используйте эти обозначения, flake8 можно настроить на игнорирование конкретных ошибок:

Как читать вывод flake8

Как читать вывод flake8

Для проверки качества кода с помощью flake8 вы даже можете настроить редакторы, например VS Code. Пока вы пишете код, он постоянно проверяется на нарушения PEP8. Когда обнаруживается проблема, во flake8 под частью кода с ошибкой появляется красная волнистая линия, найденные ошибки можно увидеть во вкладке встроенного терминала Problems:

Проверки flake8 в Visual Studio Code

Проверки flake8 в Visual Studio Code

flake8 — отличный инструмент для поиска связанных с нарушением PEP8 ошибок, но исправлять их придётся вручную. А значит, будет много работы. К счастью, весь процесс автоматизируемый. Автоматически форматировать код согласно PEP можно с помощью инструмента под названием Black.

Конечно, рекомендации PEP8 оставляют много возможностей для выбора стиля, и в black многие решения принимаются за вас. Вы можете соглашаться с ними или нет. Конфигурация black минимальна.

Установите black c помощью pip:

# Linux/macOS $ python3 -m pip install black # Windows $ python -m pip install black

После установки командой black —check можно посмотреть, будут ли black изменять файл:

$ black —check myscript.py would reformat myscript.py Oh no!

Introduction¶

pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

  • Features
  • Disclaimer
  • Installation
  • Example usage and output
  • Configuration
  • Error codes
  • Related tools

Features¶

  • Plugin architecture: Adding new checks is easy.
  • Parseable output: Jump to error location in your editor.
  • Small: Just one Python file, requires only stdlib. You can use just the pep8.py file for this purpose.
  • Comes with a comprehensive test suite.

Disclaimer¶

This utility does not enforce every single rule of PEP 8. It helps to verify that some coding conventions are applied but it does not intend to be exhaustive. Some rules cannot be expressed with a simple algorithm, and other rules are only guidelines which you could circumvent when you need to.

Always remember this statement from PEP 8:

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.

Among other things, these features are currently not in the scope of the pep8 library:

  • naming conventions: this kind of feature is supported through plugins. Install flake8 and the pep8-naming extension to use this feature.
  • docstring conventions: they are not in the scope of this library; see the pep257 project.
  • automatic fixing: see the section PEP8 Fixers in the related tools page.

Installation¶

You can install, upgrade, uninstall pep8.py with these commands:

$ pip install pep8 $ pip install --upgrade pep8 $ pip uninstall pep8

There’s also a package for Debian/Ubuntu, but it’s not always the latest version:

$ sudo apt-get install pep8

Example usage and output¶

$ pep8 --first optparse.py optparse.py:69:11: E401 multiple imports on one line optparse.py:77:1: E302 expected 2 blank lines, found 1 optparse.py:88:5: E301 expected 1 blank line, found 0 optparse.py:222:34: W602 deprecated form of raising exception optparse.py:347:31: E211 whitespace before '(' optparse.py:357:17: E201 whitespace after '

You can also make pep8.py show the source code for each error, and even the relevant text from PEP 8:

$ pep8 --show-source --show-pep8 testsuite/E40.py testsuite/E40.py:2:10: E401 multiple imports on one line import os, sys ^ Imports should usually be on separate lines. Okay: import os\nimport sys E401: import sys, os

Or you can display how often each error was found:

$ pep8 --statistics -qq Python-2.5/Lib 232 E201 whitespace after '[' 599 E202 whitespace before ')' 631 E203 whitespace before ',' 842 E211 whitespace before '(' 2531 E221 multiple spaces before operator 4473 E301 expected 1 blank line, found 0 4006 E302 expected 2 blank lines, found 1 165 E303 too many blank lines (4) 325 E401 multiple imports on one line 3615 E501 line too long (82 characters) 612 W601 .has_key() is deprecated, use 'in' 1188 W602 deprecated form of raising exception

You can also make pep8.py show the error text in different formats by using –format having options default/pylint/custom:

$ pep8 testsuite/E40.py --format=default testsuite/E40.py:2:10: E401 multiple imports on one line $ pep8 testsuite/E40.py --format=pylint testsuite/E40.py:2: [E401] multiple imports on one line $ pep8 testsuite/E40.py --format='%(path)s|%(row)d|%(col)d| %(code)s %(text)s' testsuite/E40.py|2|10| E401 multiple imports on one line

Variables in the custom format option

Variable Significance
path File name
row Row number
col Column number
code Error code
text Error text

Quick help is available on the command line:

$ pep8 -h Usage: pep8 [options] input . Options: --version show program's version number and exit -h, --help show this help message and exit -v, --verbose print status messages, or debug with -vv -q, --quiet report only file names, or nothing with -qq --first show first occurrence of each error --exclude=patterns exclude files or directories which match these comma separated patterns (default: .svn,CVS,.bzr,.hg,.git) --filename=patterns when parsing directories, only check filenames matching these comma separated patterns (default: *.py) --select=errors select errors and warnings (e.g. E,W6) --ignore=errors skip errors and warnings (e.g. E4,W) --show-source show source code for each error --show-pep8 show text of PEP 8 for each error (implies --first) --statistics count errors and warnings --count print total number of errors and warnings to standard error and set exit code to 1 if total is not null --max-line-length=n set maximum allowed line length (default: 79) --hang-closing hang closing bracket instead of matching indentation of opening bracket's line --format=format set the error format [default|pylint|] --diff report only lines changed according to the unified diff received on STDIN Testing Options: --benchmark measure processing speed Configuration: The project options are read from the [pep8] section of the tox.ini file or the setup.cfg file located in any parent folder of the path(s) being processed. Allowed options are: exclude, filename, select, ignore, max-line-length, hang-closing, count, format, quiet, show-pep8, show-source, statistics, verbose. --config=path user config file location (default: ~/.config/pep8)

Configuration¶

The behaviour may be configured at two levels, the user and project levels.

At the user level, settings are read from the following locations:

If on Windows: ~\.pep8 Otherwise, if the XDG_CONFIG_HOME environment variable is defined: XDG_CONFIG_HOME/pep8 Else if XDG_CONFIG_HOME is not defined: ~/.config/pep8

[pep8] ignore = E226,E302,E41 max-line-length = 160 

At the project level, a setup.cfg file or a tox.ini file is read if present ( .pep8 file is also supported, but it is deprecated). If none of these files have a [pep8] section, no project specific configuration is loaded.

Error codes¶

This is the current list of error and warning codes:

code sample message
E1 Indentation
E101 indentation contains mixed spaces and tabs
E111 indentation is not a multiple of four
E112 expected an indented block
E113 unexpected indentation
E114 indentation is not a multiple of four (comment)
E115 expected an indented block (comment)
E116 unexpected indentation (comment)
E121 (*^) continuation line under-indented for hanging indent
E122 (^) continuation line missing indentation or outdented
E123 (*) closing bracket does not match indentation of opening bracket’s line
E124 (^) closing bracket does not match visual indentation
E125 (^) continuation line with same indent as next logical line
E126 (*^) continuation line over-indented for hanging indent
E127 (^) continuation line over-indented for visual indent
E128 (^) continuation line under-indented for visual indent
E129 (^) visually indented line with same indent as next logical line
E131 (^) continuation line unaligned for hanging indent
E133 (*) closing bracket is missing indentation
E2 Whitespace
E201 whitespace after ‘(‘
E202 whitespace before ‘)’
E203 whitespace before ‘:’
E211 whitespace before ‘(‘
E221 multiple spaces before operator
E222 multiple spaces after operator
E223 tab before operator
E224 tab after operator
E225 missing whitespace around operator
E226 (*) missing whitespace around arithmetic operator
E227 missing whitespace around bitwise or shift operator
E228 missing whitespace around modulo operator
E231 missing whitespace after ‘,’, ‘;’, or ‘:’
E241 (*) multiple spaces after ‘,’
E242 (*) tab after ‘,’
E251 unexpected spaces around keyword / parameter equals
E261 at least two spaces before inline comment
E262 inline comment should start with ‘# ‘
E265 block comment should start with ‘# ‘
E266 too many leading ‘#’ for block comment
E271 multiple spaces after keyword
E272 multiple spaces before keyword
E273 tab after keyword
E274 tab before keyword
E3 Blank line
E301 expected 1 blank line, found 0
E302 expected 2 blank lines, found 0
E303 too many blank lines (3)
E304 blank lines found after function decorator
E4 Import
E401 multiple imports on one line
E402 module level import not at top of file
E5 Line length
E501 (^) line too long (82 > 79 characters)
E502 the backslash is redundant between brackets
E7 Statement
E701 multiple statements on one line (colon)
E702 multiple statements on one line (semicolon)
E703 statement ends with a semicolon
E704 (*) multiple statements on one line (def)
E711 (^) comparison to None should be ‘if cond is None:’
E712 (^) comparison to True should be ‘if cond is True:’ or ‘if cond:’
E713 test for membership should be ‘not in’
E714 test for object identity should be ‘is not’
E721 (^) do not compare types, use ‘isinstance()’
E731 do not assign a lambda expression, use a def
E9 Runtime
E901 SyntaxError or IndentationError
E902 IOError
W1 Indentation warning
W191 indentation contains tabs
W2 Whitespace warning
W291 trailing whitespace
W292 no newline at end of file
W293 blank line contains whitespace
W3 Blank line warning
W391 blank line at end of file
W5 Line break warning
W503 line break occurred before a binary operator
W6 Deprecation warning
W601 .has_key() is deprecated, use ‘in’
W602 deprecated form of raising exception
W603 ‘<>’ is deprecated, use ‘!=’
W604 backticks are deprecated, use ‘repr()’

(*) In the default configuration, the checks E121, E123, E126, E133, E226, E241, E242 and E704 are ignored because they are not rules unanimously accepted, and PEP 8 does not enforce them. The check E133 is mutually exclusive with check E123. Use switch --hang- closing to report E133 instead of E123.

(^) These checks can be disabled at the line level using the # noqa special comment. This possibility should be reserved for special cases.

Special cases aren’t special enough to break the rules.

Note: most errors can be listed with such one-liner:

$ python pep8.py --first --select E,W testsuite/ --format '%(code)s: %(text)s'

Related tools¶

The flake8 checker is a wrapper around pep8 and similar tools. It supports plugins.

Other tools which use pep8 are referenced in the Wiki: list of related tools.

© Copyright 2006-2016, Johann C. Rocholl, Florent Xicluna, Ian Lee. Revision 45f79c71 .

Built with Sphinx using a theme provided by Read the Docs.
Read the Docs v: release-1.7.x

Versions latest stable 1.7.0 release-1.7.x Downloads pdf htmlzip epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *