From c099d10b1a4ee8e54b7732f80cd4de502c07f96f Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Wed, 30 Aug 2023 02:38:07 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- days/01-03-datetimes/code/datetime_date.py | 8 +++-- .../code/datetime_timedelta.py | 4 +-- days/10-12-pytest/fizzbuzz/fizzbuzz.py | 8 ++--- days/10-12-pytest/guess/guess.py | 3 +- days/13-15-text-games/data/sample_reader.py | 6 ++-- days/13-15-text-games/dnd_game/program.py | 16 ++++----- days/19-21-itertools/code/traffic_lights.py | 6 ++-- .../demo/movie_search_error_edition/api.py | 6 +--- .../movie_search_error_edition/program.py | 2 +- .../starter_movie_search_error_edition/api.py | 6 +--- .../demo/movie_search_logging_edition/api.py | 9 ++--- .../movie_search_logging_edition/program.py | 11 +++--- .../demo/starter_movie_search/api.py | 6 +--- .../demo/starter_movie_search/program.py | 2 +- .../weather_csv_demo/program.py | 6 ++-- .../weather_csv_demo/research.py | 6 +--- days/40-42-json-data/code/json_dicts.py | 11 ++---- .../43-45-search-api/demo/movie_search/api.py | 6 +--- .../scraper_demo/scraper.py | 4 +-- .../demo/final_csv_code/program.py | 6 ++-- .../demo/final_csv_code/program_pycharm.py | 6 ++-- .../demo/final_csv_code/research.py | 4 +-- .../demo/starter_csv_code/program.py | 6 ++-- .../demo/starter_csv_code/research.py | 6 +--- days/52-54-feedparser/code/parser.py | 2 +- days/55-57-uplink/demo/blog_client.py | 6 ++-- days/55-57-uplink/demo/program.py | 4 +-- days/67-69-pyperclip/code/text-replacer.py | 6 ++-- .../code/excel_automation.py | 2 +- .../code/openpyxl_commands.py | 6 ++-- days/79-81-sqlite3/demos/generatedb.py | 10 +++--- days/79-81-sqlite3/demos/populatedb.py | 7 ++-- .../pypoint-100days/forms/AddDocForm.py | 9 +++-- .../pypoint-100days/forms/AllDocsForm.py | 2 +- .../server_modules/data_layer.py | 8 +++-- .../code/inventory.py | 34 +++++++++++-------- .../persistent_rps/data/session_factory.py | 2 +- .../demo/persistent_rps/game.py | 16 ++++----- .../demo/persistent_rps/game_decider.py | 7 ++-- .../demo/persistent_rps/program.py | 4 +-- .../demo/persistent_rps_starter/game.py | 16 ++++----- .../persistent_rps_starter/game_decider.py | 7 ++-- .../persistent_rps_starter/game_service.py | 4 +-- .../demo/persistent_rps_starter/program.py | 4 +-- days/94-96-guis/demos/final_search_app/api.py | 10 ++---- .../demos/starter_search_app/api.py | 10 ++---- .../demo_app/client/game_app.py | 16 +++++---- .../demo_app/client/uplink_helpers.py | 6 ++-- .../demo_app/web/game_logic/game.py | 8 +++-- .../demo_app/web/game_logic/game_decider.py | 17 +++------- .../demo_app/web/game_logic/game_service.py | 4 +-- .../web/game_logic/session_factory.py | 2 +- 52 files changed, 155 insertions(+), 228 deletions(-) diff --git a/days/01-03-datetimes/code/datetime_date.py b/days/01-03-datetimes/code/datetime_date.py index 17e85784..95c408ba 100644 --- a/days/01-03-datetimes/code/datetime_date.py +++ b/days/01-03-datetimes/code/datetime_date.py @@ -3,10 +3,10 @@ from datetime import date from datetime import datetime -datetime.today() +datetime.now() # datetime.datetime(2021, 1, 19, 14, 38, 52, 133483) -today = datetime.today() +today = datetime.now() type(today) # @@ -36,6 +36,8 @@ # We need to use != & == rather than is / is not for comparison. Sorry for the mistake in the video. if christmas != today_date: - print("Sorry there are still " + str((christmas - today_date).days) + " until Christmas!") + print( + f"Sorry there are still {str((christmas - today_date).days)} until Christmas!" + ) else: print("Yay it's Christmas!") diff --git a/days/01-03-datetimes/code/datetime_timedelta.py b/days/01-03-datetimes/code/datetime_timedelta.py index 28d7a381..8f445efb 100644 --- a/days/01-03-datetimes/code/datetime_timedelta.py +++ b/days/01-03-datetimes/code/datetime_timedelta.py @@ -12,8 +12,6 @@ #36000 t.hours -#Traceback (most recent call last): - #File "", line 1, in t.hours #AttributeError: 'datetime.timedelta' object has no attribute 'hours' t.seconds / 60 / 60 @@ -27,7 +25,7 @@ eta = timedelta(hours=6) -today = datetime.today() +today = datetime.now() today #datetime.datetime(2018, 2, 19, 14, 55, 19, 197404 diff --git a/days/10-12-pytest/fizzbuzz/fizzbuzz.py b/days/10-12-pytest/fizzbuzz/fizzbuzz.py index d51a3437..fff72e51 100644 --- a/days/10-12-pytest/fizzbuzz/fizzbuzz.py +++ b/days/10-12-pytest/fizzbuzz/fizzbuzz.py @@ -1,8 +1,4 @@ def fizzbuzz(n): - if n % 3 == 0 and n % 5 == 0: - return 'Fizz Buzz' if n % 3 == 0: - return 'Fizz' - if n % 5 == 0: - return 'Buzz' - return n + return 'Fizz Buzz' if n % 5 == 0 else 'Fizz' + return 'Buzz' if n % 5 == 0 else n diff --git a/days/10-12-pytest/guess/guess.py b/days/10-12-pytest/guess/guess.py index b2ed9efc..29df9711 100644 --- a/days/10-12-pytest/guess/guess.py +++ b/days/10-12-pytest/guess/guess.py @@ -72,8 +72,7 @@ def __call__(self): print(ve) continue - win = self._validate_guess(guess) - if win: + if win := self._validate_guess(guess): guess_str = self.num_guesses == 1 and "guess" or "guesses" print(f'It took you {self.num_guesses} {guess_str}') self._win = True diff --git a/days/13-15-text-games/data/sample_reader.py b/days/13-15-text-games/data/sample_reader.py index d57c028e..046f0aa0 100644 --- a/days/13-15-text-games/data/sample_reader.py +++ b/days/13-15-text-games/data/sample_reader.py @@ -12,10 +12,10 @@ def read_roll(row: dict): del row['Attacker'] del row[name] - print("Roll: {}".format(name)) - for k in row.keys(): + print(f"Roll: {name}") + for k in row: can_defeat = row[k].strip().lower() == 'win' - print(" * {} will defeat {}? {}".format(name, k, can_defeat)) + print(f" * {name} will defeat {k}? {can_defeat}") print() diff --git a/days/13-15-text-games/dnd_game/program.py b/days/13-15-text-games/dnd_game/program.py index deaf3b46..93cb3146 100644 --- a/days/13-15-text-games/dnd_game/program.py +++ b/days/13-15-text-games/dnd_game/program.py @@ -28,26 +28,24 @@ def game_loop(): active_creature = random.choice(creatures) - print('A {} of level {} has appear from a dark and foggy forest...' - .format(active_creature.name, active_creature.level)) + print( + f'A {active_creature.name} of level {active_creature.level} has appear from a dark and foggy forest...' + ) print() cmd = input('Do you [a]ttack, [r]unaway, or [l]ook around? ') if cmd == 'a': if hero.attack(active_creature): creatures.remove(active_creature) - print("The wizard defeated {}".format(active_creature.name)) + print(f"The wizard defeated {active_creature.name}") else: - print("The wizard has been defeat by the powerful {}".format(active_creature.name)) + print(f"The wizard has been defeat by the powerful {active_creature.name}") elif cmd == 'r': print('The wizard has become unsure of his power and flees!!!') elif cmd == 'l': - print('The wizard {} takes in the surroundings and sees:' - .format(hero.name)) + print(f'The wizard {hero.name} takes in the surroundings and sees:') for c in creatures: - print(" * {} of level {}".format( - c.name, c.level - )) + print(f" * {c.name} of level {c.level}") else: print("OK, exiting game... bye!") break diff --git a/days/19-21-itertools/code/traffic_lights.py b/days/19-21-itertools/code/traffic_lights.py index 5326fa65..1c813b18 100644 --- a/days/19-21-itertools/code/traffic_lights.py +++ b/days/19-21-itertools/code/traffic_lights.py @@ -11,13 +11,13 @@ def rg_timer(): def light_rotation(rotation): for colour in rotation: if colour == 'Amber': - print('Caution! The light is %s' % colour) + print(f'Caution! The light is {colour}') sleep(3) elif colour == 'Red': - print('STOP! The light is %s' % colour) + print(f'STOP! The light is {colour}') sleep(rg_timer()) else: - print('Go! The light is %s' % colour) + print(f'Go! The light is {colour}') sleep(rg_timer()) if __name__ == '__main__': diff --git a/days/25-27-error-handling/demo/movie_search_error_edition/api.py b/days/25-27-error-handling/demo/movie_search_error_edition/api.py index 044fc1ac..fb77b165 100644 --- a/days/25-27-error-handling/demo/movie_search_error_edition/api.py +++ b/days/25-27-error-handling/demo/movie_search_error_edition/api.py @@ -20,11 +20,7 @@ def find_movie_by_title(keyword: str) -> List[Movie]: results = resp.json() results = create_random_errors(results) - movies = [] - for r in results.get('hits'): - movies.append(Movie(**r)) - - return movies + return [Movie(**r) for r in results.get('hits')] def create_random_errors(results): diff --git a/days/25-27-error-handling/demo/movie_search_error_edition/program.py b/days/25-27-error-handling/demo/movie_search_error_edition/program.py index 85cfdf41..ff934076 100644 --- a/days/25-27-error-handling/demo/movie_search_error_edition/program.py +++ b/days/25-27-error-handling/demo/movie_search_error_edition/program.py @@ -15,7 +15,7 @@ def main(): except ValueError: print("ERROR: You must specify a search term.") except Exception as x: - print("Oh that didn't work!: {}".format(x)) + print(f"Oh that didn't work!: {x}") if __name__ == '__main__': diff --git a/days/25-27-error-handling/demo/starter_movie_search_error_edition/api.py b/days/25-27-error-handling/demo/starter_movie_search_error_edition/api.py index 044fc1ac..fb77b165 100644 --- a/days/25-27-error-handling/demo/starter_movie_search_error_edition/api.py +++ b/days/25-27-error-handling/demo/starter_movie_search_error_edition/api.py @@ -20,11 +20,7 @@ def find_movie_by_title(keyword: str) -> List[Movie]: results = resp.json() results = create_random_errors(results) - movies = [] - for r in results.get('hits'): - movies.append(Movie(**r)) - - return movies + return [Movie(**r) for r in results.get('hits')] def create_random_errors(results): diff --git a/days/31-33-logging/demo/movie_search_logging_edition/api.py b/days/31-33-logging/demo/movie_search_logging_edition/api.py index a6bc4a41..7e6edac0 100644 --- a/days/31-33-logging/demo/movie_search_logging_edition/api.py +++ b/days/31-33-logging/demo/movie_search_logging_edition/api.py @@ -16,7 +16,7 @@ def find_movie_by_title(keyword: str) -> List[Movie]: t0 = time.time() - api_log.trace('Starting search for {}'.format(keyword)) + api_log.trace(f'Starting search for {keyword}') if not keyword or not keyword.strip(): api_log.warn("No keyword supplied") @@ -25,16 +25,13 @@ def find_movie_by_title(keyword: str) -> List[Movie]: url = f'https://movieservice.talkpython.fm/api/search/{keyword}' resp = requests.get(url) - api_log.trace("Request finished, status code {}.".format(resp.status_code)) + api_log.trace(f"Request finished, status code {resp.status_code}.") resp.raise_for_status() results = resp.json() results = create_random_errors(results) - movies = [] - for r in results.get('hits'): - movies.append(Movie(**r)) - + movies = [Movie(**r) for r in results.get('hits')] t1 = time.time() api_log.trace('Finished search for {}, {:,} results in {} ms.'.format( diff --git a/days/31-33-logging/demo/movie_search_logging_edition/program.py b/days/31-33-logging/demo/movie_search_logging_edition/program.py index 29aa7a91..fbee9e2e 100644 --- a/days/31-33-logging/demo/movie_search_logging_edition/program.py +++ b/days/31-33-logging/demo/movie_search_logging_edition/program.py @@ -20,14 +20,14 @@ def main(): keyword, len(results))) except requests.exceptions.ConnectionError: msg = "Could not find server. Check your network connection." - print("ERROR: " + msg) + print(f"ERROR: {msg}") app_log.warn(msg) except ValueError: msg = "You must specify a search term." - print("ERROR: " + msg) + print(f"ERROR: {msg}") app_log.warn(msg) except Exception as x: - msg = "Oh that didn't work!: {}".format(x) + msg = f"Oh that didn't work!: {x}" print(msg) app_log.exception(x) @@ -40,10 +40,7 @@ def init_logging(filename: str = None): else: logbook.StreamHandler(sys.stdout, level=level).push_application() - msg = 'Logging initialized, level: {}, mode: {}'.format( - level, - "stdout mode" if not filename else 'file mode: ' + filename - ) + msg = f"""Logging initialized, level: {level}, mode: {"stdout mode" if not filename else f'file mode: {filename}'}""" logger = logbook.Logger('Startup') logger.notice(msg) diff --git a/days/31-33-logging/demo/starter_movie_search/api.py b/days/31-33-logging/demo/starter_movie_search/api.py index 044fc1ac..fb77b165 100644 --- a/days/31-33-logging/demo/starter_movie_search/api.py +++ b/days/31-33-logging/demo/starter_movie_search/api.py @@ -20,11 +20,7 @@ def find_movie_by_title(keyword: str) -> List[Movie]: results = resp.json() results = create_random_errors(results) - movies = [] - for r in results.get('hits'): - movies.append(Movie(**r)) - - return movies + return [Movie(**r) for r in results.get('hits')] def create_random_errors(results): diff --git a/days/31-33-logging/demo/starter_movie_search/program.py b/days/31-33-logging/demo/starter_movie_search/program.py index 85cfdf41..ff934076 100644 --- a/days/31-33-logging/demo/starter_movie_search/program.py +++ b/days/31-33-logging/demo/starter_movie_search/program.py @@ -15,7 +15,7 @@ def main(): except ValueError: print("ERROR: You must specify a search term.") except Exception as x: - print("Oh that didn't work!: {}".format(x)) + print(f"Oh that didn't work!: {x}") if __name__ == '__main__': diff --git a/days/37-39-csv-data-analysis/weather_csv_demo/program.py b/days/37-39-csv-data-analysis/weather_csv_demo/program.py index d0932975..94472119 100644 --- a/days/37-39-csv-data-analysis/weather_csv_demo/program.py +++ b/days/37-39-csv-data-analysis/weather_csv_demo/program.py @@ -9,18 +9,18 @@ def main(): print("The hottest 5 days:") days = research.hot_days() for idx, d in enumerate(days[:5]): - print("{}. {} F on {}".format(idx+1, d.actual_max_temp, d.date)) + print(f"{idx + 1}. {d.actual_max_temp} F on {d.date}") print() print("The coldest 5 days:") days = research.cold_days() for idx, d in enumerate(days[:5]): - print("{}. {} F on {}".format(idx+1, d.actual_min_temp, d.date)) + print(f"{idx + 1}. {d.actual_min_temp} F on {d.date}") print() print("The wettest 5 days:") days = research.wet_days() for idx, d in enumerate(days[:5]): - print("{}. {} inches of rain on {}".format(idx+1, d.actual_precipitation, d.date)) + print(f"{idx + 1}. {d.actual_precipitation} inches of rain on {d.date}") if __name__ == '__main__': diff --git a/days/37-39-csv-data-analysis/weather_csv_demo/research.py b/days/37-39-csv-data-analysis/weather_csv_demo/research.py index 19ac0eea..db67ca50 100644 --- a/days/37-39-csv-data-analysis/weather_csv_demo/research.py +++ b/days/37-39-csv-data-analysis/weather_csv_demo/research.py @@ -41,11 +41,7 @@ def parse_row(row): row['average_precipitation'] = float(row['average_precipitation']) row['record_precipitation'] = float(row['record_precipitation']) - record = Record( - **row - ) - - return record + return Record(**row) def hot_days() -> List[Record]: diff --git a/days/40-42-json-data/code/json_dicts.py b/days/40-42-json-data/code/json_dicts.py index d1ab6322..271d9d17 100644 --- a/days/40-42-json-data/code/json_dicts.py +++ b/days/40-42-json-data/code/json_dicts.py @@ -22,14 +22,9 @@ for item in data['mounts']['collected']: pprint(item['name']) -#Prints just the data associated with the 'name' key. - - -is_flying = [] -for mount in data['mounts']['collected']: - if mount['isFlying']: - is_flying.append(mount) - +is_flying = [ + mount for mount in data['mounts']['collected'] if mount['isFlying'] +] #Collects all of the applicable mounts and stores them as a list of dicts #You can then work with the data as normal: diff --git a/days/43-45-search-api/demo/movie_search/api.py b/days/43-45-search-api/demo/movie_search/api.py index d840ec7f..7e30780e 100644 --- a/days/43-45-search-api/demo/movie_search/api.py +++ b/days/43-45-search-api/demo/movie_search/api.py @@ -14,8 +14,4 @@ def find_movie_by_title(keyword: str) -> List[Movie]: resp.raise_for_status() results = resp.json() - movies = [] - for r in results.get('hits'): - movies.append(Movie(**r)) - - return movies + return [Movie(**r) for r in results.get('hits')] diff --git a/days/46-48-beautifulsoup4/scraper_demo/scraper.py b/days/46-48-beautifulsoup4/scraper_demo/scraper.py index 0f6a485c..008c29ac 100644 --- a/days/46-48-beautifulsoup4/scraper_demo/scraper.py +++ b/days/46-48-beautifulsoup4/scraper_demo/scraper.py @@ -10,13 +10,11 @@ def pull_site(): return raw_site_page def scrape(site): - header_list = [] #Create BeautifulSoup object soup = bs4.BeautifulSoup(site.text, 'html.parser') html_header_list = soup.select('.projectHeader') - for headers in html_header_list: - header_list.append(headers.getText()) + header_list = [headers.getText() for headers in html_header_list] for headers in header_list: print(headers) diff --git a/days/49-51-measuring-perf/demo/final_csv_code/program.py b/days/49-51-measuring-perf/demo/final_csv_code/program.py index a41dcf7a..f73ad604 100644 --- a/days/49-51-measuring-perf/demo/final_csv_code/program.py +++ b/days/49-51-measuring-perf/demo/final_csv_code/program.py @@ -21,17 +21,17 @@ def main(): print("The hottest 5 days:") for idx, d in enumerate(hot_days[:5]): - print("{}. {} F on {}".format(idx + 1, d.actual_max_temp, d.date)) + print(f"{idx + 1}. {d.actual_max_temp} F on {d.date}") print() print("The coldest 5 days:") for idx, d in enumerate(cold_days[:5]): - print("{}. {} F on {}".format(idx + 1, d.actual_min_temp, d.date)) + print(f"{idx + 1}. {d.actual_min_temp} F on {d.date}") print() print("The wettest 5 days:") for idx, d in enumerate(wet_days[:5]): - print("{}. {} inches of rain on {}".format(idx + 1, d.actual_precipitation, d.date)) + print(f"{idx + 1}. {d.actual_precipitation} inches of rain on {d.date}") if __name__ == '__main__': diff --git a/days/49-51-measuring-perf/demo/final_csv_code/program_pycharm.py b/days/49-51-measuring-perf/demo/final_csv_code/program_pycharm.py index 073a4d59..47dc9e95 100644 --- a/days/49-51-measuring-perf/demo/final_csv_code/program_pycharm.py +++ b/days/49-51-measuring-perf/demo/final_csv_code/program_pycharm.py @@ -13,17 +13,17 @@ def main(): print("The hottest 5 days:") for idx, d in enumerate(hot_days[:5]): - print("{}. {} F on {}".format(idx + 1, d.actual_max_temp, d.date)) + print(f"{idx + 1}. {d.actual_max_temp} F on {d.date}") print() print("The coldest 5 days:") for idx, d in enumerate(cold_days[:5]): - print("{}. {} F on {}".format(idx + 1, d.actual_min_temp, d.date)) + print(f"{idx + 1}. {d.actual_min_temp} F on {d.date}") print() print("The wettest 5 days:") for idx, d in enumerate(wet_days[:5]): - print("{}. {} inches of rain on {}".format(idx + 1, d.actual_precipitation, d.date)) + print(f"{idx + 1}. {d.actual_precipitation} inches of rain on {d.date}") if __name__ == '__main__': diff --git a/days/49-51-measuring-perf/demo/final_csv_code/research.py b/days/49-51-measuring-perf/demo/final_csv_code/research.py index 8e6986dc..c54c9c72 100644 --- a/days/49-51-measuring-perf/demo/final_csv_code/research.py +++ b/days/49-51-measuring-perf/demo/final_csv_code/research.py @@ -32,15 +32,13 @@ def parse_row(row): row['actual_max_temp'] = int(row['actual_max_temp']) row['actual_precipitation'] = float(row['actual_precipitation']) - record = Record( + return Record( date=row.get('date'), actual_min_temp=row.get('actual_min_temp'), actual_max_temp=row.get('actual_max_temp'), actual_precipitation=row.get('actual_precipitation'), ) - return record - # Before simpler parse_row: # 99 0.050 0.001 0.759 0.008 research.py:17(init) # 36135 0.321 0.000 0.351 0.000 research.py:30(parse_row) diff --git a/days/49-51-measuring-perf/demo/starter_csv_code/program.py b/days/49-51-measuring-perf/demo/starter_csv_code/program.py index d0932975..94472119 100644 --- a/days/49-51-measuring-perf/demo/starter_csv_code/program.py +++ b/days/49-51-measuring-perf/demo/starter_csv_code/program.py @@ -9,18 +9,18 @@ def main(): print("The hottest 5 days:") days = research.hot_days() for idx, d in enumerate(days[:5]): - print("{}. {} F on {}".format(idx+1, d.actual_max_temp, d.date)) + print(f"{idx + 1}. {d.actual_max_temp} F on {d.date}") print() print("The coldest 5 days:") days = research.cold_days() for idx, d in enumerate(days[:5]): - print("{}. {} F on {}".format(idx+1, d.actual_min_temp, d.date)) + print(f"{idx + 1}. {d.actual_min_temp} F on {d.date}") print() print("The wettest 5 days:") days = research.wet_days() for idx, d in enumerate(days[:5]): - print("{}. {} inches of rain on {}".format(idx+1, d.actual_precipitation, d.date)) + print(f"{idx + 1}. {d.actual_precipitation} inches of rain on {d.date}") if __name__ == '__main__': diff --git a/days/49-51-measuring-perf/demo/starter_csv_code/research.py b/days/49-51-measuring-perf/demo/starter_csv_code/research.py index fa2dcc7d..520dbba6 100644 --- a/days/49-51-measuring-perf/demo/starter_csv_code/research.py +++ b/days/49-51-measuring-perf/demo/starter_csv_code/research.py @@ -41,11 +41,7 @@ def parse_row(row): row['average_precipitation'] = float(row['average_precipitation']) row['record_precipitation'] = float(row['record_precipitation']) - record = Record( - **row - ) - - return record + return Record(**row) def hot_days() -> List[Record]: diff --git a/days/52-54-feedparser/code/parser.py b/days/52-54-feedparser/code/parser.py index 0dda2dc2..3c0ac0aa 100644 --- a/days/52-54-feedparser/code/parser.py +++ b/days/52-54-feedparser/code/parser.py @@ -8,4 +8,4 @@ if 'title' in feed.entries[0]: for entry in feed.entries: - print(entry.published + " - " + entry.title + ": " + entry.link) + print(f"{entry.published} - {entry.title}: {entry.link}") diff --git a/days/55-57-uplink/demo/blog_client.py b/days/55-57-uplink/demo/blog_client.py index 80b3495b..8848976e 100644 --- a/days/55-57-uplink/demo/blog_client.py +++ b/days/55-57-uplink/demo/blog_client.py @@ -29,9 +29,9 @@ def create_new_entry(self, title: str, content: str, if published is None: published = datetime.datetime.now().isoformat() - # noinspection PyTypeChecker - resp = self.internal_create_new_entry(title=title, content=content, view_count=views, published=published) - return resp + return self.internal_create_new_entry( + title=title, content=content, view_count=views, published=published + ) # Note: For some reason, the name of this method was freaking out the latest version of # uplink. So we just named it internal_. That's why it's different from the video. diff --git a/days/55-57-uplink/demo/program.py b/days/55-57-uplink/demo/program.py index bcb0593f..28e16f72 100644 --- a/days/55-57-uplink/demo/program.py +++ b/days/55-57-uplink/demo/program.py @@ -32,7 +32,7 @@ def read_posts(): response = svc.entry_by_id(selected_id) selected_post = response.json() - print("Details for selected_post: {}".format(selected_post.get('id'))) + print(f"Details for selected_post: {selected_post.get('id')}") print("Title: " + selected_post.get('title')) print("Written: " + selected_post.get('published')) print("Content: " + selected_post.get('content')) @@ -51,7 +51,7 @@ def write_post(): print() resp = resp.json() - print("Created new post successfully: {}".format(resp.get('id'))) + print(f"Created new post successfully: {resp.get('id')}") print() diff --git a/days/67-69-pyperclip/code/text-replacer.py b/days/67-69-pyperclip/code/text-replacer.py index 3dd5d32b..bb50b3e4 100644 --- a/days/67-69-pyperclip/code/text-replacer.py +++ b/days/67-69-pyperclip/code/text-replacer.py @@ -3,8 +3,7 @@ import pyperclip def paste_from_clipboard(): - text = pyperclip.paste() - return text + return pyperclip.paste() def copy_to_clipboard(new_text): @@ -15,8 +14,7 @@ def copy_to_clipboard(new_text): def replace_text(old_text): target = input('What would you like to replace? ') replacement = input('And what would you like to replace it with? ') - new_text = old_text.replace(target, replacement) - return new_text + return old_text.replace(target, replacement) if __name__ == "__main__": old_text = paste_from_clipboard() diff --git a/days/70-72-openpyxl-excel-automation/code/excel_automation.py b/days/70-72-openpyxl-excel-automation/code/excel_automation.py index c7578c7b..c5047655 100644 --- a/days/70-72-openpyxl-excel-automation/code/excel_automation.py +++ b/days/70-72-openpyxl-excel-automation/code/excel_automation.py @@ -7,7 +7,7 @@ maxrow = ws1.max_row def insert_sum(): - ws1['L' + str(maxrow)] = "=SUM(L2:L" + str(maxrow - 1) + ")" + ws1[f'L{str(maxrow)}'] = f"=SUM(L2:L{str(maxrow - 1)})" if __name__ == "__main__": diff --git a/days/70-72-openpyxl-excel-automation/code/openpyxl_commands.py b/days/70-72-openpyxl-excel-automation/code/openpyxl_commands.py index d23f9886..319e9c4c 100644 --- a/days/70-72-openpyxl-excel-automation/code/openpyxl_commands.py +++ b/days/70-72-openpyxl-excel-automation/code/openpyxl_commands.py @@ -13,7 +13,7 @@ ws1['B9'].value for row in range(2, ws1.max_row): - cell = 'B' + str(row) + cell = f'B{str(row)}' print(ws1[cell].value) ##### @@ -23,7 +23,7 @@ for row in range(2, 101): cell = col + str(row) profit_total += float(ws1[cell].value) - + print(profit_total) @@ -36,5 +36,5 @@ ws1['L703'] = "=SUM(L2:L701)" wb.save('Financial Sample.xlsx') -ws1['L' + str(ws1.max_row)] = "=SUM(L2:L" + str(ws1.max_row - 1) + ")" +ws1[f'L{str(ws1.max_row)}'] = f"=SUM(L2:L{str(ws1.max_row - 1)})" wb.save('Financial Sample.xlsx') diff --git a/days/79-81-sqlite3/demos/generatedb.py b/days/79-81-sqlite3/demos/generatedb.py index 82260c31..c9ad9dd6 100644 --- a/days/79-81-sqlite3/demos/generatedb.py +++ b/days/79-81-sqlite3/demos/generatedb.py @@ -6,16 +6,14 @@ @contextmanager def create_db(name): try: - conn = sqlite3.connect('%s.db' % name) - cursor = conn.cursor() - yield cursor + conn = sqlite3.connect(f'{name}.db') + yield conn.cursor() finally: conn.close() def prompt_for_name(): - name = input("What would you like to name your test db file?: ") - return name + return input("What would you like to name your test db file?: ") if __name__ == "__main__": name = prompt_for_name() @@ -23,4 +21,4 @@ def prompt_for_name(): cursor.execute("""CREATE TABLE test_table (col1 TEXT, col2 TEXT, col3 TEXT, col4 INT) """) - print('%s.db has been created' % name) + print(f'{name}.db has been created') diff --git a/days/79-81-sqlite3/demos/populatedb.py b/days/79-81-sqlite3/demos/populatedb.py index c92bba87..0b0269a9 100644 --- a/days/79-81-sqlite3/demos/populatedb.py +++ b/days/79-81-sqlite3/demos/populatedb.py @@ -4,18 +4,15 @@ def enter_details(): while True: - info = [] name = input('Enter a name: ') address = input('Enter an address: ') number = input('Enter a phone number: ') - for i in (name, address, number): - info.append(i) - + info = [name, address, number] with sqlite3.connect("addressbook.db") as connection: c = connection.cursor() c.execute("INSERT INTO Details VALUES(?, ?, ?)", info) print('Data inserted to database.\n') - + stop = input("Hit Q to to quit.\n") if stop.upper() == 'Q': break diff --git a/days/85-87-full-stack-easy/pypoint-100days/forms/AddDocForm.py b/days/85-87-full-stack-easy/pypoint-100days/forms/AddDocForm.py index b04de0de..05106afa 100644 --- a/days/85-87-full-stack-easy/pypoint-100days/forms/AddDocForm.py +++ b/days/85-87-full-stack-easy/pypoint-100days/forms/AddDocForm.py @@ -13,16 +13,15 @@ def __init__(self, **properties): self.drop_down_categories.items = [('select a category', None)] + [(c, c) for c in utilities.categories] self.label_errors.text = "" - def button_save_click (self, **event_args): - errors = self.validate() - if errors: + def button_save_click(self, **event_args): + if errors := self.validate(): self.label_errors.text = "\n".join(errors) return - + name = self.text_box_doc_name.text.strip() category = self.drop_down_categories.selected_value contents = self.text_area_contents.text.strip() - + utilities.create_doc(name, category, contents) utilities.go_home() diff --git a/days/85-87-full-stack-easy/pypoint-100days/forms/AllDocsForm.py b/days/85-87-full-stack-easy/pypoint-100days/forms/AllDocsForm.py index fcca8009..e460f1c4 100644 --- a/days/85-87-full-stack-easy/pypoint-100days/forms/AllDocsForm.py +++ b/days/85-87-full-stack-easy/pypoint-100days/forms/AllDocsForm.py @@ -16,7 +16,7 @@ def text_box_filter_change (self, **event_args): self.repeating_panel_docs.items = self.filtered_docs() def doc_to_text(self, d): - return "{} {} {}".format(d["name"], d["contents"], d["category"]["name"]) + return f'{d["name"]} {d["contents"]} {d["category"]["name"]}' def filtered_docs(self): txt = self.text_box_filter.text diff --git a/days/85-87-full-stack-easy/pypoint-100days/server_modules/data_layer.py b/days/85-87-full-stack-easy/pypoint-100days/server_modules/data_layer.py index 9efd7a27..872a66e7 100644 --- a/days/85-87-full-stack-easy/pypoint-100days/server_modules/data_layer.py +++ b/days/85-87-full-stack-easy/pypoint-100days/server_modules/data_layer.py @@ -5,8 +5,8 @@ @anvil.server.callable def all_docs(): - results = list(app_tables.documents.search(tables.order_by("created", ascending=False))) - return results + return list( + app_tables.documents.search(tables.order_by("created", ascending=False))) @anvil.server.callable @@ -26,7 +26,9 @@ def category_by_name(category_name): @anvil.server.callable def add_doc(doc_name, category_name, contents, views): now = datetime.datetime.now() - print("Server: Creating new document: {} {} {} {}".format(doc_name, category_name, views, contents, now)) + print( + f"Server: Creating new document: {doc_name} {category_name} {views} {contents}" + ) category = category_by_name(category_name) app_tables.documents.add_row(name=doc_name, category=category, contents=contents, views=views, created=now) return doc_by_name(doc_name) diff --git a/days/88-90-home-inventory-app/code/inventory.py b/days/88-90-home-inventory-app/code/inventory.py index 4399ccde..ddab5965 100644 --- a/days/88-90-home-inventory-app/code/inventory.py +++ b/days/88-90-home-inventory-app/code/inventory.py @@ -19,8 +19,7 @@ def first_launch(): def access_db(): try: conn = sqlite3.connect(DB) - cursor = conn.cursor() - yield cursor + yield conn.cursor() finally: conn.commit() conn.close() @@ -28,12 +27,13 @@ def access_db(): #A somewhat dirty menu. Improvement Point (make it a dict perhaps) def main_menu(): - menu = {} - menu['1'] = "Add Room." - menu['2'] = "Add Inventory." - menu['3'] = "View Inventory List." - menu['4'] = "Total Value." - menu['5'] = "Exit." + menu = { + '1': "Add Room.", + '2': "Add Inventory.", + '3': "View Inventory List.", + '4': "Total Value.", + '5': "Exit.", + } while True: print("\n") for item, desc in sorted(menu.items()): @@ -59,9 +59,14 @@ def add_room(): name = input("\nWhat name would you like to give the room? ") name = scrub(name) with access_db() as cursor: - cursor.execute("CREATE TABLE '" + name.lower() + "' """" + cursor.execute( + ( + f"CREATE TABLE '{name.lower()}" + "' " + """ (Item TEXT, Value REAL) - """) + """ + ) + ) print("\nA room with name %s has been added to the db.\n" % name) @@ -70,8 +75,7 @@ def list_rooms(): room_list = [] with access_db() as cursor: cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") - for room in cursor: - room_list.append(room[0]) + room_list.extend(room[0] for room in cursor) return room_list @@ -99,7 +103,7 @@ def add_inventory(selection): name = input("\nName of item: ") cost = input("Monetary value: ") with access_db() as cursor: - cursor.execute("INSERT INTO '" + selection + "' VALUES(?, ?)", [name, cost]) + cursor.execute(f"INSERT INTO '{selection}' VALUES(?, ?)", [name, cost]) cont = input('\nHit Q to quit or any other key to continue: ') if cont.lower() == 'q': @@ -110,7 +114,7 @@ def add_inventory(selection): def view_inventory(selection): total = 0 with access_db() as cursor: - cursor.execute("SELECT * FROM '" + selection + "'") + cursor.execute(f"SELECT * FROM '{selection}'") print("\n") for data in cursor: print("%s: $%d" % (data[0], data[1])) @@ -124,7 +128,7 @@ def calc_total(): room_list = list_rooms() with access_db() as cursor: for room in room_list: - cursor.execute("SELECT value FROM '" + room + "'") + cursor.execute(f"SELECT value FROM '{room}'") for value in cursor: total += value[0] print("\nTotal Value of all rooms: $%d" % total) diff --git a/days/91-93-sqlalchemy/demo/persistent_rps/data/session_factory.py b/days/91-93-sqlalchemy/demo/persistent_rps/data/session_factory.py index fa1ff976..ccfbb936 100644 --- a/days/91-93-sqlalchemy/demo/persistent_rps/data/session_factory.py +++ b/days/91-93-sqlalchemy/demo/persistent_rps/data/session_factory.py @@ -14,7 +14,7 @@ def global_init(): global __factory full_file = db_folder.get_db_path('rock_paper_scissors.sqlite') - conn_str = 'sqlite:///' + full_file + conn_str = f'sqlite:///{full_file}' engine = sqlalchemy.create_engine(conn_str, echo=False) ModelBase.metadata.create_all(engine) diff --git a/days/91-93-sqlalchemy/demo/persistent_rps/game.py b/days/91-93-sqlalchemy/demo/persistent_rps/game.py index 47bf27c9..6ea2b3fc 100644 --- a/days/91-93-sqlalchemy/demo/persistent_rps/game.py +++ b/days/91-93-sqlalchemy/demo/persistent_rps/game.py @@ -13,7 +13,7 @@ def game_loop(player1, player2, rolls): p1_wins = 0 p2_wins = 0 while count <= 5 or (p1_wins == p2_wins and count > 5): - print(" ------------- ROUND {} --------------".format(count)) + print(f" ------------- ROUND {count} --------------") print() p1_roll = get_roll_choice(rolls) p2_roll = random.choice(rolls) @@ -22,10 +22,10 @@ def game_loop(player1, player2, rolls): if outcome == game_decider.Decision.tie: msg = "Tie!" elif outcome == game_decider.Decision.win: - msg = player1.name + " wins!" + msg = f"{player1.name} wins!" p1_wins += 1 else: - msg = player1.name + " is defeated!" + msg = f"{player1.name} is defeated!" p2_wins += 1 final_move = count >= 5 and p1_wins != p2_wins @@ -35,8 +35,8 @@ def game_loop(player1, player2, rolls): p2_wins > p1_wins and final_move, count) print() - print(player1.name + " throws " + p1_roll.name) - print(player2.name + " throws " + p2_roll.name) + print(f"{player1.name} throws {p1_roll.name}") + print(f"{player2.name} throws {p2_roll.name}") print(msg) print() print(" -------------------------------------") @@ -45,9 +45,9 @@ def game_loop(player1, player2, rolls): count += 1 if p1_wins < p2_wins: - print(player2.name + " wins {} to {}".format(p2_wins, p1_wins)) + print(f"{player2.name} wins {p2_wins} to {p1_wins}") else: - print(player1.name + " wins {} to {}".format(p1_wins, p2_wins)) + print(f"{player1.name} wins {p1_wins} to {p2_wins}") show_history([player1, player2], rolls, game_id) @@ -60,7 +60,7 @@ def show_history(players, rolls, game_id): def get_roll_choice(rolls: List[Roll]): print("Rolls: ") for idx, r in enumerate(rolls): - print("{}. {}".format(idx + 1, r.name)) + print(f"{idx + 1}. {r.name}") print() idx = int(input("What roll will you throw? ")) return rolls[idx - 1] diff --git a/days/91-93-sqlalchemy/demo/persistent_rps/game_decider.py b/days/91-93-sqlalchemy/demo/persistent_rps/game_decider.py index b7cacfc6..b8e303c0 100644 --- a/days/91-93-sqlalchemy/demo/persistent_rps/game_decider.py +++ b/days/91-93-sqlalchemy/demo/persistent_rps/game_decider.py @@ -20,10 +20,7 @@ def decide(roll1: Roll, roll2: Roll) -> Decision: roll1_wins = roll2.name in __winner_lookup[roll1.name] - if roll1_wins: - return Decision.win - else: - return Decision.lose + return Decision.win if roll1_wins else Decision.lose def __build_decisions(): @@ -44,7 +41,7 @@ def __build_roll(row: dict): del row[name] __winner_lookup[name] = set() - for k in row.keys(): + for k in row: can_defeat = row[k].strip().lower() == 'win' if can_defeat: __winner_lookup[name].add(k) diff --git a/days/91-93-sqlalchemy/demo/persistent_rps/program.py b/days/91-93-sqlalchemy/demo/persistent_rps/program.py index 1bcbfcff..bfb2dc99 100644 --- a/days/91-93-sqlalchemy/demo/persistent_rps/program.py +++ b/days/91-93-sqlalchemy/demo/persistent_rps/program.py @@ -26,9 +26,7 @@ def build_rolls() -> List[Roll]: rolls = [] with open('battle-table.csv') as fin: reader = csv.DictReader(fin) - for row in reader: - rolls.append(build_roll(row)) - + rolls.extend(build_roll(row) for row in reader) return rolls diff --git a/days/91-93-sqlalchemy/demo/persistent_rps_starter/game.py b/days/91-93-sqlalchemy/demo/persistent_rps_starter/game.py index 47bf27c9..6ea2b3fc 100644 --- a/days/91-93-sqlalchemy/demo/persistent_rps_starter/game.py +++ b/days/91-93-sqlalchemy/demo/persistent_rps_starter/game.py @@ -13,7 +13,7 @@ def game_loop(player1, player2, rolls): p1_wins = 0 p2_wins = 0 while count <= 5 or (p1_wins == p2_wins and count > 5): - print(" ------------- ROUND {} --------------".format(count)) + print(f" ------------- ROUND {count} --------------") print() p1_roll = get_roll_choice(rolls) p2_roll = random.choice(rolls) @@ -22,10 +22,10 @@ def game_loop(player1, player2, rolls): if outcome == game_decider.Decision.tie: msg = "Tie!" elif outcome == game_decider.Decision.win: - msg = player1.name + " wins!" + msg = f"{player1.name} wins!" p1_wins += 1 else: - msg = player1.name + " is defeated!" + msg = f"{player1.name} is defeated!" p2_wins += 1 final_move = count >= 5 and p1_wins != p2_wins @@ -35,8 +35,8 @@ def game_loop(player1, player2, rolls): p2_wins > p1_wins and final_move, count) print() - print(player1.name + " throws " + p1_roll.name) - print(player2.name + " throws " + p2_roll.name) + print(f"{player1.name} throws {p1_roll.name}") + print(f"{player2.name} throws {p2_roll.name}") print(msg) print() print(" -------------------------------------") @@ -45,9 +45,9 @@ def game_loop(player1, player2, rolls): count += 1 if p1_wins < p2_wins: - print(player2.name + " wins {} to {}".format(p2_wins, p1_wins)) + print(f"{player2.name} wins {p2_wins} to {p1_wins}") else: - print(player1.name + " wins {} to {}".format(p1_wins, p2_wins)) + print(f"{player1.name} wins {p1_wins} to {p2_wins}") show_history([player1, player2], rolls, game_id) @@ -60,7 +60,7 @@ def show_history(players, rolls, game_id): def get_roll_choice(rolls: List[Roll]): print("Rolls: ") for idx, r in enumerate(rolls): - print("{}. {}".format(idx + 1, r.name)) + print(f"{idx + 1}. {r.name}") print() idx = int(input("What roll will you throw? ")) return rolls[idx - 1] diff --git a/days/91-93-sqlalchemy/demo/persistent_rps_starter/game_decider.py b/days/91-93-sqlalchemy/demo/persistent_rps_starter/game_decider.py index b7cacfc6..b8e303c0 100644 --- a/days/91-93-sqlalchemy/demo/persistent_rps_starter/game_decider.py +++ b/days/91-93-sqlalchemy/demo/persistent_rps_starter/game_decider.py @@ -20,10 +20,7 @@ def decide(roll1: Roll, roll2: Roll) -> Decision: roll1_wins = roll2.name in __winner_lookup[roll1.name] - if roll1_wins: - return Decision.win - else: - return Decision.lose + return Decision.win if roll1_wins else Decision.lose def __build_decisions(): @@ -44,7 +41,7 @@ def __build_roll(row: dict): del row[name] __winner_lookup[name] = set() - for k in row.keys(): + for k in row: can_defeat = row[k].strip().lower() == 'win' if can_defeat: __winner_lookup[name].add(k) diff --git a/days/91-93-sqlalchemy/demo/persistent_rps_starter/game_service.py b/days/91-93-sqlalchemy/demo/persistent_rps_starter/game_service.py index 19ddf276..0ace1165 100644 --- a/days/91-93-sqlalchemy/demo/persistent_rps_starter/game_service.py +++ b/days/91-93-sqlalchemy/demo/persistent_rps_starter/game_service.py @@ -49,6 +49,4 @@ def find_roll(name: str) -> Optional['Roll']: def create_roll(name: str) -> 'Roll': - roll = Roll(name) - # TODO: Save - return roll + return Roll(name) diff --git a/days/91-93-sqlalchemy/demo/persistent_rps_starter/program.py b/days/91-93-sqlalchemy/demo/persistent_rps_starter/program.py index 10a28cef..60363270 100644 --- a/days/91-93-sqlalchemy/demo/persistent_rps_starter/program.py +++ b/days/91-93-sqlalchemy/demo/persistent_rps_starter/program.py @@ -25,9 +25,7 @@ def build_rolls() -> List[Roll]: rolls = [] with open('battle-table.csv') as fin: reader = csv.DictReader(fin) - for row in reader: - rolls.append(build_roll(row)) - + rolls.extend(build_roll(row) for row in reader) return rolls diff --git a/days/94-96-guis/demos/final_search_app/api.py b/days/94-96-guis/demos/final_search_app/api.py index 5f141cc8..3d226e67 100644 --- a/days/94-96-guis/demos/final_search_app/api.py +++ b/days/94-96-guis/demos/final_search_app/api.py @@ -22,17 +22,11 @@ def find_movie_by_imdb_code(imdb_code: str) -> List[Movie]: resp = requests.get(url) resp.raise_for_status() result = resp.json() - if not result.get('imdb_code'): - return [] - - return [Movie(**result)] + return [] if not result.get('imdb_code') else [Movie(**result)] def __get_results(url): resp = requests.get(url) resp.raise_for_status() results = resp.json() - movies = [] - for r in results.get('hits'): - movies.append(Movie(**r)) - return movies + return [Movie(**r) for r in results.get('hits')] diff --git a/days/94-96-guis/demos/starter_search_app/api.py b/days/94-96-guis/demos/starter_search_app/api.py index 5f141cc8..3d226e67 100644 --- a/days/94-96-guis/demos/starter_search_app/api.py +++ b/days/94-96-guis/demos/starter_search_app/api.py @@ -22,17 +22,11 @@ def find_movie_by_imdb_code(imdb_code: str) -> List[Movie]: resp = requests.get(url) resp.raise_for_status() result = resp.json() - if not result.get('imdb_code'): - return [] - - return [Movie(**result)] + return [] if not result.get('imdb_code') else [Movie(**result)] def __get_results(url): resp = requests.get(url) resp.raise_for_status() results = resp.json() - movies = [] - for r in results.get('hits'): - movies.append(Movie(**r)) - return movies + return [Movie(**r) for r in results.get('hits')] diff --git a/days/97-99-online-game-api/demo_app/client/game_app.py b/days/97-99-online-game-api/demo_app/client/game_app.py index b7e0d31d..b39189a9 100644 --- a/days/97-99-online-game-api/demo_app/client/game_app.py +++ b/days/97-99-online-game-api/demo_app/client/game_app.py @@ -11,7 +11,7 @@ def main(): print() print("TOP SCORES") for s in svc.top_scores(): - print("{} scored {}".format(s.get('player').get('name'), s.get('score'))) + print(f"{s.get('player').get('name')} scored {s.get('score')}") print() game_id = svc.create_game().get('game_id') @@ -24,14 +24,18 @@ def main(): roll = random.choice(rolls) rnd = svc.play_round(game_id=game_id, user=name, roll=roll) is_over = rnd.get('is_final_round') - print("Round {}".format(rnd.get('round_number'))) - print("{} rolls {}".format(name, roll)) - print("{} rolls {}".format(rnd.get('opponent').get('name'), rnd.get('computer_roll').get('name'))) - print("Resulting in {}".format(rnd.get('round_outcome'))) + print(f"Round {rnd.get('round_number')}") + print(f"{name} rolls {roll}") + print( + f"{rnd.get('opponent').get('name')} rolls {rnd.get('computer_roll').get('name')}" + ) + print(f"Resulting in {rnd.get('round_outcome')}") print("") game_status = svc.game_status(game_id) - print("Game is over, outcome: Winner: {}".format(game_status.get('winner').get('name'))) + print( + f"Game is over, outcome: Winner: {game_status.get('winner').get('name')}" + ) if __name__ == '__main__': diff --git a/days/97-99-online-game-api/demo_app/client/uplink_helpers.py b/days/97-99-online-game-api/demo_app/client/uplink_helpers.py index fd2850e8..022bffbf 100644 --- a/days/97-99-online-game-api/demo_app/client/uplink_helpers.py +++ b/days/97-99-online-game-api/demo_app/client/uplink_helpers.py @@ -17,6 +17,6 @@ def response_to_data(response: Response): try: return response.json() except Exception as x: - raise FormatError("Invalid format, could not parse JSON. Error: {}, status={}, text={}".format( - x, response.status_code, response.text - )) from x + raise FormatError( + f"Invalid format, could not parse JSON. Error: {x}, status={response.status_code}, text={response.text}" + ) from x diff --git a/days/97-99-online-game-api/demo_app/web/game_logic/game.py b/days/97-99-online-game-api/demo_app/web/game_logic/game.py index 4889af25..aacc0b18 100644 --- a/days/97-99-online-game-api/demo_app/web/game_logic/game.py +++ b/days/97-99-online-game-api/demo_app/web/game_logic/game.py @@ -36,8 +36,12 @@ def play(self): self.record_roll(d.reversed(), self.player2, self.p2_roll, self.player2_wins) print("RECORDING ROUND") - print("Player 1: {}, prior wins {}, outcome: {}".format(self.p1_roll.name, self.player1_wins, d)) - print("Player 2: {}, prior wins {}, outcome: {}".format(self.p2_roll.name, self.player2_wins, d.reversed())) + print( + f"Player 1: {self.p1_roll.name}, prior wins {self.player1_wins}, outcome: {d}" + ) + print( + f"Player 2: {self.p2_roll.name}, prior wins {self.player2_wins}, outcome: {d.reversed()}" + ) print() self.is_over = game_service.is_game_over(self.game_id) diff --git a/days/97-99-online-game-api/demo_app/web/game_logic/game_decider.py b/days/97-99-online-game-api/demo_app/web/game_logic/game_decider.py index 5aad90b2..559cdf34 100644 --- a/days/97-99-online-game-api/demo_app/web/game_logic/game_decider.py +++ b/days/97-99-online-game-api/demo_app/web/game_logic/game_decider.py @@ -15,20 +15,14 @@ class Decision(Enum): def reversed(self): if self == Decision.win: return Decision.lose - if self == Decision.lose: - return Decision.win - - return Decision.tie + return Decision.win if self == Decision.lose else Decision.tie def __str__(self): if self == Decision.win: return 'win' if self == Decision.lose: return 'lose' - if self == Decision.tie: - return 'tie' - - return "UNKNOWN DECISION: {}".format(self) + return 'tie' if self == Decision.tie else f"UNKNOWN DECISION: {self}" def decide(roll1: Roll, roll2: Roll) -> Decision: @@ -39,10 +33,7 @@ def decide(roll1: Roll, roll2: Roll) -> Decision: roll1_wins = roll2.name in __winner_lookup[roll1.name] - if roll1_wins: - return Decision.win - else: - return Decision.lose + return Decision.win if roll1_wins else Decision.lose def __build_decisions(): @@ -65,7 +56,7 @@ def __build_roll(row: dict): del row[name] __winner_lookup[name] = set() - for k in row.keys(): + for k in row: can_defeat = row[k].strip().lower() == 'win' if can_defeat: __winner_lookup[name].add(k) diff --git a/days/97-99-online-game-api/demo_app/web/game_logic/game_service.py b/days/97-99-online-game-api/demo_app/web/game_logic/game_service.py index 8a36926d..9cc2ae6b 100644 --- a/days/97-99-online-game-api/demo_app/web/game_logic/game_service.py +++ b/days/97-99-online-game-api/demo_app/web/game_logic/game_service.py @@ -29,7 +29,7 @@ def get_game_history(game_id: str) -> List[Move]: def is_game_over(game_id: str) -> bool: history = get_game_history(game_id) - return any([h.is_winning_play for h in history]) + return any(h.is_winning_play for h in history) def get_win_count(player: Player) -> int: @@ -163,7 +163,7 @@ def count_round_wins(player_id: int, game_id: str) -> int: for h in history: grouped_moves[h.roll_number].append(h) - for rnd_num, moves in grouped_moves.items(): + for moves in grouped_moves.values(): player_move = [m for m in moves if m.player_id == player_id][0] opponent_move = [m for m in moves if m.player_id != player_id][0] diff --git a/days/97-99-online-game-api/demo_app/web/game_logic/session_factory.py b/days/97-99-online-game-api/demo_app/web/game_logic/session_factory.py index 95d2e116..1811968b 100644 --- a/days/97-99-online-game-api/demo_app/web/game_logic/session_factory.py +++ b/days/97-99-online-game-api/demo_app/web/game_logic/session_factory.py @@ -14,7 +14,7 @@ def global_init(): global __factory full_file = db_folder.get_db_path('rock_paper_scissors.sqlite') - conn_str = 'sqlite:///' + full_file + conn_str = f'sqlite:///{full_file}' engine = sqlalchemy.create_engine(conn_str, echo=False) ModelBase.metadata.create_all(engine)