python: Fix PAR001 Redundant parentheses.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2023-11-11 12:09:07 -08:00
parent aeb89bcae5
commit 059458b4ca
21 changed files with 29 additions and 41 deletions

View file

@ -36,17 +36,6 @@ python_rules = RuleList(
"good_lines": ["def foo (self):"], "good_lines": ["def foo (self):"],
"bad_lines": ["def foo(self: Any):"], "bad_lines": ["def foo(self: Any):"],
}, },
# This next check could have false positives, but it seems pretty
# rare; if we find any, they can be added to the exclude list for
# this rule.
{
"pattern": r" % [a-zA-Z0-9_.]*\)?$",
"description": "Used % comprehension without a tuple",
},
{
"pattern": r".*%s.* % \([a-zA-Z0-9_.]*\)$",
"description": "Used % comprehension without a tuple",
},
{ {
"pattern": r"__future__", "pattern": r"__future__",
"include_only": {"zulip_bots/zulip_bots/bots/"}, "include_only": {"zulip_bots/zulip_bots/bots/"},

View file

@ -43,7 +43,7 @@ the Python version this command is executed with."""
py_version = tuple(int(num) for num in py_version_list[0:2]) py_version = tuple(int(num) for num in py_version_list[0:2])
venv_name = f"zulip-api-py{py_version[0]}-venv" venv_name = f"zulip-api-py{py_version[0]}-venv"
if py_version <= (3, 1) and (not options.force): if py_version <= (3, 1) and not options.force:
print( print(
red red
+ "Provision failed: Cannot create venv with outdated Python version ({}).\n" + "Provision failed: Cannot create venv with outdated Python version ({}).\n"

View file

@ -75,7 +75,7 @@ class IRCBot(irc.bot.SingleServerIRCBot):
in_the_specified_stream = msg["display_recipient"] == self.stream in_the_specified_stream = msg["display_recipient"] == self.stream
at_the_specified_subject = msg["subject"].casefold() == self.topic.casefold() at_the_specified_subject = msg["subject"].casefold() == self.topic.casefold()
if in_the_specified_stream and at_the_specified_subject: if in_the_specified_stream and at_the_specified_subject:
msg["content"] = ("@**{}**: ".format(msg["sender_full_name"])) + msg["content"] msg["content"] = "@**{}**: ".format(msg["sender_full_name"]) + msg["content"]
send = lambda x: self.c.privmsg(self.channel, x) send = lambda x: self.c.privmsg(self.channel, x)
else: else:
return return

View file

@ -82,7 +82,7 @@ parser.add_argument(
options = parser.parse_args() options = parser.parse_args()
if not (options.zulip_email): if not options.zulip_email:
parser.error("You must specify --user") parser.error("You must specify --user")
zulip_client = zulip.init_from_options(options) zulip_client = zulip.init_from_options(options)

View file

@ -227,7 +227,7 @@ for feed_url in feed_urls:
) )
if ( if (
entry_time is not None entry_time is not None
and (time.time() - calendar.timegm(entry_time)) > OLDNESS_THRESHOLD * 60 * 60 * 24 and time.time() - calendar.timegm(entry_time) > OLDNESS_THRESHOLD * 60 * 60 * 24
): ):
# As a safeguard against misbehaving feeds, don't try to process # As a safeguard against misbehaving feeds, don't try to process
# entries older than some threshold. # entries older than some threshold.
@ -235,7 +235,7 @@ for feed_url in feed_urls:
if entry_hash in old_feed_hashes: if entry_hash in old_feed_hashes:
# We've already seen this. No need to process any older entries. # We've already seen this. No need to process any older entries.
break break
if (not old_feed_hashes) and (len(new_hashes) >= 3): if not old_feed_hashes and len(new_hashes) >= 3:
# On a first run, pick up the 3 most recent entries. An RSS feed has # On a first run, pick up the 3 most recent entries. An RSS feed has
# entries in reverse chronological order. # entries in reverse chronological order.
break break

View file

@ -122,7 +122,7 @@ at <https://zulip.com/integrations/doc/trello>.
parser.add_argument( parser.add_argument(
"--trello-board-id", "--trello-board-id",
required=True, required=True,
help=("The Trello board short ID. Can usually be found in the URL of the Trello board."), help="The Trello board short ID. Can usually be found in the URL of the Trello board.",
) )
parser.add_argument( parser.add_argument(
"--trello-api-key", "--trello-api-key",

View file

@ -474,7 +474,7 @@ def process_notice(
# Drop messages not to the listed subscriptions # Drop messages not to the listed subscriptions
if is_personal and not options.forward_personals: if is_personal and not options.forward_personals:
return return
if (zephyr_class.lower() not in current_zephyr_subs) and not is_personal: if zephyr_class.lower() not in current_zephyr_subs and not is_personal:
logger.debug("Skipping ... %s/%s/%s", zephyr_class, zephyr_instance, is_personal) logger.debug("Skipping ... %s/%s/%s", zephyr_class, zephyr_instance, is_personal)
return return
if notice.z_default_format.startswith(b"Zephyr error: See") or notice.z_default_format.endswith( if notice.z_default_format.startswith(b"Zephyr error: See") or notice.z_default_format.endswith(
@ -916,7 +916,7 @@ def maybe_forward_to_zephyr(message: Dict[str, Any], zulip_client: zulip.Client)
# The key string can be used to direct any type of text. # The key string can be used to direct any type of text.
if message["sender_email"] == zulip_account_email: if message["sender_email"] == zulip_account_email:
if not ( if not (
(message["type"] == "stream") message["type"] == "stream"
or ( or (
message["type"] == "private" message["type"] == "private"
and False and False

View file

@ -60,7 +60,7 @@ def send_message(recipients: List[str], stream: str, subject: str, message: str)
if len(recipients) != 0 and has_stream: if len(recipients) != 0 and has_stream:
click.echo("You cannot specify both a username and a stream/subject.") click.echo("You cannot specify both a username and a stream/subject.")
raise SystemExit(1) raise SystemExit(1)
if len(recipients) == 0 and (has_stream != has_subject): if len(recipients) == 0 and has_stream != has_subject:
click.echo("Stream messages must have a subject") click.echo("Stream messages must have a subject")
raise SystemExit(1) raise SystemExit(1)
if len(recipients) == 0 and not has_stream: if len(recipients) == 0 and not has_stream:

View file

@ -77,7 +77,7 @@ def main() -> int:
# Sanity check user data # Sanity check user data
if len(options.recipients) != 0 and (options.stream or options.subject): if len(options.recipients) != 0 and (options.stream or options.subject):
parser.error("You cannot specify both a username and a stream/subject.") parser.error("You cannot specify both a username and a stream/subject.")
if len(options.recipients) == 0 and (bool(options.stream) != bool(options.subject)): if len(options.recipients) == 0 and bool(options.stream) != bool(options.subject):
parser.error("Stream messages must have a subject") parser.error("Stream messages must have a subject")
if len(options.recipients) == 0 and not (options.stream and options.subject): if len(options.recipients) == 0 and not (options.stream and options.subject):
parser.error("You must specify a stream/subject or at least one recipient.") parser.error("You must specify a stream/subject or at least one recipient.")

View file

@ -401,7 +401,7 @@ def make_loss_response(board: chess.Board, reason: str) -> str:
Returns: The loss response string. Returns: The loss response string.
""" """
return ("*{}* {}. **{}** wins!\n\n{}").format( return "*{}* {}. **{}** wins!\n\n{}".format(
"White" if board.turn else "Black", "White" if board.turn else "Black",
reason, reason,
"Black" if board.turn else "White", "Black" if board.turn else "White",
@ -418,7 +418,7 @@ def make_not_legal_response(board: chess.Board, move_san: str) -> str:
Returns: The not-legal-move response string. Returns: The not-legal-move response string.
""" """
return ("Sorry, the move *{}* isn't legal.\n\n{}\n\n\n{}").format( return "Sorry, the move *{}* isn't legal.\n\n{}\n\n\n{}".format(
move_san, make_str(board, board.turn), make_footer() move_san, make_str(board, board.turn), make_footer()
) )

View file

@ -62,10 +62,10 @@ def get_bot_converter_response(message: Dict[str, str], bot_handler: BotHandler)
results = [] results = []
for convert_index in convert_indexes: for convert_index in convert_indexes:
if (convert_index + 1) < len(words) and words[convert_index + 1] == "help": if convert_index + 1 < len(words) and words[convert_index + 1] == "help":
results.append(utils.HELP_MESSAGE) results.append(utils.HELP_MESSAGE)
continue continue
if (convert_index + 3) < len(words): if convert_index + 3 < len(words):
number = words[convert_index + 1] number = words[convert_index + 1]
unit_from = utils.ALIASES.get(words[convert_index + 2], words[convert_index + 2]) unit_from = utils.ALIASES.get(words[convert_index + 2], words[convert_index + 2])
unit_to = utils.ALIASES.get(words[convert_index + 3], words[convert_index + 3]) unit_to = utils.ALIASES.get(words[convert_index + 3], words[convert_index + 3])
@ -132,7 +132,7 @@ def get_bot_converter_response(message: Dict[str, str], bot_handler: BotHandler)
new_content = "" new_content = ""
for idx, result in enumerate(results, 1): for idx, result in enumerate(results, 1):
new_content += ((str(idx) + ". conversion: ") if len(results) > 1 else "") + result + "\n" new_content += (str(idx) + ". conversion: " if len(results) > 1 else "") + result + "\n"
return new_content return new_content

View file

@ -62,16 +62,16 @@ class GameOfFifteenModel:
if tile not in coordinates: if tile not in coordinates:
raise BadMoveError("You can only move tiles which exist in the board.") raise BadMoveError("You can only move tiles which exist in the board.")
i, j = coordinates[tile] i, j = coordinates[tile]
if (j - 1) > -1 and board[i][j - 1] == 0: if j - 1 > -1 and board[i][j - 1] == 0:
board[i][j - 1] = tile board[i][j - 1] = tile
board[i][j] = 0 board[i][j] = 0
elif (i - 1) > -1 and board[i - 1][j] == 0: elif i - 1 > -1 and board[i - 1][j] == 0:
board[i - 1][j] = tile board[i - 1][j] = tile
board[i][j] = 0 board[i][j] = 0
elif (j + 1) < 3 and board[i][j + 1] == 0: elif j + 1 < 3 and board[i][j + 1] == 0:
board[i][j + 1] = tile board[i][j + 1] = tile
board[i][j] = 0 board[i][j] = 0
elif (i + 1) < 3 and board[i + 1][j] == 0: elif i + 1 < 3 and board[i + 1][j] == 0:
board[i + 1][j] = tile board[i + 1][j] = tile
board[i][j] = 0 board[i][j] = 0
else: else:

View file

@ -85,7 +85,7 @@ def generate_ticket_id(storage: Any) -> str:
except KeyError: except KeyError:
incident_num = 0 incident_num = 0
incident_num += 1 incident_num += 1
incident_num = incident_num % (1000) incident_num = incident_num % 1000
storage.put("ticket_id", incident_num) storage.put("ticket_id", incident_num)
ticket_id = "TICKET%04d" % (incident_num,) ticket_id = "TICKET%04d" % (incident_num,)
return ticket_id return ticket_id

View file

@ -64,7 +64,7 @@ class LinkShortenerHandler:
shortened_links = [self.shorten_link(link) for link in link_matches] shortened_links = [self.shorten_link(link) for link in link_matches]
link_pairs = [ link_pairs = [
(link_match + ": " + shortened_link) link_match + ": " + shortened_link
for link_match, shortened_link in zip(link_matches, shortened_links) for link_match, shortened_link in zip(link_matches, shortened_links)
if shortened_link != "" if shortened_link != ""
] ]

View file

@ -152,7 +152,7 @@ def is_legal_move(v1, h1, v2, h2, turn, phase, grid):
return ( return (
is_in_grid(v2, h2) is_in_grid(v2, h2)
and is_empty(v2, h2, grid) and is_empty(v2, h2, grid)
and (not is_jump(v1, h1, v2, h2)) and not is_jump(v1, h1, v2, h2)
and is_own_piece(v1, h1, turn, grid) and is_own_piece(v1, h1, turn, grid)
) )

View file

@ -34,8 +34,7 @@ class MerelsModel:
data = game_data.GameData(merels.get_game_data(self.topic)) data = game_data.GameData(merels.get_game_data(self.topic))
return data.get_phase() > 1 and ( return data.get_phase() > 1 and (
(mechanics.get_piece("X", data.grid()) <= 2) mechanics.get_piece("X", data.grid()) <= 2 or mechanics.get_piece("O", data.grid()) <= 2
or (mechanics.get_piece("O", data.grid()) <= 2)
) )
def make_move(self, move: str, player_number: int, computer_move: bool = False) -> Any: def make_move(self, move: str, player_number: int, computer_move: bool = False) -> Any:

View file

@ -194,8 +194,8 @@ class TicTacToeModel:
move_coords = move_coords_str.split(",") move_coords = move_coords_str.split(",")
# Subtraction must be done to convert to the right indices, # Subtraction must be done to convert to the right indices,
# since computers start numbering at 0. # since computers start numbering at 0.
row = (int(move_coords[1])) - 1 row = int(move_coords[1]) - 1
column = (int(move_coords[0])) - 1 column = int(move_coords[0]) - 1
if board[row][column] != 0: if board[row][column] != 0:
raise BadMoveError("Make sure your space hasn't already been filled.") raise BadMoveError("Make sure your space hasn't already been filled.")
board[row][column] = player_number + 1 board[row][column] = player_number + 1

View file

@ -83,7 +83,7 @@ class TestTrelloBot(BotTestCase, DefaultTests):
with self.mock_http_conversation("get_lists"): with self.mock_http_conversation("get_lists"):
self.verify_reply( self.verify_reply(
"get-all-lists TEST", "get-all-lists TEST",
("**Lists:**\n1. TEST_A\n * TEST_1\n2. TEST_B\n * TEST_2"), "**Lists:**\n1. TEST_A\n * TEST_1\n2. TEST_B\n * TEST_2",
) )
def test_command_exceptions(self) -> None: def test_command_exceptions(self) -> None:

View file

@ -134,7 +134,7 @@ def generate_quiz_id(storage: Any) -> str:
except (KeyError, TypeError): except (KeyError, TypeError):
quiz_num = 0 quiz_num = 0
quiz_num += 1 quiz_num += 1
quiz_num = quiz_num % (1000) quiz_num = quiz_num % 1000
storage.put("quiz_id", quiz_num) storage.put("quiz_id", quiz_num)
quiz_id = "Q%03d" % (quiz_num,) quiz_id = "Q%03d" % (quiz_num,)
return quiz_id return quiz_id

View file

@ -40,7 +40,7 @@ class WeatherHandler:
@**Weather Bot** Portland, Me @**Weather Bot** Portland, Me
""".strip() """.strip()
if (message["content"] == "help") or (message["content"] == ""): if message["content"] == "help" or message["content"] == "":
response = help_content response = help_content
else: else:
api_params = dict(q=message["content"], APPID=self.api_key) api_params = dict(q=message["content"], APPID=self.api_key)

View file

@ -92,7 +92,7 @@ class YodaSpeakHandler:
def handle_input(self, message: Dict[str, str], bot_handler: BotHandler) -> None: def handle_input(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
original_content = message["content"] original_content = message["content"]
if self.is_help(original_content) or (original_content == ""): if self.is_help(original_content) or original_content == "":
bot_handler.send_reply(message, HELP_MESSAGE) bot_handler.send_reply(message, HELP_MESSAGE)
else: else: