Skip to content
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
6 changes: 1 addition & 5 deletions days/009-012-modern-apis-starred/demo/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,9 @@ def _load_cars_data():


cars = _load_cars_data()
VALID_MANUFACTURERS = set([car["manufacturer"]
for car in cars.values()])
VALID_MANUFACTURERS = {car["manufacturer"] for car in cars.values()}
CAR_NOT_FOUND = 'Car not found'

# definition

Comment on lines -17 to -22
Copy link
Author

Choose a reason for hiding this comment

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

Lines 17-22 refactored with the following changes:

This removes the following comments ( why? ):

# definition


class Car(types.Type):
id = validators.Integer(allow_null=True) # assign in POST
manufacturer = validators.String(enum=list(VALID_MANUFACTURERS))
Expand Down
2 changes: 1 addition & 1 deletion days/009-012-modern-apis-starred/demo/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def test_create_car():
def test_create_car_after_delete():
"""Test to fail create_car's len(cars)+1 (fix max(cars.keys())+1)"""
car_count = len(cars)
response = client.delete(f'/99/')
response = client.delete('/99/')
Copy link
Author

Choose a reason for hiding this comment

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

Function test_create_car_after_delete refactored with the following changes:

assert response.status_code == 204
assert len(cars) == car_count - 1
data = {'manufacturer': 'Honda',
Expand Down
11 changes: 3 additions & 8 deletions days/017-020-flask-call-apis/code/program/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from program import app

time_now = str(datetime.today())
time_now = str(datetime.now())
Copy link
Author

Choose a reason for hiding this comment

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

Lines 8-8 refactored with the following changes:



@app.route('/')
Expand Down Expand Up @@ -43,11 +43,6 @@ def get_chuck_joke():


def get_poke_colours(colour):
r = requests.get('https://pokeapi.co/api/v2/pokemon-color/' + colour.lower())
r = requests.get(f'https://pokeapi.co/api/v2/pokemon-color/{colour.lower()}')
pokedata = r.json()
pokemon = []

for i in pokedata['pokemon_species']:
pokemon.append(i['name'])

return pokemon
return [i['name'] for i in pokedata['pokemon_species']]
Comment on lines -46 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 get_poke_colours refactored with the following changes:

2 changes: 1 addition & 1 deletion days/021-024-quart-async/async_cityscape_api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def configure_app():
services.sun_service.use_cached_data = data.get('use_cached_data', False)
services.location_service.use_cached_data = True

print("Using cached data? {}".format(data.get('use_cached_data', False)))
print(f"Using cached data? {data.get('use_cached_data', False)}")
Copy link
Author

Choose a reason for hiding this comment

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

Function configure_app refactored with the following changes:



def run_web_app():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ async def get_lat_long(zip_code: str, country: str) -> Tuple[float, float]:
resp.raise_for_status()
data = await resp.json()

city_data = data.get(f'{zip_code}, {country}', dict())
city_data = data.get(f'{zip_code}, {country}', {})
Copy link
Author

Choose a reason for hiding this comment

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

Function get_lat_long refactored with the following changes:

return city_data.get('latitude', 0.00), city_data.get('longitude', 0.00)
2 changes: 1 addition & 1 deletion days/021-024-quart-async/cityscape_api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def configure_app():
# Sadly, datasciencetoolkit.org seems to have gone out of existence.
services.location_service.use_cached_data = True

print("Using cached data? {}".format(data.get('use_cached_data', False)))
print(f"Using cached data? {data.get('use_cached_data', False)}")
Copy link
Author

Choose a reason for hiding this comment

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

Function configure_app refactored with the following changes:



def run_web_app():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ def get_lat_long(zip_code: str, country: str) -> Tuple[float, float]:

data = resp.json()

city_data = data.get(f'{zip_code}, {country}', dict())
city_data = data.get(f'{zip_code}, {country}', {})
Copy link
Author

Choose a reason for hiding this comment

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

Function get_lat_long refactored with the following changes:

return city_data.get('latitude', 0.00), city_data.get('longitude', 0.00)
4 changes: 2 additions & 2 deletions days/021-024-quart-async/python_async/async_program.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

def main():
t0 = datetime.datetime.now()
print(colorama.Fore.WHITE + "App started.", flush=True)
print(f"{colorama.Fore.WHITE}App started.", flush=True)
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:


# Changed from asyncio.get_event_loop() => asyncio.new_event_loop()
# There has been a deprecation:
Expand All @@ -31,7 +31,7 @@ async def generate_data(num: int, data: asyncio.Queue):
item = idx*idx
await data.put((item, datetime.datetime.now()))

print(colorama.Fore.YELLOW + f" -- generated item {idx}", flush=True)
print(f"{colorama.Fore.YELLOW} -- generated item {idx}", flush=True)
Copy link
Author

Choose a reason for hiding this comment

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

Function generate_data refactored with the following changes:

await asyncio.sleep(random.random() + .5)


Expand Down
4 changes: 2 additions & 2 deletions days/021-024-quart-async/python_async/sync_program.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

def main():
t0 = datetime.datetime.now()
print(colorama.Fore.WHITE + "App started.", flush=True)
print(f"{colorama.Fore.WHITE}App started.", flush=True)
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:

data = []
generate_data(20, data)
process_data(20, data)
Expand All @@ -20,7 +20,7 @@ def generate_data(num: int, data: list):
item = idx*idx
data.append((item, datetime.datetime.now()))

print(colorama.Fore.YELLOW + f" -- generated item {idx}", flush=True)
print(f"{colorama.Fore.YELLOW} -- generated item {idx}", flush=True)
Copy link
Author

Choose a reason for hiding this comment

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

Function generate_data refactored with the following changes:

time.sleep(random.random() + .5)


Expand Down
11 changes: 4 additions & 7 deletions days/021-024-quart-async/your_turn/day_2/web_crawl/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


def get_html(episode_number: int) -> str:
print(Fore.YELLOW + f"Getting HTML for episode {episode_number}", flush=True)
print(f"{Fore.YELLOW}Getting HTML for episode {episode_number}", flush=True)
Copy link
Author

Choose a reason for hiding this comment

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

Function get_html refactored with the following changes:


url = f'https://talkpython.fm/{episode_number}'
resp = requests.get(url)
Expand All @@ -14,13 +14,10 @@ def get_html(episode_number: int) -> str:


def get_title(html: str, episode_number: int) -> str:
print(Fore.CYAN + f"Getting TITLE for episode {episode_number}", flush=True)
print(f"{Fore.CYAN}Getting TITLE for episode {episode_number}", flush=True)
soup = bs4.BeautifulSoup(html, 'html.parser')
header = soup.select_one('h1')
if not header:
return "MISSING"

return header.text.strip()
return "MISSING" if not header else header.text.strip()
Comment on lines -17 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 get_title refactored with the following changes:



def main():
Expand All @@ -33,7 +30,7 @@ def get_title_range():
for n in range(150, 170):
html = get_html(n)
title = get_title(html, n)
print(Fore.WHITE + f"Title found: {title}", flush=True)
print(f"{Fore.WHITE}Title found: {title}", flush=True)
Comment on lines -36 to +33
Copy link
Author

Choose a reason for hiding this comment

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

Function get_title_range refactored with the following changes:



if __name__ == '__main__':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def configure_app():
# Sadly, datasciencetoolkit.org seems to have gone out of existence.
services.location_service.use_cached_data = True

print("Using cached data? {}".format(data.get('use_cached_data', False)))
print(f"Using cached data? {data.get('use_cached_data', False)}")
Copy link
Author

Choose a reason for hiding this comment

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

Function configure_app refactored with the following changes:



def run_web_app():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@ def get_lat_long(zip_code: str, country: str) -> Tuple[float, float]:

data = resp.json()

city_data = data.get(f'{zip_code}, {country}', dict())
city_data = data.get(f'{zip_code}, {country}', {})
Copy link
Author

Choose a reason for hiding this comment

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

Function get_lat_long refactored with the following changes:

return city_data.get('latitude', 0.00), city_data.get('longitude', 0.00)
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def global_init(db_name: str):
if __factory:
return

conn_str = 'sqlite:///' + db_folder.get_full_path(db_name)
conn_str = f'sqlite:///{db_folder.get_full_path(db_name)}'
Copy link
Author

Choose a reason for hiding this comment

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

Function global_init refactored with the following changes:

__engine = sqlalchemy.create_engine(conn_str, echo=False)
__factory = sqlalchemy.orm.sessionmaker(bind=__engine)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def case(self, key, func: Callable[[], Any], fallthrough=False):
if not fallthrough:
self._falling_through = False

if isinstance(key, list) or isinstance(key, range):
if isinstance(key, (list, range)):
Copy link
Author

Choose a reason for hiding this comment

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

Function switch.case refactored with the following changes:

found = False
for i in key:
if self.case(i, func, fallthrough=None):
Expand All @@ -63,7 +63,7 @@ def case(self, key, func: Callable[[], Any], fallthrough=False):
return found

if key in self.cases:
raise ValueError("Duplicate case: {}".format(key))
raise ValueError(f"Duplicate case: {key}")
if not func:
raise ValueError("Action for case cannot be None.")
if not callable(func):
Expand All @@ -85,8 +85,9 @@ def __exit__(self, exc_type, exc_val, exc_tb):
raise exc_val

if not self._func_stack:
raise Exception("Value does not match any case and there "
"is no default case: value {}".format(self.value))
raise Exception(
f"Value does not match any case and there is no default case: value {self.value}"
)
Comment on lines -88 to +90
Copy link
Author

Choose a reason for hiding this comment

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

Function switch.__exit__ refactored with the following changes:


for func in self._func_stack:
# noinspection PyCallingNonCallable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def rent_a_scooter():
scooters = find_available_scooters(True)
chose_it = try_int(input('Which one do you want? ')) - 1

if not (0 <= chose_it or chose_it < len(scooters)):
if chose_it < 0 and chose_it >= len(scooters):
Copy link
Author

Choose a reason for hiding this comment

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

Function rent_a_scooter refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)
  • Ensure constant in comparison is on the right (flip-comparison)

print("Error: Pick another number.")
return

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def rented_scooters() -> List[Scooter]:
session = session_factory.create_session()

# noinspection PyComparisonWithNone
scooters = session.query(Scooter).filter(Scooter.location_id == None).all()
scooters = session.query(Scooter).filter(Scooter.location_id is None).all()
Copy link
Author

Choose a reason for hiding this comment

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

Function rented_scooters refactored with the following changes:


return list(scooters)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def case(self, key, func: Callable[[], Any], fallthrough=False):
if not fallthrough:
self._falling_through = False

if isinstance(key, list) or isinstance(key, range):
if isinstance(key, (list, range)):
Copy link
Author

Choose a reason for hiding this comment

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

Function switch.case refactored with the following changes:

found = False
for i in key:
if self.case(i, func, fallthrough=None):
Expand All @@ -63,7 +63,7 @@ def case(self, key, func: Callable[[], Any], fallthrough=False):
return found

if key in self.cases:
raise ValueError("Duplicate case: {}".format(key))
raise ValueError(f"Duplicate case: {key}")
if not func:
raise ValueError("Action for case cannot be None.")
if not callable(func):
Expand All @@ -85,8 +85,9 @@ def __exit__(self, exc_type, exc_val, exc_tb):
raise exc_val

if not self._func_stack:
raise Exception("Value does not match any case and there "
"is no default case: value {}".format(self.value))
raise Exception(
f"Value does not match any case and there is no default case: value {self.value}"
)
Comment on lines -88 to +90
Copy link
Author

Choose a reason for hiding this comment

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

Function switch.__exit__ refactored with the following changes:


for func in self._func_stack:
# noinspection PyCallingNonCallable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def rent_a_scooter():
scooters = find_available_scooters(True)
chose_it = try_int(input('Which one do you want? ')) - 1

if not (0 <= chose_it or chose_it < len(scooters)):
if chose_it < 0 and chose_it >= len(scooters):
Copy link
Author

Choose a reason for hiding this comment

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

Function rent_a_scooter refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)
  • Ensure constant in comparison is on the right (flip-comparison)

print("Error: Pick another number.")
return

Expand All @@ -51,10 +51,9 @@ def find_available_scooters(suppress_header=False):
if not suppress_header:
print("********* Available scooters: ********* ")

parked_scooters = []
# todo show parked scooters
print()
return parked_scooters
return []
Comment on lines -54 to +56
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_available_scooters refactored with the following changes:



def locate_our_scooters():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ def global_init(db_file: str):

DbSession.db_folder = os.path.dirname(db_file)

conn_str = 'sqlite:///' + db_file
print("Connecting to DB at: {}".format(conn_str))
conn_str = f'sqlite:///{db_file}'
print(f"Connecting to DB at: {conn_str}")
Comment on lines -28 to +29
Copy link
Author

