Skip to content

Commit dee5e05

Browse files
committed
style(flynt): convert .format and % strings to f-strings
1 parent af3d705 commit dee5e05

24 files changed

+133
-138
lines changed

src/acquisition/afhsb/afhsb_csv.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,15 @@ def get_flu_cat(dx):
5151
if dx.startswith(prefix):
5252
return 1
5353
for i in range(12, 19):
54-
prefix = "J{}".format(i)
54+
prefix = f"J{i}"
5555
if dx.startswith(prefix):
5656
return 2
5757
for i in range(0, 7):
58-
prefix = "J0{}".format(i)
58+
prefix = f"J0{i}"
5959
if dx.startswith(prefix):
6060
return 3
6161
for i in range(20, 23):
62-
prefix = "J{}".format(i)
62+
prefix = f"J{i}"
6363
if dx.startswith(prefix):
6464
return 3
6565
for prefix in ["J40", "R05", "H669", "R509", "B9789"]:
@@ -79,7 +79,7 @@ def get_field(row, column):
7979

8080
def row2flu(row):
8181
for i in range(1, 9):
82-
dx = get_field(row, "dx{}".format(i))
82+
dx = get_field(row, f"dx{i}")
8383
flu_cat = get_flu_cat(dx)
8484
if flu_cat is not None:
8585
return flu_cat
@@ -136,7 +136,7 @@ def get_country_mapping():
136136

137137

138138
def format_dmisid_csv(filename, target_name):
139-
src_path = os.path.join(TARGET_DIR, "{}.csv".format(filename))
139+
src_path = os.path.join(TARGET_DIR, f"{filename}.csv")
140140
dst_path = os.path.join(TARGET_DIR, target_name)
141141

142142
src_csv = open(src_path, encoding="utf-8-sig")
@@ -231,10 +231,10 @@ def state2region_csv():
231231

232232
def write_afhsb_csv(period):
233233
flu_mapping = {0: "ili-flu3", 1: "flu1", 2: "flu2-flu1", 3: "flu3-flu2"}
234-
results_dict = pickle.load(open(os.path.join(TARGET_DIR, "{}.pickle".format(period)), "rb"))
234+
results_dict = pickle.load(open(os.path.join(TARGET_DIR, f"{period}.pickle"), "rb"))
235235

236236
fieldnames = ["id", "epiweek", "dmisid", "flu_type", "visit_sum"]
237-
with open(os.path.join(TARGET_DIR, "{}.csv".format(period)), "w") as csvfile:
237+
with open(os.path.join(TARGET_DIR, f"{period}.csv"), "w") as csvfile:
238238
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
239239
writer.writeheader()
240240

@@ -248,7 +248,7 @@ def write_afhsb_csv(period):
248248
for flu in sorted(dmisid_dict.keys()):
249249
visit_sum = dmisid_dict[flu]
250250
i += 1
251-
epiweek = int("{}{:02d}".format(year, week))
251+
epiweek = int(f"{year}{week:02d}")
252252
flu_type = flu_mapping[flu]
253253

