Skip to content

Commit

Permalink
python: Convert more percent formatting to Python 3.6 f-strings.
Browse files Browse the repository at this point in the history
Generated by pyupgrade --py36-plus.

Now including %d, %i, %u, and multi-line strings.

Signed-off-by: Anders Kaseorg <[email protected]>
  • Loading branch information
andersk authored and timabbott committed Jun 15, 2020
1 parent 1ed2d9b commit 74c17bf
Show file tree
Hide file tree
Showing 49 changed files with 217 additions and 241 deletions.
2 changes: 1 addition & 1 deletion analytics/management/commands/client_activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def compute_activity(self, user_activity_objects: QuerySet) -> None:
counts.sort()

for count in counts:
print("%25s %15d" % (count[1], count[0]))
print(f"{count[1]:>25} {count[0]:15}")
print("Total:", total)

def handle(self, *args: Any, **options: Optional[str]) -> None:
Expand Down
22 changes: 11 additions & 11 deletions analytics/management/commands/realm_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,26 +93,26 @@ def handle(self, *args: Any, **options: Any) -> None:
active_users = self.active_users(realm)
num_active = len(active_users)

print("%d active users (%d total)" % (num_active, len(user_profiles)))
print(f"{num_active} active users ({len(user_profiles)} total)")
streams = Stream.objects.filter(realm=realm).extra(
tables=['zerver_subscription', 'zerver_recipient'],
where=['zerver_subscription.recipient_id = zerver_recipient.id',
'zerver_recipient.type = 2',
'zerver_recipient.type_id = zerver_stream.id',
'zerver_subscription.active = true']).annotate(count=Count("name"))
print("%d streams" % (streams.count(),))
print(f"{streams.count()} streams")

for days_ago in (1, 7, 30):
print("In last %d days, users sent:" % (days_ago,))
print(f"In last {days_ago} days, users sent:")
sender_quantities = [self.messages_sent_by(user, days_ago) for user in user_profiles]
for quantity in sorted(sender_quantities, reverse=True):
print(quantity, end=' ')
print("")

print("%d stream messages" % (self.stream_messages(realm, days_ago),))
print("%d one-on-one private messages" % (self.private_messages(realm, days_ago),))
print("%d messages sent via the API" % (self.api_messages(realm, days_ago),))
print("%d group private messages" % (self.group_private_messages(realm, days_ago),))
print(f"{self.stream_messages(realm, days_ago)} stream messages")
print(f"{self.private_messages(realm, days_ago)} one-on-one private messages")
print(f"{self.api_messages(realm, days_ago)} messages sent via the API")
print(f"{self.group_private_messages(realm, days_ago)} group private messages")