Choose a reason for hiding this comment

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

Function DbSession.global_init refactored with the following changes:


engine = sqlalchemy.create_engine(conn_str, echo=False)
DbSession.engine = engine
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,4 @@ def details_post(request: Request):

repository.add_payment(amount, bill_id)

return HTTPFound(___location='/bill/{}'.format(bill_id))
return HTTPFound(___location=f'/bill/{bill_id}')
Copy link
Author

Choose a reason for hiding this comment

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

Function details_post refactored with the following changes:

47 changes: 13 additions & 34 deletions days/050-responder/demo/movie_svc/data/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import collections
from typing import List

__movie_data = dict()
__movie_data = {}
Copy link
Author

Choose a reason for hiding this comment

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

Lines 6-6 refactored with the following changes:


Movie = collections.namedtuple(
'Movie',
Expand All @@ -15,7 +15,7 @@ def movie_to_dict(m: Movie):
if not m:
return {}

d = dict(
return dict(
Copy link
Author

Choose a reason for hiding this comment

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

Function movie_to_dict refactored with the following changes:

imdb_code=m.imdb_code,
title=m.title,
director=m.director,
Expand All @@ -24,16 +24,13 @@ def movie_to_dict(m: Movie):
genres=list(m.genres),
rating=m.rating,
year=m.year,
imdb_score=m.imdb_score
imdb_score=m.imdb_score,
)

return d


def find_by_imdb(imdb_code: str) -> Movie:
global __movie_data
movie = __movie_data.get(imdb_code)
return movie
return __movie_data.get(imdb_code)
Comment on lines -35 to +33
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_by_imdb refactored with the following changes:



def search_keyword(keyword: str) -> List[Movie]:
Expand Down Expand Up @@ -62,12 +59,7 @@ def search_title(keyword: str) -> List[Movie]:

keyword = keyword.lower().strip()

hits = []
for m in __movie_data.values():
if m.lower_title.find(keyword) >= 0:
hits.append(m)

return hits
return [m for m in __movie_data.values() if m.lower_title.find(keyword) >= 0]
Comment on lines -65 to +62
Copy link
Author

Choose a reason for hiding this comment

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

Function search_title refactored with the following changes:



def search_director(director: str) -> List[Movie]:
Expand All @@ -78,12 +70,11 @@ def search_director(director: str) -> List[Movie]:

director = director.lower().strip()

hits = []
for m in __movie_data.values():
if m.director.lower().find(director) >= 0:
hits.append(m)

return hits
return [
m
for m in __movie_data.values()
if m.director.lower().find(director) >= 0
]
Comment on lines -81 to +77
Copy link
Author

Choose a reason for hiding this comment

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

Function search_director refactored with the following changes:



def global_init():
Expand Down Expand Up @@ -113,10 +104,7 @@ def global_init():


def __make_numerical(text):
if not text or not text.strip():
return 0

return int(text)
return 0 if not text or not text.strip() else int(text)
Comment on lines -116 to +107
Copy link
Author

Choose a reason for hiding this comment

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

Function __make_numerical refactored with the following changes:



def __build_imdb_code(link):
Expand All @@ -126,21 +114,12 @@ def __build_imdb_code(link):
# tt0449088

parts = link.split('/')
if len(parts) < 5:
return None

return parts[4]
return None if len(parts) < 5 else parts[4]
Comment on lines -129 to +117
Copy link
Author

Choose a reason for hiding this comment

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

Function __build_imdb_code refactored with the following changes:



def __split_separated_text(text):
if not text:
return text

text = text.strip()
parts = [
p.strip()
for p in text.split('|')
if p and p.strip()
]

return parts
return [p.strip() for p in text.split('|') if p and p.strip()]
Comment on lines -140 to +125
Copy link
Author

Choose a reason for hiding this comment

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

Function __split_separated_text refactored with the following changes:

Loading