Skip to content

Commit 264b2c9

Browse files
authored
Switch Code Formatting to Black (python-telegram-bot#2122)
* Swtich code formatting to Black * Update docs * Fix tests * TRy fixing pre-commit
1 parent 8efb052 commit 264b2c9

237 files changed

Lines changed: 9454 additions & 5907 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.github/CONTRIBUTING.rst

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,14 @@ Here's how to make a one-off code change.
9191
9292
Once the process terminates, you can view the built documentation by opening ``docs/build/html/index.html`` with a browser.
9393

94-
- For consistency, please conform to `Google Python Style Guide`_ and `Google Python Style Docstrings`_. In addition, code should be formatted consistently with other code around it.
94+
- For consistency, please conform to `Google Python Style Guide`_ and `Google Python Style Docstrings`_.
9595

9696
- The following exceptions to the above (Google's) style guides applies:
9797

9898
- Documenting types of global variables and complex types of class members can be done using the Sphinx docstring convention.
9999

100+
- In addition, PTB uses the `Black`_ coder formatting. Plugins for Black exist for some `popular editors`_. You can use those instead of manually formatting everything.
101+
100102
- Please ensure that the code you write is well-tested.
101103

102104
- Don’t break backward compatibility.
@@ -189,11 +191,6 @@ Here's how to make a one-off code change.
189191
Style commandments
190192
------------------
191193

192-
Specific commandments
193-
#####################
194-
195-
- Avoid using "double quotes" where you can reasonably use 'single quotes'.
196-
197194
Assert comparison order
198195
#######################
199196

@@ -255,3 +252,5 @@ break the API classes. For example:
255252
.. _AUTHORS.rst: ../AUTHORS.rst
256253
.. _`MyPy`: https://mypy.readthedocs.io/en/stable/index.html
257254
.. _`here`: https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
255+
.. _`Black`: https://black.readthedocs.io/en/stable/index.html
256+
.. _`popular editors`: https://black.readthedocs.io/en/stable/editor_integration.html

.pre-commit-config.yaml

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
repos:
2-
- repo: git://github.com/python-telegram-bot/mirrors-yapf
3-
rev: 5769e088ef6e0a0d1eb63bd6d0c1fe9f3606d6c8
2+
- repo: https://github.com/psf/black
3+
rev: 20.8b1
44
hooks:
5-
- id: yapf
6-
files: ^(telegram|tests)/.*\.py$
5+
- id: black
76
args:
87
- --diff
98
- repo: https://gitlab.com/pycqa/flake8

README.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ We have a vibrant community of developers helping each other in our `Telegram gr
4545
:target: https://www.codacy.com/app/python-telegram-bot/python-telegram-bot?utm_source=github.com&utm_medium=referral&utm_content=python-telegram-bot/python-telegram-bot&utm_campaign=Badge_Grade
4646
:alt: Code quality
4747

48+
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
49+
:target: https://github.com/psf/black
50+
4851
.. image:: https://img.shields.io/badge/Telegram-Group-blue.svg
4952
:target: https://telegram.me/pythontelegrambotgroup
5053
:alt: Telegram Group

examples/conversationbot.py

Lines changed: 37 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@
1616

1717
import logging
1818

19-
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
20-
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
21-
ConversationHandler)
19+
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove
20+
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler
2221

2322
# Enable logging
24-
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25-
level=logging.INFO)
23+
logging.basicConfig(
24+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
25+
)
2626

2727
logger = logging.getLogger(__name__)
2828

@@ -36,17 +36,20 @@ def start(update, context):
3636
'Hi! My name is Professor Bot. I will hold a conversation with you. '
3737
'Send /cancel to stop talking to me.\n\n'
3838
'Are you a boy or a girl?',
39-
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
39+
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True),
40+
)
4041

4142
return GENDER
4243

4344

4445
def gender(update, context):
4546
user = update.message.from_user
4647
logger.info("Gender of %s: %s", user.first_name, update.message.text)
47-
update.message.reply_text('I see! Please send me a photo of yourself, '
48-
'so I know what you look like, or send /skip if you don\'t want to.',
49-
reply_markup=ReplyKeyboardRemove())
48+
update.message.reply_text(
49+
'I see! Please send me a photo of yourself, '
50+
'so I know what you look like, or send /skip if you don\'t want to.',
51+
reply_markup=ReplyKeyboardRemove(),
52+
)
5053

5154
return PHOTO
5255

@@ -56,37 +59,42 @@ def photo(update, context):
5659
photo_file = update.message.photo[-1].get_file()
5760
photo_file.download('user_photo.jpg')
5861
logger.info("Photo of %s: %s", user.first_name, 'user_photo.jpg')
59-
update.message.reply_text('Gorgeous! Now, send me your location please, '
60-
'or send /skip if you don\'t want to.')
62+
update.message.reply_text(
63+
'Gorgeous! Now, send me your location please, ' 'or send /skip if you don\'t want to.'
64+
)
6165

6266
return LOCATION
6367

6468

6569
def skip_photo(update, context):
6670
user = update.message.from_user
6771
logger.info("User %s did not send a photo.", user.first_name)
68-
update.message.reply_text('I bet you look great! Now, send me your location please, '
69-
'or send /skip.')
72+
update.message.reply_text(
73+
'I bet you look great! Now, send me your location please, ' 'or send /skip.'
74+
)
7075

7176
return LOCATION
7277

7378

7479
def location(update, context):
7580
user = update.message.from_user
7681
user_location = update.message.location
77-
logger.info("Location of %s: %f / %f", user.first_name, user_location.latitude,
78-
user_location.longitude)
79-
update.message.reply_text('Maybe I can visit you sometime! '
80-
'At last, tell me something about yourself.')
82+
logger.info(
83+
"Location of %s: %f / %f", user.first_name, user_location.latitude, user_location.longitude
84+
)
85+
update.message.reply_text(
86+
'Maybe I can visit you sometime! ' 'At last, tell me something about yourself.'
87+
)
8188

8289
return BIO
8390

8491

8592
def skip_location(update, context):
8693
user = update.message.from_user
8794
logger.info("User %s did not send a location.", user.first_name)
88-
update.message.reply_text('You seem a bit paranoid! '
89-
'At last, tell me something about yourself.')
95+
update.message.reply_text(
96+
'You seem a bit paranoid! ' 'At last, tell me something about yourself.'
97+
)
9098

9199
return BIO
92100

@@ -102,8 +110,9 @@ def bio(update, context):
102110
def cancel(update, context):
103111
user = update.message.from_user
104112
logger.info("User %s canceled the conversation.", user.first_name)
105-
update.message.reply_text('Bye! I hope we can talk again some day.',
106-
reply_markup=ReplyKeyboardRemove())
113+
update.message.reply_text(
114+
'Bye! I hope we can talk again some day.', reply_markup=ReplyKeyboardRemove()
115+
)
107116

108117
return ConversationHandler.END
109118

@@ -120,20 +129,16 @@ def main():
120129
# Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
121130
conv_handler = ConversationHandler(
122131
entry_points=[CommandHandler('start', start)],
123-
124132
states={
125133
GENDER: [MessageHandler(Filters.regex('^(Boy|Girl|Other)$'), gender)],
126-
127-
PHOTO: [MessageHandler(Filters.photo, photo),
128-
CommandHandler('skip', skip_photo)],
129-
130-
LOCATION: [MessageHandler(Filters.location, location),
131-
CommandHandler('skip', skip_location)],
132-
133-
BIO: [MessageHandler(Filters.text & ~Filters.command, bio)]
134+
PHOTO: [MessageHandler(Filters.photo, photo), CommandHandler('skip', skip_photo)],
135+
LOCATION: [
136+
MessageHandler(Filters.location, location),
137+
CommandHandler('skip', skip_location),
138+
],
139+
BIO: [MessageHandler(Filters.text & ~Filters.command, bio)],
134140
},
135-
136-
fallbacks=[CommandHandler('cancel', cancel)]
141+
fallbacks=[CommandHandler('cancel', cancel)],
137142
)
138143

139144
dp.add_handler(conv_handler)

examples/conversationbot2.py

Lines changed: 41 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,22 @@
1717
import logging
1818

1919
from telegram import ReplyKeyboardMarkup
20-
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
21-
ConversationHandler)
20+
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler
2221

2322
# Enable logging
24-
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25-
level=logging.INFO)
23+
logging.basicConfig(
24+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
25+
)
2626

2727
logger = logging.getLogger(__name__)
2828

2929
CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)
3030

31-
reply_keyboard = [['Age', 'Favourite colour'],
32-
['Number of siblings', 'Something else...'],
33-
['Done']]
31+
reply_keyboard = [
32+
['Age', 'Favourite colour'],
33+
['Number of siblings', 'Something else...'],
34+
['Done'],
35+
]
3436
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
3537

3638

@@ -47,7 +49,8 @@ def start(update, context):
4749
update.message.reply_text(
4850
"Hi! My name is Doctor Botter. I will hold a more complex conversation with you. "
4951
"Why don't you tell me something about yourself?",
50-
reply_markup=markup)
52+
reply_markup=markup,
53+
)
5154

5255
return CHOOSING
5356

@@ -56,14 +59,16 @@ def regular_choice(update, context):
5659
text = update.message.text
5760
context.user_data['choice'] = text
5861
update.message.reply_text(
59-
'Your {}? Yes, I would love to hear about that!'.format(text.lower()))
62+
'Your {}? Yes, I would love to hear about that!'.format(text.lower())
63+
)
6064

6165
return TYPING_REPLY
6266

6367

6468
def custom_choice(update, context):
65-
update.message.reply_text('Alright, please send me the category first, '
66-
'for example "Most impressive skill"')
69+
update.message.reply_text(
70+
'Alright, please send me the category first, ' 'for example "Most impressive skill"'
71+
)
6772

6873
return TYPING_CHOICE
6974

@@ -75,10 +80,12 @@ def received_information(update, context):
7580
user_data[category] = text
7681
del user_data['choice']
7782

78-
update.message.reply_text("Neat! Just so you know, this is what you already told me:"
79-
"{} You can tell me more, or change your opinion"
80-
" on something.".format(facts_to_str(user_data)),
81-
reply_markup=markup)
83+
update.message.reply_text(
84+
"Neat! Just so you know, this is what you already told me:"
85+
"{} You can tell me more, or change your opinion"
86+
" on something.".format(facts_to_str(user_data)),
87+
reply_markup=markup,
88+
)
8289

8390
return CHOOSING
8491

@@ -88,9 +95,9 @@ def done(update, context):
8895
if 'choice' in user_data:
8996
del user_data['choice']
9097

91-
update.message.reply_text("I learned these facts about you:"
92-
"{}"
93-
"Until next time!".format(facts_to_str(user_data)))
98+
update.message.reply_text(
99+
"I learned these facts about you:" "{}" "Until next time!".format(facts_to_str(user_data))
100+
)
94101

95102
user_data.clear()
96103
return ConversationHandler.END
@@ -108,24 +115,26 @@ def main():
108115
# Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
109116
conv_handler = ConversationHandler(
110117
entry_points=[CommandHandler('start', start)],
111-
112118
states={
113-
CHOOSING: [MessageHandler(Filters.regex('^(Age|Favourite colour|Number of siblings)$'),
114-
regular_choice),
115-
MessageHandler(Filters.regex('^Something else...$'),
116-
custom_choice)
117-
],
118-
119+
CHOOSING: [
120+
MessageHandler(
121+
Filters.regex('^(Age|Favourite colour|Number of siblings)$'), regular_choice
122+
),
123+
MessageHandler(Filters.regex('^Something else...$'), custom_choice),
124+
],
119125
TYPING_CHOICE: [
120-
MessageHandler(Filters.text & ~(Filters.command | Filters.regex('^Done$')),
121-
regular_choice)],
122-
126+
MessageHandler(
127+
Filters.text & ~(Filters.command | Filters.regex('^Done$')), regular_choice
128+
)
129+
],
123130
TYPING_REPLY: [
124-
MessageHandler(Filters.text & ~(Filters.command | Filters.regex('^Done$')),
125-
received_information)],
131+
MessageHandler(
132+
Filters.text & ~(Filters.command | Filters.regex('^Done$')),
133+
received_information,
134+
)
135+
],
126136
},
127-
128-
fallbacks=[MessageHandler(Filters.regex('^Done$'), done)]
137+
fallbacks=[MessageHandler(Filters.regex('^Done$'), done)],
129138
)
130139

131140
dp.add_handler(conv_handler)

examples/deeplinking.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,9 @@
2525
# Enable logging
2626
from telegram.utils import helpers
2727

28-
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
29-
level=logging.INFO)
28+
logging.basicConfig(
29+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
30+
)
3031

3132
logger = logging.getLogger(__name__)
3233

@@ -48,8 +49,10 @@ def deep_linked_level_1(update, context):
4849
"""Reached through the CHECK_THIS_OUT payload"""
4950
bot = context.bot
5051
url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL)
51-
text = "Awesome, you just accessed hidden functionality! " \
52-
" Now let's get back to the private chat."
52+
text = (
53+
"Awesome, you just accessed hidden functionality! "
54+
" Now let's get back to the private chat."
55+
)
5356
keyboard = InlineKeyboardMarkup.from_button(
5457
InlineKeyboardButton(text='Continue here!', url=url)
5558
)
@@ -60,16 +63,16 @@ def deep_linked_level_2(update, context):
6063
"""Reached through the SO_COOL payload"""
6164
bot = context.bot
6265
url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES)
63-
text = "You can also mask the deep-linked URLs as links: " \
64-
"[▶️ CLICK HERE]({}).".format(url)
66+
text = "You can also mask the deep-linked URLs as links: " "[▶️ CLICK HERE]({}).".format(url)
6567
update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
6668

6769

6870
def deep_linked_level_3(update, context):
6971
"""Reached through the USING_ENTITIES payload"""
7072
payload = context.args
71-
update.message.reply_text("Congratulations! This is as deep as it gets 👏🏻\n\n"
72-
"The payload was: {}".format(payload))
73+
update.message.reply_text(
74+
"Congratulations! This is as deep as it gets 👏🏻\n\n" "The payload was: {}".format(payload)
75+
)
7376

7477

7578
def main():
@@ -90,10 +93,9 @@ def main():
9093
dp.add_handler(CommandHandler("start", deep_linked_level_2, Filters.regex(SO_COOL)))
9194

9295
# We can also pass on the deep-linking payload
93-
dp.add_handler(CommandHandler("start",
94-
deep_linked_level_3,
95-
Filters.regex(USING_ENTITIES),
96-
pass_args=True))
96+
dp.add_handler(
97+
CommandHandler("start", deep_linked_level_3, Filters.regex(USING_ENTITIES), pass_args=True)
98+
)
9799

98100
# Make sure the deep-linking handlers occur *before* the normal /start handler.
99101
dp.add_handler(CommandHandler("start", start))

examples/echobot.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@
2020
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
2121

2222
# Enable logging
23-
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
24-
level=logging.INFO)
23+
logging.basicConfig(
24+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
25+
)
2526

2627
logger = logging.getLogger(__name__)
2728

0 commit comments

Comments
 (0)