num_notifications_enabled = len([x for x in active_users if x.enable_desktop_notifications])
self.report_percentage(num_notifications_enabled, num_active,
Expand All @@ -132,7 +132,7 @@ def handle(self, *args: Any, **options: Any) -> None:
starrers = UserMessage.objects.filter(user_profile__in=user_profiles,
flags=UserMessage.flags.starred).values(
"user_profile").annotate(count=Count("user_profile"))
print("%d users have starred %d messages" % (
print("{} users have starred {} messages".format(
len(starrers), sum([elt["count"] for elt in starrers])))

active_user_subs = Subscription.objects.filter(
Expand All @@ -141,20 +141,20 @@ def handle(self, *args: Any, **options: Any) -> None:
# Streams not in home view
non_home_view = active_user_subs.filter(is_muted=True).values(
"user_profile").annotate(count=Count("user_profile"))
print("%d users have %d streams not in home view" % (
print("{} users have {} streams not in home view".format(
len(non_home_view), sum([elt["count"] for elt in non_home_view])))

# Code block markup
markup_messages = human_messages.filter(
sender__realm=realm, content__contains="~~~").values(
"sender").annotate(count=Count("sender"))
print("%d users have used code block markup on %s messages" % (
print("{} users have used code block markup on {} messages".format(
len(markup_messages), sum([elt["count"] for elt in markup_messages])))

# Notifications for stream messages
notifications = active_user_subs.filter(desktop_notifications=True).values(
"user_profile").annotate(count=Count("user_profile"))
print("%d users receive desktop notifications for %d streams" % (
print("{} users receive desktop notifications for {} streams".format(
len(notifications), sum([elt["count"] for elt in notifications])))

print("")
10 changes: 5 additions & 5 deletions analytics/management/commands/stream_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ def handle(self, *args: Any, **options: str) -> None:
public_count += 1
print("------------")
print(realm.string_id, end=' ')
print("%10s %d public streams and" % ("(", public_count), end=' ')
print("%d private streams )" % (private_count,))
print("{:>10} {} public streams and".format("(", public_count), end=' ')
print(f"{private_count} private streams )")
print("------------")
print("{:>25} {:>15} {:>10} {:>12}".format("stream", "subscribers", "messages", "type"))

Expand All @@ -48,9 +48,9 @@ def handle(self, *args: Any, **options: str) -> None:
stream_type = 'public'
print(f"{stream.name:>25}", end=' ')
recipient = Recipient.objects.filter(type=Recipient.STREAM, type_id=stream.id)
print("%10d" % (len(Subscription.objects.filter(recipient=recipient,
active=True)),), end=' ')
print("{:10}".format(len(Subscription.objects.filter(recipient=recipient,
active=True))), end=' ')
num_messages = len(Message.objects.filter(recipient=recipient))
print("%12d" % (num_messages,), end=' ')
print(f"{num_messages:12}", end=' ')
print(f"{stream_type:>15}")
print("")
6 changes: 3 additions & 3 deletions analytics/management/commands/user_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ def handle(self, *args: Any, **options: Any) -> None:
for realm in realms:
print(realm.string_id)
user_profiles = UserProfile.objects.filter(realm=realm, is_active=True)
print("%d users" % (len(user_profiles),))
print("%d streams" % (len(Stream.objects.filter(realm=realm)),))
print(f"{len(user_profiles)} users")
print(f"{len(Stream.objects.filter(realm=realm))} streams")

for user_profile in user_profiles:
print(f"{user_profile.email:>35}", end=' ')
for week in range(10):
print("%5d" % (self.messages_sent_by(user_profile, week),), end=' ')
print(f"{self.messages_sent_by(user_profile, week):5}", end=' ')
print("")
2 changes: 1 addition & 1 deletion confirmation/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ class Confirmation(models.Model):
type: int = models.PositiveSmallIntegerField()

def __str__(self) -> str:
return '<Confirmation: %s>' % (self.content_object,)
return f'<Confirmation: {self.content_object}>'

class Meta:
unique_together = ("type", "confirmation_key")
Expand Down
4 changes: 2 additions & 2 deletions corporate/tests/test_stripe.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def normalize_fixture_data(decorated_function: CallableT,
('src', 24), ('invst', 26), ('acct', 16), ('rcpt', 31)]
# We'll replace cus_D7OT2jf5YAtZQ2 with something like cus_NORMALIZED0001
pattern_translations = {
"%s_[A-Za-z0-9]{%d}" % (prefix, length): "%s_NORMALIZED%%0%dd" % (prefix, length - 10)
f"{prefix}_[A-Za-z0-9]{{{length}}}": f"{prefix}_NORMALIZED%0{length - 10}d"
for prefix, length in id_lengths
}
# We'll replace "invoice_prefix": "A35BC4Q" with something like "invoice_prefix": "NORMA01"
Expand All @@ -168,7 +168,7 @@ def normalize_fixture_data(decorated_function: CallableT,
# Don't use (..) notation, since the matched timestamp can easily appear in other fields
pattern_translations[
f'"{timestamp_field}": 1[5-9][0-9]{{8}}(?![0-9-])'
] = '"%s": 1%02d%%07d' % (timestamp_field, i+1)
] = f'"{timestamp_field}": 1{i+1:02}%07d'

normalized_values: Dict[str, Dict[str, str]] = {
pattern: {} for pattern in pattern_translations.keys()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,22 @@ replay_diff = secondary_recv_offset - secondary_replay_offset

# xlog segments are normally 16MB each. These thresholds are pretty arbitrary.
if recv_diff > 5 * 16 * 1024**2:
report('CRITICAL', 'secondary is %d bytes behind on receiving xlog' % (recv_diff,))
report('CRITICAL', f'secondary is {recv_diff} bytes behind on receiving xlog')

if replay_diff > 5 * 16 * 1024**2:
report('CRITICAL', 'secondary is %d bytes behind on applying received xlog' % (replay_diff,))
report('CRITICAL', f'secondary is {replay_diff} bytes behind on applying received xlog')

if recv_diff < 0:
report('CRITICAL', 'secondary is %d bytes ahead on receiving xlog' % (recv_diff,))
report('CRITICAL', f'secondary is {recv_diff} bytes ahead on receiving xlog')

if replay_diff < 0:
report('CRITICAL', 'secondary is %d bytes ahead on applying received xlog' % (replay_diff,))
report('CRITICAL', f'secondary is {replay_diff} bytes ahead on applying received xlog')

if recv_diff > 16 * 1024**2:
report('WARNING', 'secondary is %d bytes behind on receiving xlog' % (recv_diff,))
report('WARNING', f'secondary is {recv_diff} bytes behind on receiving xlog')

if replay_diff > 16 * 1024**2:
report('WARNING', 'secondary is %d bytes behind on applying received xlog' % (replay_diff,))
report('WARNING', f'secondary is {replay_diff} bytes behind on applying received xlog')

report('OK', ('secondary is %d bytes behind on receiving and %d bytes behind on applying xlog'
% (recv_diff, replay_diff)))
12 changes: 6 additions & 6 deletions puppet/zulip_ops/files/zulip-ec2-configure-interfaces
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import netifaces

def address_of(device_id: int) -> Optional[str]:
try:
return netifaces.ifaddresses("ens%i" % (device_id,))[netifaces.AF_INET][0]['addr']
return netifaces.ifaddresses(f"ens{device_id}")[netifaces.AF_INET][0]['addr']
except KeyError:
return None

Expand Down Expand Up @@ -83,7 +83,7 @@ ifaces = [iface for iface in netifaces.interfaces() if ":" not in iface and ifac

# Number of IDs should equal number of interfaces
if len(ids) != len(ifaces):
log.error("Metadata indicated %i interfaces but we have %i!" % (len(ids), len(ifaces)))
log.error(f"Metadata indicated {len(ids)} interfaces but we have {len(ifaces)}!")
sys.exit(1)

for device in macs.values():
Expand All @@ -105,8 +105,8 @@ for device in macs.values():

if address is None:
# If the device was not autoconfigured, do so now.
log.info("Device ens%i not configured, starting dhcpd" % (device_number,))
subprocess.check_call(['/sbin/dhcpcd', 'ens%i' % (device_number,)])
log.info(f"Device ens{device_number} not configured, starting dhcpd")
subprocess.check_call(['/sbin/dhcpcd', f'ens{device_number}'])

dev_num = str(device_number)
address = address_of(device_number)
Expand All @@ -120,7 +120,7 @@ for device in macs.values():
['/sbin/ip', 'rule', 'add', 'fwmark', dev_num, 'table', dev_num])
subprocess.check_call(
['/sbin/ip', 'route', 'add', '0.0.0.0/0', 'table', dev_num, 'dev',
'ens%i' % (device_number,), 'via', gateway])
f'ens{device_number}', 'via', gateway])
subprocess.check_call(
['/sbin/iptables', '-t', 'mangle', '-A', 'OUTPUT', '-m', 'conntrack', '--ctorigdst',
address, '-j', 'MARK', '--set-mark', dev_num])
Expand All @@ -129,7 +129,7 @@ for device in macs.values():

for (count, ip) in enumerate(to_configure):
# Configure the IP via a virtual interface
device = "ens%i:%i" % (device_number, count)
device = f"ens{device_number}:{count}"
log.info(f"Configuring {device} with IP {ip}")
subprocess.check_call(['/sbin/ifconfig', device, ip])
subprocess.check_call(
Expand Down
4 changes: 2 additions & 2 deletions static/assets/favicon/generate
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ elems = [tree.getroot().findall(

for i in range(1, 100):
# Prepare a modified SVG
s = '%2d' % (i,)
s = f'{i:2}'
for e in elems:
e.text = s
with open('tmp.svg', 'wb') as out:
tree.write(out)

# Convert to PNG
subprocess.check_call(['inkscape', '--without-gui', '--export-area-page',
'--export-png=../../../static/images/favicon/favicon-%d.png' % (i,),
f'--export-png=../../../static/images/favicon/favicon-{i}.png',
'tmp.svg'])
33 changes: 14 additions & 19 deletions tools/lib/template_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,12 +157,7 @@ def looking_at_jinja2_start_whitespace_stripped_type2() -> bool:
continue
except TokenizationException as e:
raise FormattedException(
'''%s at Line %d Col %d:"%s"''' % (
e.message,
state.line,
state.col,
e.line_content,
),
f'''{e.message} at Line {state.line} Col {state.col}:"{e.line_content}"''',
)

line_span = len(s.split('\n'))
Expand Down Expand Up @@ -223,13 +218,13 @@ def __init__(self, func: Callable[[Token], None]) -> None:
self.matcher = func

def no_start_tag(token: Token) -> None:
raise TemplateParserException('''
raise TemplateParserException(f'''
No start tag
fn: %s
fn: {fn}
end tag:
%s
line %d, col %d
''' % (fn, token.tag, token.line, token.col))
{token.tag}
line {token.line}, col {token.col}
''')

state = State(no_start_tag)

Expand Down Expand Up @@ -261,16 +256,16 @@ def f(end_token: Token) -> None:
if end_col != start_col:
problem = 'Bad indentation.'
if problem:
raise TemplateParserException('''
fn: %s
%s
raise TemplateParserException(f'''
fn: {fn}
{problem}
start:
%s
line %d, col %d
{start_token.s}
line {start_line}, col {start_col}
end tag:
%s
line %d, col %d
''' % (fn, problem, start_token.s, start_line, start_col, end_tag, end_line, end_col))
{end_tag}
line {end_line}, col {end_col}
''')
state.matcher = old_matcher
state.depth -= 1
state.matcher = f
Expand Down
2 changes: 1 addition & 1 deletion tools/renumber-migrations
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def renumber_migration(conflicts: List[str], order: List[int], last_correct_migr

# Rename the migration indexing at the end
new_name = conflicts[i-1].replace(conflicts[i-1][0:4],
'%04d' % (int(last_correct_migration[0:4]) + 1,))
f'{int(last_correct_migration[0:4]) + 1:04}')
os.rename('zerver/migrations/' + conflicts[i-1], 'zerver/migrations/' + new_name)

last_correct_migration = new_name.replace('.py', '')
Expand Down
4 changes: 2 additions & 2 deletions tools/review
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ def ensure_on_clean_master() -> None:
run(['git', 'rebase', 'upstream/master'])

def create_pull_branch(pull_id: int) -> None:
run(['git', 'fetch', 'upstream', 'pull/%d/head' % (pull_id,)])
run(['git', 'fetch', 'upstream', f'pull/{pull_id}/head'])
run(['git', 'checkout', '-B', f'review-{pull_id}', 'FETCH_HEAD'])
run(['git', 'rebase', 'upstream/master'])
run(['git', 'log', 'upstream/master..', '--oneline'])
run(['git', 'diff', 'upstream/master..', '--name-status'])

print()
print('PR: %d' % (pull_id,))
print(f'PR: {pull_id}')
print(subprocess.check_output(['git', 'log', 'HEAD~..',
'--pretty=format:Author: %an']))

Expand Down
4 changes: 2 additions & 2 deletions tools/run-dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,9 @@
def server_processes() -> List[List[str]]:
main_cmds = [
['./manage.py', 'runserver'] +
manage_args + runserver_args + ['127.0.0.1:%d' % (django_port,)],
manage_args + runserver_args + [f'127.0.0.1:{django_port}'],
['env', 'PYTHONUNBUFFERED=1', './manage.py', 'runtornado'] +
manage_args + ['127.0.0.1:%d' % (tornado_port,)],
manage_args + [f'127.0.0.1:{tornado_port}'],
]

if options.streamlined:
Expand Down
2 changes: 1 addition & 1 deletion tools/zulip-export/zulip-export
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,5 @@ for msg in result['messages']:
filename = f"zulip-{options.stream}.json"
with open(filename, 'wb') as f:
f.write(json.dumps(messages, indent=0, sort_keys=False).encode('utf-8'))
print("%d messages exported to %s" % (len(messages), filename))
print(f"{len(messages)} messages exported to {filename}")
sys.exit(0)
2 changes: 1 addition & 1 deletion zerver/data_import/gitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def convert_gitter_workspace_messages(gitter_data: GitterDataT, output_dir: str,

message_json['zerver_message'] = zerver_message
message_json['zerver_usermessage'] = zerver_usermessage
message_filename = os.path.join(output_dir, "messages-%06d.json" % (dump_file_id,))
message_filename = os.path.join(output_dir, f"messages-{dump_file_id:06}.json")
logging.info("Writing Messages to %s\n", message_filename)
write_data_to_file(os.path.join(message_filename), message_json)

Expand Down
2 changes: 1 addition & 1 deletion zerver/data_import/hipchat.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,7 @@ def fix_mentions(content: str,
)

dump_file_id = NEXT_ID('dump_file_id')
message_file = "/messages-%06d.json" % (dump_file_id,)
message_file = f"/messages-{dump_file_id:06}.json"
create_converted_data_files(message_json, output_dir, message_file)

def do_convert_data(input_tar_file: str,
Expand Down
2 changes: 1 addition & 1 deletion zerver/data_import/mattermost.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ def fix_mentions(content: str, mention_user_ids: Set[int]) -> str:
)

dump_file_id = NEXT_ID('dump_file_id' + str(realm_id))
message_file = "/messages-%06d.json" % (dump_file_id,)
message_file = f"/messages-{dump_file_id:06}.json"
create_converted_data_files(message_json, output_dir, message_file)

def process_posts(num_teams: int,
Expand Down
2 changes: 1 addition & 1 deletion zerver/data_import/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ def convert_slack_workspace_messages(slack_data_dir: str, users: List[ZerverFiel
zerver_message=zerver_message,
zerver_usermessage=zerver_usermessage)

message_file = "/messages-%06d.json" % (dump_file_id,)
message_file = f"/messages-{dump_file_id:06}.json"
logging.info("Writing Messages to %s\n", output_dir + message_file)
create_converted_data_files(message_json, output_dir, message_file)

Expand Down
10 changes: 2 additions & 8 deletions zerver/lib/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,9 +347,7 @@ def notify_new_user(user_profile: UserProfile) -> None:
sender,
signup_notifications_stream,
"signups",
"@_**%s|%s** just signed up for Zulip. (total: %i)" % (
user_profile.full_name, user_profile.id, user_count,
),
f"@_**{user_profile.full_name}|{user_profile.id}** just signed up for Zulip. (total: {user_count})",
)

# We also send a notification to the Zulip administrative realm
Expand All @@ -362,11 +360,7 @@ def notify_new_user(user_profile: UserProfile) -> None:
sender,
signups_stream,
user_profile.realm.display_subdomain,
"%s <`%s`> just signed up for Zulip! (total: **%i**)" % (
user_profile.full_name,
user_profile.email,
user_count,
),
f"{user_profile.full_name} <`{user_profile.email}`> just signed up for Zulip! (total: **{user_count}**)",
)

except Stream.DoesNotExist:
Expand Down
Loading

0 comments on commit 74c17bf

Please sign in to comment.