Skip to content

Sourcery refactored master branch #1

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
8 changes: 5 additions & 3 deletions days/01-03-datetimes/code/datetime_date.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
# <class 'datetime.datetime'>
Expand Down Expand Up @@ -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!")
4 changes: 1 addition & 3 deletions days/01-03-datetimes/code/datetime_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
#36000

t.hours
#Traceback (most recent call last):
#File "<pyshell#119>", line 1, in <module> t.hours
Comment on lines -15 to -16
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 15-30 refactored with the following changes:

This removes the following comments ( why? ):

#File "<pyshell#119>", line 1, in <module> t.hours
#Traceback (most recent call last):

#AttributeError: 'datetime.timedelta' object has no attribute 'hours'

t.seconds / 60 / 60
Expand All @@ -27,7 +25,7 @@

eta = timedelta(hours=6)

today = datetime.today()
today = datetime.now()

today
#datetime.datetime(2018, 2, 19, 14, 55, 19, 197404
Expand Down
8 changes: 2 additions & 6 deletions days/10-12-pytest/fizzbuzz/fizzbuzz.py
Original file line number Diff line number Diff line change
@@ -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
Comment on lines -2 to +4
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fizzbuzz refactored with the following changes:

3 changes: 1 addition & 2 deletions days/10-12-pytest/guess/guess.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,7 @@ def __call__(self):
print(ve)
continue

win = self._validate_guess(guess)
if win:
if win := self._validate_guess(guess):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Game.__call__ refactored with the following changes:

guess_str = self.num_guesses == 1 and "guess" or "guesses"
print(f'It took you {self.num_guesses} {guess_str}')
self._win = True
Expand Down
6 changes: 3 additions & 3 deletions days/13-15-text-games/data/sample_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Comment on lines -15 to +18
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function read_roll refactored with the following changes:


print()

Expand Down
16 changes: 7 additions & 9 deletions days/13-15-text-games/dnd_game/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Comment on lines -31 to +48
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function game_loop refactored with the following changes:

else:
print("OK, exiting game... bye!")
break
Expand Down
6 changes: 3 additions & 3 deletions days/19-21-itertools/code/traffic_lights.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}')
Comment on lines -14 to +20
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function light_rotation refactored with the following changes:

sleep(rg_timer())

if __name__ == '__main__':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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')]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_movie_by_title refactored with the following changes:



def create_random_errors(results):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



if __name__ == '__main__':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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')]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_movie_by_title refactored with the following changes:



def create_random_errors(results):
Expand Down
9 changes: 3 additions & 6 deletions days/31-33-logging/demo/movie_search_logging_edition/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_movie_by_title refactored with the following changes:


if not keyword or not keyword.strip():
api_log.warn("No keyword supplied")
Expand All @@ -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(
Expand Down
11 changes: 4 additions & 7 deletions days/31-33-logging/demo/movie_search_logging_edition/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Comment on lines -23 to +30
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

print(msg)
app_log.exception(x)

Expand All @@ -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}'}"""
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function init_logging refactored with the following changes:

logger = logbook.Logger('Startup')
logger.notice(msg)

Expand Down
6 changes: 1 addition & 5 deletions days/31-33-logging/demo/starter_movie_search/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_movie_by_title refactored with the following changes:



def create_random_errors(results):
Expand Down
2 changes: 1 addition & 1 deletion days/31-33-logging/demo/starter_movie_search/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



if __name__ == '__main__':
Expand Down
6 changes: 3 additions & 3 deletions days/37-39-csv-data-analysis/weather_csv_demo/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Comment on lines -12 to +23
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



if __name__ == '__main__':
Expand Down
6 changes: 1 addition & 5 deletions days/37-39-csv-data-analysis/weather_csv_demo/research.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_row refactored with the following changes:



def hot_days() -> List[Record]:
Expand Down
11 changes: 3 additions & 8 deletions days/40-42-json-data/code/json_dicts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
]
Comment on lines -25 to +27
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 25-32 refactored with the following changes:

This removes the following comments ( why? ):

#Prints just the data associated with the 'name' key.

#Collects all of the applicable mounts and stores them as a list of dicts

#You can then work with the data as normal:
Expand Down
6 changes: 1 addition & 5 deletions days/43-45-search-api/demo/movie_search/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_movie_by_title refactored with the following changes:

4 changes: 1 addition & 3 deletions days/46-48-beautifulsoup4/scraper_demo/scraper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Comment on lines -13 to +17
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function scrape refactored with the following changes:

for headers in header_list:
print(headers)

Expand Down
6 changes: 3 additions & 3 deletions days/49-51-measuring-perf/demo/final_csv_code/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Comment on lines -24 to +34
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



if __name__ == '__main__':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Comment on lines -16 to +26
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



if __name__ == '__main__':
Expand Down
4 changes: 1 addition & 3 deletions days/49-51-measuring-perf/demo/final_csv_code/research.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines -35 to -42
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_row refactored with the following changes:


# 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)
Expand Down
Loading