Code should have consistent indentation, typically spaced out in increments of two or four.
Anti-pattern
The print function on the following line is indented at five spaces instead of four.
if True:
print('Hi there')
Best practice
The code is now spaced out at four spaces instead of five.
if True:
print('Hi there')
Additional links
- https://www.python.org/dev/peps/pep-0008/#indentation
This happened to me when using pycodestyle 2.5.0.
Instruction to reproduce:
- Create a script test.py with the following contents:
def a(b):
return b # indented with tab
- Run
pycodestyle --show-source --show-pep8 test.py - Output obtained:
test.py:2:1: W191 indentation contains tabs
return b
^
On new projects, spaces-only are strongly recommended over tabs.
Okay: if True:n return
W191: if True:ntreturn
test.py:2:2: E117 over-indented
return b
^
Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue
to use 8-space tabs.
Okay: a = 1
Okay: if a == 0:n a = 1
E111: a = 1
E114: # a = 1
Okay: for item in items:n pass
E112: for item in items:npass
E115: for item in items:n# Hin pass
Okay: a = 1nb = 2
E113: a = 1n b = 2
E116: a = 1n # b = 2
I’m currently ignoring E117 as a workaround, which can mask actual E117 errors.
That’s mostly a matter of tab historycally being used to indent by 8. The only way to make this work «properly» would be to add an option for what a tab should be expanded into, imo.
My comment from #837:
PEP8 says:
Use 4 spaces per indentation level.
If a tab is used as indentation (my preference), it should be assumed to have a tabwidth of 4 by default.
If other codebases are using other tabwidths (8 and 2 are probably the most common alternatives), then it might make more sense to add a config option to allow customizing tabwidth rather than having the default divert that far from PEP8.
(Note also the existence of
flake8-tabs.)
this is fixed on master:
$ python -m pycodestyle t.py --ignore=W191
$
@GPHemsley the standard width of a tab is 8 btw
@asottile There is no «standard» width of a tab. The default width of a tab differs depending on what domain it appears in. In the domain of programming, most IDEs allow tab size to be configured by the user (or the file).
But we’re not talking about broader culture here; we’re talking about Python code styling. (We could argue about which size is better in other domains, but that would be off-topic.)
As I said above, in the domain of Python code styling, I think having the default size match the Python indentation size (4) would be best, with a configuration option allowing that to be overridden.
I also think it’s important to distinguish between indentation using a combination of tabs and spaces (always bad) and indentation using only tabs (likely programmer preference).
python treats a tab as 8 spaces (try in python2), so yes there is a standard width in python
I also think it’s important to distinguish between indentation using a combination of tabs and spaces (always bad) and indentation using only tabs (likely programmer preference).
Believe it or not, there’s a better reason than «programmer preference» to prefer always using tabs; Accessibility and screen readers. Tabs are better for programmers who either have to verbally dictate code or rely on a screen reader to read it back to them.
I also think it’s important to distinguish between indentation using a combination of tabs and spaces (always bad) and indentation using only tabs (likely programmer preference).
Believe it or not, there’s a better reason than «programmer preference» to prefer always using tabs; Accessibility and screen readers. Tabs are better for programmers who either have to verbally dictate code or rely on a screen reader to read it back to them.
Indeed. I should have said that indentation using only tabs would be «likely an active decision on the part of the programmer».
closing given the fix on master
closing given the fix on master
Can you please point to the fix on (which) master so we know when it is fixed? Many thanks!
here’s how I found the answer to that, I’m not sure why this wasn’t linked as a duplicate of #836
here’s the commands I ran to figure this out. First I wanted to figure out what commit fixed this issue.
git bisect start # these are backwards because we "fixed" it instead of introducing a regression # which is the "normal" use for `git bisect` git bisect good 2.5.0 git bisect bad HEAD git bisect run bash -c '! python3 -m pycodestyle t.py --ignore=W191'
and that ends up with this:
$ git bisect run bash -c '! python -m pycodestyle t.py --ignore=W191' running bash -c ! python -m pycodestyle t.py --ignore=W191 Bisecting: 13 revisions left to test after this (roughly 4 steps) [e5cdc22a29bf0c4abe30c152f81124e4b7a5dad7] Add lines breaks running bash -c ! python -m pycodestyle t.py --ignore=W191 Bisecting: 6 revisions left to test after this (roughly 3 steps) [a5488e2817637eca9def0be4b329566a1ed0f231] Merge pull request #848 from adamchainz/tox_url running bash -c ! python -m pycodestyle t.py --ignore=W191 Bisecting: 2 revisions left to test after this (roughly 2 steps) [dd1d313152a136f80c9ac3d508d2d99d6b3dc0a8] Expect lines to be indented 8 places when tabs are used running bash -c ! python -m pycodestyle t.py --ignore=W191 Bisecting: 0 revisions left to test after this (roughly 1 step) [ac1c5e579c840e20544e9d65dbcebc1ecd9bf796] Merge pull request #832 from asottile/patch-1 running bash -c ! python -m pycodestyle t.py --ignore=W191 t.py:2:2: E117 over-indented dd1d313152a136f80c9ac3d508d2d99d6b3dc0a8 is the first bad commit commit dd1d313152a136f80c9ac3d508d2d99d6b3dc0a8 Author: Jon Dufresne <jon.dufresne@gmail.com> Date: Thu Jan 31 16:38:31 2019 -0800 Expect lines to be indented 8 places when tabs are used Fixes #836 pycodestyle.py | 8 +++++--- testsuite/E10.py | 4 ++-- testsuite/E11.py | 3 +++ testsuite/E90.py | 2 +- testsuite/W19.py | 38 +++++++++++++++++++------------------- testsuite/test_api.py | 4 ++-- testsuite/test_shell.py | 2 +- 7 files changed, 33 insertions(+), 28 deletions(-) bisect run success
so then we want to see when that commit got released, we use the following command:
$ git describe --contains dd1d313152a136f80c9ac3d508d2d99d6b3dc0a8 2.6.0a1~18^2
so that says that this was integrated 18 commits before 2.6.0a1 was released, meaning any version after that will contain it
Good afternoon, I decided to try creating a Telegram keyword search bot for the first time. Found a ready-made script, but I can not debug it. Constantly gives out all sorts of errors. I have debugged most of them. I have only a few bugs left but I do not know how to fix them:
- Local variable ‘channel_title’ value is not used:71.
- PEP 8: E117 over-indented:68
- Parameter ‘text’ unfilled:77
- Expected type ‘EventBuilder’, got ‘Type[NewMessage]’ instead:65
- Parameter ‘text’ unfilled:59
- Expected type ‘EventBuilder’, got ‘Type[NewMessage]’ instead:43
- Unused import statement ‘from telethon.sessions import StringSession’:10
- Unused import statement ‘from telethon.tl.types import ChannelParticipantsSearch’:9
- Unused import statement ‘from telethon.tl.functions.channels import GetParticipantsRequest’:8
- Unused import statement ‘from telethon.tl.functions.messages import GetHistoryRequest’:7
- Unused import statement ‘from telethon.tl.types import InputPeerEmpty’:6
- Unused import statement ‘from telethon.tl.functions.messages import GetDialogsRequest’:5
The following errors are displayed at startup:
C:UsersАндрейPycharmProjectsnew1venvScriptspython.exe C:UsersАндрейPycharmProjectsnew1main.py
Goodbye!
Traceback (most recent call last):
File "C:UsersАндрейPycharmProjectsnew1main.py", line 36, in <module>
client.start()
File "C:UsersАндрейPycharmProjectsnew1venvlibsite-packagestelethonclientauth.py", line 128, in start
else self.loop.run_until_complete(coro)
File "C:UsersАндрейAppDataLocalProgramsPythonPython310Libasynciobase_events.py", line 649, in run_until_complete
return future.result()
File "C:UsersАндрейPycharmProjectsnew1venvlibsite-packagestelethonclientauth.py", line 165, in _start
value = phone()
File "C:UsersАндрейPycharmProjectsnew1venvlibsite-packagestelethonclientauth.py", line 22, in <lambda>
phone: typing.Callable[[], str] = lambda: input('Please enter your phone (or bot token): '),
File "C:UsersАндрейAppDataLocalProgramsPythonPython310Libcodecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Please enter your phone (or bot token):
Process finished with exit code -1073741819 (0xC0000005)
The code:
from telethon.sync import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon import events
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch
from telethon.sessions import StringSession
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
import hashlib
import re
import redis
bot = Bot(token='6159673080:AAEO5cLmq_', parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot)
if __name__ == '__main__':
executor.start_polling(dp)
conn = redis.Redis(host='localhost', port=6379, db=2, charset="utf-8", decode_responses=True)
TRIGGER = ['создать бота', 'нужен бот', 'сделать бота', 'сделать чат-бот', 'нужен кодер', 'нужен программист',
'нужен прогер', 'написать бот', 'кто делает бот', 'кто сделает бот', 'пишет бот', 'создаст бота']
hash_object = []
string_session = '' # тут должен быть ключ стринг сессии, если вы используете ее
ID = 5815 # ваше id, куда бот будет скидывать вам ссылки на найденные сообщения
# client = TelegramClient(StringSession(string_session), 2496 , "8da85b0d5bfe62527e5b244c209159c3",
# flood_sleep_threshold = 0) # способ авторизации с помощью ключа типа строка
client = TelegramClient('my_account_session', 2496, "8da85b0d5bfe62527e5b244c209159c3",
flood_sleep_threshold=0) # способ авторизации с помощью файлы сессии
client.start()
# print('String Session = ', client.session.save())
# получение ключа типа string_session, который надо вставить в переменную string_session
@client.on(events.NewMessage) # апдейт на новые сообщения только из групп
async def hahdler_group(event):
if event.is_group is True:
r = re.compile("|".join(TRIGGER), flags=re.I)
list_count = r.findall(event.raw_text)
if len(list_count) >= 1:
if conn.get(event.from_id.user_id) is None:
# чтобы не было повторов от одного id в разных группых в течении 200 сек
if not hashlib.md5(
str(str(event.from_id.user_id) + event.raw_text).encode()).hexdigest() in hash_object:
# проверяем дубилрование сообщений от одного юзера
out = ''.join(list_count)
await Bot.send_message(id, "Триггер сработал на <b>" + str(list_count) + "</b>nТекст сообщения: "
+ str(event.raw_text.replace(out, "<b>" + out + "</b>"))
+ "nСсылка на сообщение: <i>t.me/c/"
+ str(event.peer_id.channel_id) + "/" + str(event.message.id) + "</i>",
disable_web_page_preview=True)
conn.set(event.from_id.user_id, 1, ex=200)
hash_object.append(hashlib.md5(str(str(event.from_id.user_id)
+ event.raw_text).encode()).hexdigest())
@client.on(events.NewMessage) # апдейт на новые сообщения только из каналов
async def hahdler_chanell(event):
if not event.is_group and not event.is_private:
r = re.compile("|".join(TRIGGER), flags=re.I)
list_count = r.findall(event.raw_text)
if len(list_count) >= 1:
channel_title = await client.get_entity(event.peer_id.channel_id)
out = ''.join(list_count)
await Bot.send_message(id, "Триггер сработал на <b>" + str(list_count) + "</b>nТекст сообщения: "
+ str(event.raw_text.replace(out, "<b>" + out + "</b>"))
+ "nСсылка на сообщение: <i>t.me/c/"
+ str(event.peer_id.channel_id) + "/" + str(event.message.id) + " </i>",
disable_web_page_preview=True)
client.run_until_disconnected()
Don’t judge too harshly, this is my first time doing this and I would like some help in figuring out what I’m doing wrong.
Power went out, then pycharm acted like it was running for the first time. I have set up the editor to use tabs with python, but at the start of every indented block I get a squiggly with the message:
Pep 8 over-indented
I’m not indenting with any spaces, only tabs. Same projects didn’t complain before. Now all files have this problem.
Chose the ‘reformat file’ option, but the problem persists. I made sure that the project and IDE profiles python options were set to use tabs, widths 4, 4, 4.
Thanks for any help!
|
milwey 0 / 0 / 0 Регистрация: 26.10.2021 Сообщений: 14 |
||||
|
1 |
||||
В чем здесь ошибка, не понимаю03.11.2021, 15:40. Показов 6990. Ответов 11 Метки нет (Все метки)
Ошибка оформления кода. stdout: stderr:
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
03.11.2021, 15:40 |
|
Ответы с готовыми решениями: Не понимаю в чём здесь ошибка, Python Нашел код и не понимаю, где здесь ошибка В чем здесь ошибка? В чём здесь ошибка? int main() 11 |
|
4629 / 3165 / 1116 Регистрация: 21.03.2016 Сообщений: 7,861 |
|
|
03.11.2021, 17:34 |
2 |
|
а что в вашей портянке можно понять??? выделить и по скринам действовать
3 |
|
milwey 0 / 0 / 0 Регистрация: 26.10.2021 Сообщений: 14 |
||||
|
03.11.2021, 20:06 [ТС] |
3 |
|||
0 |
|
Status 418
3891 / 2167 / 576 Регистрация: 26.11.2017 Сообщений: 5,051 Записей в блоге: 2 |
|
|
03.11.2021, 20:11 |
4 |
|
Semen-Semenich, теперь отступам придется учить
1 |
|
0 / 0 / 0 Регистрация: 26.10.2021 Сообщений: 14 |
|
|
03.11.2021, 20:19 [ТС] |
5 |
|
там после «:» должно быть четыре пробела. stdout: stderr:
0 |
|
4688 / 2553 / 535 Регистрация: 07.11.2019 Сообщений: 4,224 |
|
|
03.11.2021, 20:21 |
6 |
|
milwey, отступы сделай!
0 |
|
0 / 0 / 0 Регистрация: 26.10.2021 Сообщений: 14 |
|
|
03.11.2021, 20:27 [ТС] |
7 |
|
Вот такая задача: Вывод Добавлено через 1 минуту
0 |
|
4688 / 2553 / 535 Регистрация: 07.11.2019 Сообщений: 4,224 |
|
|
03.11.2021, 20:27 |
8 |
|
milwey, пробелами, как и в редакторе кода.
1 |
|
milwey 0 / 0 / 0 Регистрация: 26.10.2021 Сообщений: 14 |
||||
|
03.11.2021, 20:40 [ТС] |
9 |
|||
Добавлено через 3 минуты stdout: stderr: Я не знаю, как ее исправить
0 |
|
4688 / 2553 / 535 Регистрация: 07.11.2019 Сообщений: 4,224 |
|
|
03.11.2021, 20:48 |
10 |
|
milwey, тебе пишет ошибку, что проблемы с отступами. Исправь отступами (пробелами). Почитай про форматирование кода в Python отступами, если проблемы с пониманием.
0 |
|
Модератор
35725 / 19608 / 4119 Регистрация: 12.02.2012 Сообщений: 32,671 Записей в блоге: 13 |
|
|
04.11.2021, 08:18 |
11 |
|
milwey, пока не научишься правильно расставлять тэги — не трогай Питон!
1 |
|
Автоматизируй это!
7138 / 4434 / 1185 Регистрация: 30.03.2015 Сообщений: 12,898 Записей в блоге: 29 |
|
|
04.11.2021, 09:45 |
12 |
|
пока не научишься правильно расставлять тэги — не трогай Питон! отлить в граните!
1 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
04.11.2021, 09:45 |
|
Помогаю со студенческими работами здесь В чем здесь ошибка? public static void main(String args) В чем здесь ошибка? В чём здесь ошибка? #include "stdafx.h" В чем здесь ошибка ? В чём здесь ошибка? В чем здесь ошибка? В чем здесь ошибка? Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 12 |