254254
row = {
@@ -290,8 +290,8 @@ def dmisid_start_time():
290290

291291

292292
def fillin_zero_to_csv(period, dmisid_start_record):
293-
src_path = os.path.join(TARGET_DIR, "{}.csv".format(period))
294-
dst_path = os.path.join(TARGET_DIR, "filled_{}.csv".format(period))
293+
src_path = os.path.join(TARGET_DIR, f"{period}.csv")
294+
dst_path = os.path.join(TARGET_DIR, f"filled_{period}.csv")
295295

296296
# Load data into a dictionary
297297
src_csv = open(src_path)
@@ -352,7 +352,7 @@ def fillin_zero_to_csv(period, dmisid_start_record):
352352
if i % 100000 == 0:
353353
print(row)
354354
i += 1
355-
print("Wrote {} rows".format(i))
355+
print(f"Wrote {i} rows")
356356

357357

358358
######################### Functions for AFHSB data ##########################

src/acquisition/afhsb/afhsb_sql.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def init_region_table(sourcefile):
7373

7474

7575
def init_raw_data(table_name, sourcefile):
76-
print("Initialize {}".format(table_name))
76+
print(f"Initialize {table_name}")
7777
(u, p) = secrets.db.epi
7878
cnx = connector.connect(user=u, passwd=p, database="epidata")
7979
create_table_cmd = f"""

src/acquisition/cdcp/cdc_dropbox_receiver.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def fetch_data():
101101
if resp.status_code != 200:
102102
raise Exception(["resp.status_code", resp.status_code])
103103
dropbox_len = meta.size
104-
print(" need %d bytes..." % dropbox_len)
104+
print(f" need {int(dropbox_len)} bytes...")
105105
content_len = int(resp.headers.get("Content-Length", -1))
106106
if dropbox_len != content_len:
107107
info = ["dropbox_len", dropbox_len, "content_len", content_len]

src/acquisition/cdcp/cdc_extract.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def get_total_hits(cur, epiweek, state):
110110
for (total,) in cur:
111111
pass
112112
if total is None:
113-
raise Exception("missing data for %d-%s" % (epiweek, state))
113+
raise Exception(f"missing data for {int(epiweek)}-{state}")
114114
return total
115115

116116

@@ -166,7 +166,7 @@ def extract(first_week=None, last_week=None, test_mode=False):
166166
cur.execute("SELECT max(`epiweek`) FROM `cdc_meta`")
167167
for (last_week,) in cur:
168168
pass
169-
print("extracting %d--%d" % (first_week, last_week))
169+
print(f"extracting {int(first_week)}--{int(last_week)}")
170170

171171
# update each epiweek
172172
for epiweek in flu.range_epiweeks(first_week, last_week, inclusive=True):
@@ -180,7 +180,7 @@ def extract(first_week=None, last_week=None, test_mode=False):
180180
store_result(cur, epiweek, state, *nums, total)
181181
print(f" {epiweek}-{state}: {' '.join(str(n) for n in nums)} ({total})")
182182
except Exception as ex:
183-
print(" %d-%s: failed" % (epiweek, state), ex)
183+
print(f" {int(epiweek)}-{state}: failed", ex)
184184
# raise ex
185185
sys.stdout.flush()
186186

src/acquisition/cdcp/cdc_upload.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def parse_zip(zf, level=1):
232232
if handler is not None:
233233
with zf.open(name) as temp:
234234
count = handler(csv.reader(io.StringIO(str(temp.read(), "utf-8"))))
235-
print(prefix, " %d rows" % count)
235+
print(prefix, f" {int(count)} rows")
236236
else:
237237
print(prefix, " (ignored)")
238238

src/acquisition/ecdc/ecdc_db_update.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def safe_int(i):
8787
def get_rows(cnx, table="ecdc_ili"):
8888
# Count and return the number of rows in the `ecdc_ili` table.
8989
select = cnx.cursor()
90-
select.execute("SELECT count(1) num FROM %s" % table)
90+
select.execute(f"SELECT count(1) num FROM {table}")
9191
for (num,) in select:
9292
pass
9393
select.close()
@@ -100,7 +100,7 @@ def update_from_file(issue, date, dir, test_mode=False):
100100
u, p = secrets.db.epi
101101
cnx = mysql.connector.connect(user=u, password=p, database="epidata")
102102
rows1 = get_rows(cnx, "ecdc_ili")
103-
print("rows before: %d" % (rows1))
103+
print(f"rows before: {int(rows1)}")
104104
insert = cnx.cursor()
105105

106106
# load the data, ignoring empty rows
@@ -115,9 +115,9 @@ def update_from_file(issue, date, dir, test_mode=False):
115115
row["region"] = data[4]
116116
row["incidence_rate"] = data[3]
117117
rows.append(row)
118-
print(" loaded %d rows" % len(rows))
118+
print(f" loaded {len(rows)} rows")
119119
entries = [obj for obj in rows if obj]
120-
print(" found %d entries" % len(entries))
120+
print(f" found {len(entries)} entries")
121121

122122
sql = """
123123
INSERT INTO
@@ -149,7 +149,7 @@ def update_from_file(issue, date, dir, test_mode=False):
149149
else:
150150
cnx.commit()
151151
rows2 = get_rows(cnx)
152-
print("rows after: %d (added %d)" % (rows2, rows2 - rows1))
152+
print(f"rows after: {int(rows2)} (added {int(rows2 - rows1)})")
153153
cnx.close()
154154

155155

@@ -171,7 +171,7 @@ def main():
171171
raise Exception("--file and --issue must both be present or absent")
172172

173173
date = datetime.datetime.now().strftime("%Y-%m-%d")
174-
print("assuming release date is today, %s" % date)
174+
print(f"assuming release date is today, {date}")
175175

176176
ensure_tables_exist()
177177
if args.file:

src/acquisition/flusurv/flusurv.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def fetch_json(path, payload, call_count=1, requests_impl=requests):
8080

8181
# it's polite to self-identify this "bot"
8282
delphi_url = "https://delphi.cmu.edu/index.html"
83-
user_agent = "Mozilla/5.0 (compatible; delphibot/1.0; +%s)" % delphi_url
83+
user_agent = f"Mozilla/5.0 (compatible; delphibot/1.0; +{delphi_url})"
8484

8585
# the FluSurv AMF server
8686
flusurv_url = "https://gis.cdc.gov/GRASP/Flu3/" + path
@@ -106,7 +106,7 @@ def fetch_json(path, payload, call_count=1, requests_impl=requests):
106106
if resp.status_code == 500 and call_count <= 2:
107107
# the server often fails with this status, so wait and retry
108108
delay = 10 * call_count
109-
print("got status %d, will retry in %d sec..." % (resp.status_code, delay))
109+
print(f"got status {int(resp.status_code)}, will retry in {int(delay)} sec...")
110110
time.sleep(delay)
111111
return fetch_json(path, payload, call_count=call_count + 1)
112112
elif resp.status_code != 200:
@@ -180,7 +180,7 @@ def extract_from_object(data_in):
180180
raise Exception("no data found")
181181

182182
# print the result and return flu data
183-
print("found data for %d weeks" % len(data_out))
183+
print(f"found data for {len(data_out)} weeks")
184184
return data_out
185185

186186

src/acquisition/flusurv/flusurv_update.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def update(issue, location_name, test_mode=False):
108108
cnx = mysql.connector.connect(host=secrets.db.host, user=u, password=p, database="epidata")
109109
cur = cnx.cursor()
110110
rows1 = get_rows(cur)
111-
print("rows before: %d" % rows1)
111+
print(f"rows before: {int(rows1)}")
112112

113113
# SQL for insert/update
114114
sql = """
@@ -148,7 +148,7 @@ def update(issue, location_name, test_mode=False):
148148

149149
# commit and disconnect
150150
rows2 = get_rows(cur)
151-
print("rows after: %d (+%d)" % (rows2, rows2 - rows1))
151+
print(f"rows after: {int(rows2)} (+{int(rows2 - rows1)})")
152152
cur.close()
153153
if test_mode:
154154
print("test mode: not committing database changes")
@@ -170,7 +170,7 @@ def main():
170170

171171
# scrape current issue from the main page
172172
issue = flusurv.get_current_issue()
173-
print("current issue: %d" % issue)
173+
print(f"current issue: {int(issue)}")
174174

175175
# fetch flusurv data
176176
if args.location == "all":

src/acquisition/fluview/fluview.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -108,23 +108,23 @@ def get_tier_ids(name):
108108
location_ids[Key.TierType.hhs] = sorted(set(location_ids[Key.TierType.hhs]))
109109
num = len(location_ids[Key.TierType.hhs])
110110
if num != 10:
111-
raise Exception("expected 10 hhs regions, found %d" % num)
111+
raise Exception(f"expected 10 hhs regions, found {int(num)}")
112112

113113
# add location ids for census divisions
114114
for row in data[Key.TierListEntry.cen]:
115115
location_ids[Key.TierType.cen].append(row[Key.TierIdEntry.cen])
116116
location_ids[Key.TierType.cen] = sorted(set(location_ids[Key.TierType.cen]))
117117
num = len(location_ids[Key.TierType.cen])
118118
if num != 9:
119-
raise Exception("expected 9 census divisions, found %d" % num)
119+
raise Exception(f"expected 9 census divisions, found {int(num)}")
120120

121121
# add location ids for states
122122
for row in data[Key.TierListEntry.sta]:
123123
location_ids[Key.TierType.sta].append(row[Key.TierIdEntry.sta])
124124
location_ids[Key.TierType.sta] = sorted(set(location_ids[Key.TierType.sta]))
125125
num = len(location_ids[Key.TierType.sta])
126126
if num != 57:
127-
raise Exception("expected 57 states/territories/cities, found %d" % num)
127+
raise Exception(f"expected 57 states/territories/cities, found {int(num)}")
128128

129129
# return a useful subset of the metadata
130130
# (latest epiweek, latest season, tier ids, location ids)
@@ -181,7 +181,7 @@ def save_latest(path=None):
181181
data = fetch_metadata(sess)
182182
info = get_issue_and_locations(data)
183183
issue = info["epiweek"]
184-
print("current issue: %d" % issue)
184+
print(f"current issue: {int(issue)}")
185185

186186
# establish timing
187187
dt = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -200,7 +200,7 @@ def save_latest(path=None):
200200
("cen", Key.TierType.cen),
201201
("sta", Key.TierType.sta),
202202
):
203-
name = "ilinet_%s_%d_%s.zip" % (delphi_name, issue, dt)
203+
name = f"ilinet_{delphi_name}_{int(issue)}_{dt}.zip"
204204
if path is None:
205205
filename = name
206206
else:
@@ -209,12 +209,12 @@ def save_latest(path=None):
209209
locations = info["location_ids"][cdc_name]
210210

211211
# download and show timing information
212-
print("downloading %s" % delphi_name)
212+
print(f"downloading {delphi_name}")
213213
t0 = time.time()
214214
size = download_data(tier_id, locations, seasons, filename)
215215
t1 = time.time()
216216

217-
print(" saved %s (%d bytes in %.1f seconds)" % (filename, size, t1 - t0))
217+
print(f" saved {filename} ({int(size)} bytes in {t1 - t0:.1f} seconds)")
218218
files.append(filename)
219219

220220
# return the current issue and the list of downloaded files

0 commit comments

Comments
 (0)