Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove redundant parentheses #813

Merged
merged 2 commits into from
Nov 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 0 additions & 11 deletions tools/custom_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,6 @@
"good_lines": ["def foo (self):"],
"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__",
"include_only": {"zulip_bots/zulip_bots/bots/"},
Expand Down
2 changes: 1 addition & 1 deletion tools/provision
Original file line number Diff line number Diff line change
Expand Up @@ -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])
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(
red
+ "Provision failed: Cannot create venv with outdated Python version ({}).\n"
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/bridge_with_irc/irc_mirror_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def forward_to_irc(msg: Dict[str, Any]) -> None:
in_the_specified_stream = msg["display_recipient"] == self.stream
at_the_specified_subject = msg["subject"].casefold() == self.topic.casefold()
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)
else:
return
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/google/google-calendar
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ parser.add_argument(

options = parser.parse_args()

if not (options.zulip_email):
if not options.zulip_email:
parser.error("You must specify --user")

zulip_client = zulip.init_from_options(options)
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/jabber/jabber_mirror_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ def config_error(msg: str) -> None:

parser.add_option_group(jabber_group)
parser.add_option_group(zulip.generate_option_group(parser, "zulip-"))
(options, args) = parser.parse_args()
options, args = parser.parse_args()

logging.basicConfig(level=options.log_level, format="%(levelname)-8s %(message)s")

Expand Down
4 changes: 2 additions & 2 deletions zulip/integrations/rss/rss-bot
Original file line number Diff line number Diff line change
Expand Up @@ -227,15 +227,15 @@ for feed_url in feed_urls:
)
if (
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
# entries older than some threshold.
continue
if entry_hash in old_feed_hashes:
# We've already seen this. No need to process any older entries.
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
# entries in reverse chronological order.
break
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/trello/zulip_trello.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def main() -> None:
parser.add_argument(
"--trello-board-id",
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(
"--trello-api-key",
Expand Down
10 changes: 5 additions & 5 deletions zulip/integrations/zephyr/check-mirroring
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ parser = optparse.OptionParser()
parser.add_option("--verbose", dest="verbose", default=False, action="store_true")
parser.add_option("--site", dest="site", default=None, action="store")
parser.add_option("--sharded", default=False, action="store_true")
(options, args) = parser.parse_args()
options, args = parser.parse_args()

mit_user = "tabbott/extra@ATHENA.MIT.EDU"

Expand Down Expand Up @@ -331,8 +331,8 @@ z_contents = [
notice.z_message[: notice.z_message_len].split(b"\0")[1].decode(errors="replace")
for notice in notices
]
(h_key_counts, h_missing_z, h_missing_h, h_duplicates, h_success) = process_keys(h_contents)
(z_key_counts, z_missing_z, z_missing_h, z_duplicates, z_success) = process_keys(z_contents)
h_key_counts, h_missing_z, h_missing_h, h_duplicates, h_success = process_keys(h_contents)
z_key_counts, z_missing_z, z_missing_h, z_duplicates, z_success = process_keys(z_contents)

for notice in notices:
zephyr_ctypes.ZFreeNotice(byref(notice))
Expand All @@ -350,7 +350,7 @@ for key in all_keys:
if z_key_counts[key] == 1 and h_key_counts[key] == 1:
continue
if key in zhkeys:
(stream, test) = zhkeys[key]
stream, test = zhkeys[key]
logger.warning(
"%10s: z got %s, h got %s. Sent via Zephyr(%s): class %s",
key,
Expand All @@ -360,7 +360,7 @@ for key in all_keys:
stream,
)
if key in hzkeys:
(stream, test) = hzkeys[key]
stream, test = hzkeys[key]
logger.warning(
"%10s: z got %s. h got %s. Sent via Zulip(%s): class %s",
key,
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/zephyr/zephyr_mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
sys.path[:0] = [os.path.dirname(__file__)]
from zephyr_mirror_backend import parse_args

(options, args) = parse_args()
options, args = parse_args()


def die(signal: int, frame: Optional[FrameType]) -> None:
Expand Down
24 changes: 12 additions & 12 deletions zulip/integrations/zephyr/zephyr_mirror_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def make_zulip_client() -> zulip.Client:

def to_zulip_username(zephyr_username: str) -> str:
if "@" in zephyr_username:
(user, realm) = zephyr_username.split("@")
user, realm = zephyr_username.split("@")
else:
(user, realm) = (zephyr_username, "ATHENA.MIT.EDU")
user, realm = (zephyr_username, "ATHENA.MIT.EDU")
if realm.upper() == "ATHENA.MIT.EDU":
# Hack to make ctl's fake username setup work :)
if user.lower() == "golem":
Expand All @@ -65,7 +65,7 @@ def to_zulip_username(zephyr_username: str) -> str:


def to_zephyr_username(zulip_username: str) -> str:
(user, realm) = zulip_username.split("@")
user, realm = zulip_username.split("@")
if "|" not in user:
# Hack to make ctl's fake username setup work :)
if user.lower() == "ctl":
Expand Down Expand Up @@ -358,7 +358,7 @@ def process_loop(zulip_queue: "Queue[ZephyrDict]", log: Optional[IO[str]]) -> No

def parse_zephyr_body(zephyr_data: str, notice_format: str) -> Tuple[str, str]:
try:
(zsig, body) = zephyr_data.split("\x00", 1)
zsig, body = zephyr_data.split("\x00", 1)
if notice_format in (
"New transaction [$1] entered in $2\nFrom: $3 ($5)\nSubject: $4",
"New transaction [$1] entered in $2\nFrom: $3\nSubject: $4",
Expand All @@ -374,7 +374,7 @@ def parse_zephyr_body(zephyr_data: str, notice_format: str) -> Tuple[str, str]:
fields[3],
)
except ValueError:
(zsig, body) = ("", zephyr_data)
zsig, body = "", zephyr_data
# Clean body of any null characters, since they're invalid in our protocol.
body = body.replace("\x00", "")
return (zsig, body)
Expand Down Expand Up @@ -448,7 +448,7 @@ def process_notice(
notice: zephyr_ctypes.ZNotice_t, zulip_queue: "Queue[ZephyrDict]", log: Optional[IO[str]]
) -> None:
assert notice.z_sender is not None
(zsig, body) = parse_zephyr_body(
zsig, body = parse_zephyr_body(
notice.z_message[: notice.z_message_len].decode(errors="replace"),
notice.z_default_format.decode(errors="replace"),
)
Expand All @@ -474,7 +474,7 @@ def process_notice(
# Drop messages not to the listed subscriptions
if is_personal and not options.forward_personals:
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)
return
if notice.z_default_format.startswith(b"Zephyr error: See") or notice.z_default_format.endswith(
Expand Down Expand Up @@ -852,7 +852,7 @@ class and your mirroring bot does not have access to the relevant \
logger.debug("Would have forwarded: %r\n%s", zwrite_args, wrapped_content)
return

(code, stderr) = send_authed_zephyr(zwrite_args, wrapped_content)
code, stderr = send_authed_zephyr(zwrite_args, wrapped_content)
if code == 0 and stderr == "":
return
elif code == 0:
Expand All @@ -876,7 +876,7 @@ class and your mirroring bot does not have access to the relevant \
):
# Retry sending the message unauthenticated; if that works,
# just notify the user that they need to renew their tickets
(code, stderr) = send_unauthed_zephyr(zwrite_args, wrapped_content)
code, stderr = send_unauthed_zephyr(zwrite_args, wrapped_content)
if code == 0:
if options.ignore_expired_tickets:
return
Expand Down Expand Up @@ -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.
if message["sender_email"] == zulip_account_email:
if not (
(message["type"] == "stream")
message["type"] == "stream"
or (
message["type"] == "private"
and False
Expand Down Expand Up @@ -1106,7 +1106,7 @@ def parse_zephyr_subs(verbose: bool = False) -> Set[Tuple[str, str, str]]:
if len(line) == 0:
continue
try:
(cls, instance, recipient) = line.split(",")
cls, instance, recipient = line.split(",")
cls = cls.replace("%me%", options.user)
instance = instance.replace("%me%", options.user)
recipient = recipient.replace("%me%", options.user)
Expand Down Expand Up @@ -1252,7 +1252,7 @@ def die_gracefully(signal: int, frame: Optional[FrameType]) -> None:

signal.signal(signal.SIGINT, die_gracefully)

(options, args) = parse_args()
options, args = parse_args()

logger = open_logger()
configure_logger(logger, "parent")
Expand Down
2 changes: 1 addition & 1 deletion zulip/zulip/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ def do_register() -> Tuple[str, int]:
# making a new long-polling request.
while True:
if queue_id is None:
(queue_id, last_event_id) = do_register()
queue_id, last_event_id = do_register()

try:
res = self.get_events(queue_id=queue_id, last_event_id=last_event_id)
Expand Down
2 changes: 1 addition & 1 deletion zulip/zulip/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def send_message(recipients: List[str], stream: str, subject: str, message: str)
if len(recipients) != 0 and has_stream:
click.echo("You cannot specify both a username and a stream/subject.")
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")
raise SystemExit(1)
if len(recipients) == 0 and not has_stream:
Expand Down
2 changes: 1 addition & 1 deletion zulip/zulip/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def main() -> int:
# Sanity check user data
if len(options.recipients) != 0 and (options.stream or options.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")
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.")
Expand Down
4 changes: 2 additions & 2 deletions zulip_bots/zulip_bots/bots/chessbot/chessbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ def make_loss_response(board: chess.Board, reason: str) -> str:

Returns: The loss response string.
"""
return ("*{}* {}. **{}** wins!\n\n{}").format(
return "*{}* {}. **{}** wins!\n\n{}".format(
"White" if board.turn else "Black",
reason,
"Black" if board.turn else "White",
Expand All @@ -418,7 +418,7 @@ def make_not_legal_response(board: chess.Board, move_san: str) -> str:

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()
)

Expand Down
6 changes: 3 additions & 3 deletions zulip_bots/zulip_bots/bots/converter/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ def get_bot_converter_response(message: Dict[str, str], bot_handler: BotHandler)
results = []

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)
continue
if (convert_index + 3) < len(words):
if convert_index + 3 < len(words):
number = words[convert_index + 1]
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])
Expand Down Expand Up @@ -132,7 +132,7 @@ def get_bot_converter_response(message: Dict[str, str], bot_handler: BotHandler)

new_content = ""
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

Expand Down
8 changes: 4 additions & 4 deletions zulip_bots/zulip_bots/bots/game_of_fifteen/game_of_fifteen.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,16 @@ def make_move(self, move: str, player_number: int, computer_move: bool = False)
if tile not in coordinates:
raise BadMoveError("You can only move tiles which exist in the board.")
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] = 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][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] = 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][j] = 0
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def get_translate_bot_response(message_content, config_file, author, all_languag
split_text.append("")
if len(split_text) != 3:
return help_text
(text_to_translate, target_language, source_language) = split_text
text_to_translate, target_language, source_language = split_text
text_to_translate = text_to_translate[1:]
target_language = get_code_for_language(target_language, all_languages)
if target_language == "":
Expand Down
4 changes: 2 additions & 2 deletions zulip_bots/zulip_bots/bots/incident/incident.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> No
start_new_incident(query, message, bot_handler)
elif query.startswith("answer "):
try:
(ticket_id, answer) = parse_answer(query)
ticket_id, answer = parse_answer(query)
except InvalidAnswerError:
bot_response = "Invalid answer format"
bot_handler.send_reply(message, bot_response)
Expand Down Expand Up @@ -85,7 +85,7 @@ def generate_ticket_id(storage: Any) -> str:
except KeyError:
incident_num = 0
incident_num += 1
incident_num = incident_num % (1000)
incident_num = incident_num % 1000
storage.put("ticket_id", incident_num)
ticket_id = "TICKET%04d" % (incident_num,)
return ticket_id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> No

shortened_links = [self.shorten_link(link) for link in link_matches]
link_pairs = [
(link_match + ": " + shortened_link)
link_match + ": " + shortened_link
for link_match, shortened_link in zip(link_matches, shortened_links)
if shortened_link != ""
]
Expand Down
2 changes: 1 addition & 1 deletion zulip_bots/zulip_bots/bots/merels/libraries/mechanics.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def is_legal_move(v1, h1, v2, h2, turn, phase, grid):
return (
is_in_grid(v2, h2)
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)
)

Expand Down
3 changes: 1 addition & 2 deletions zulip_bots/zulip_bots/bots/merels/merels.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ def contains_winning_move(self, board: Any) -> bool:
data = game_data.GameData(merels.get_game_data(self.topic))

return data.get_phase() > 1 and (
(mechanics.get_piece("X", data.grid()) <= 2)
or (mechanics.get_piece("O", data.grid()) <= 2)
mechanics.get_piece("X", 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:
Expand Down
4 changes: 2 additions & 2 deletions zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,8 @@ def make_move(self, move: str, player_number: int, computer_move: bool = False)
move_coords = move_coords_str.split(",")
# Subtraction must be done to convert to the right indices,
# since computers start numbering at 0.
row = (int(move_coords[1])) - 1
column = (int(move_coords[0])) - 1
row = int(move_coords[1]) - 1
column = int(move_coords[0]) - 1
if board[row][column] != 0:
raise BadMoveError("Make sure your space hasn't already been filled.")
board[row][column] = player_number + 1
Expand Down
2 changes: 1 addition & 1 deletion zulip_bots/zulip_bots/bots/trello/test_trello.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def test_get_all_lists_command(self) -> None:
with self.mock_http_conversation("get_lists"):
self.verify_reply(
"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:
Expand Down
Loading
Loading