Refactoring
- refactoring – breaking up code into a series of functions that have specific jobs
- can refactor remember_me.py by moving the bulk of its logic into one or more functions
- the focus of remember_me.py is on greeting the user so we’ll move our code into a function called greet_user()
remember_me.py
from pathlib import Path
import json
.
def greet_user():
….”””Greet the user by name.”””
….path = Path(‘username.json’)
….if path.exists():
……..contents = path.read_text()
……..username – json.loads(contents)
……..print(f”Welcome back, {username}!”)
….else:
……..username = input(“What is your name? “)
……..contents = json.dumps(username)
……..path.write_text(contents)
……..print(f”We’ll remember you when you come back, {username}!”)
.
greet_user()
- since we’re using a function, we rewrite the comments as a docstring that reflects how the program currently works
- cleaner file, but the function greet_user() greets the user and retrieves a stored username if one exists and prompts for a username if it doesn’t
- let’s refactor greet_user() so it’s not doing so many different tasks
- we’ll move the code for retrieving a stored username to a separate function
from pathlib import Path
import json
.
def get_stored_username(path):
….”””Get stored username if available.”””
….if path.exists():
……..contents = path.read_text()
……..username = json.loads(contents)
……..return username
….else:
……..return None
.
def greet_user():
….”””Greet the user by name.”””
….path = Path(‘username.json’)
….username = get_stored_username(path)
….if username:
……..print(f”Welcome back, {username}!”)
….else:
……..username = input(“What is your name? “)
……..contents = json.dumps(username)
……..path.write_text(contents)
……..print(f”We’ll remember you when you come back, {username}!”)
.
greet_user()
- new function get_stored_username() has a clear purpose
- a function should either return the value you’re expecting or it should return None
- we’ll factor one more block of code out of greet_user()
- if a username doesn’t exist, we’ll move the code that prompts for a new username to a dedicated function
from pathlib import Path
import json
.
def get_stored_username(path):
….”””Get stored username if available.”””
….–snip–
.
def get_new_username(path):
….”””Prompt for a new username.”””
….username = input(“What is your name? “)
….contents – json.dumps(username)
….path.write_text(contents)
….return username
.
def greet_user():
….”””Greet the user by name.”””
….path = Path(‘username.json’)
….username = get_stored_username(path)
….if username:
……..print(f”Welcome back, {username}!”)
….else:
……..username = get_new_username(path)
……..print(f”We’ll remember you when you come back, {username}!”)
.
greet_user()
- each function of this final version of remember_me.py has a single purpose
- this compartmentalization of work is an essential part of writing clear code that will be easy to maintain and extend
Summary
- learned how to work with files
- learned to read the entire contents of files and work through contents one line at a time
- learned to write as much text as you want to a file
- read about exceptions and how to handle the exceptions likely to see
- learned how to store Python data structures so you can save info users provide, preventing them from starting over each time they run a program
End of study session.