0% found this document useful (0 votes)
5 views1 page

Refactoring Python Code for User Greeting

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Refactoring Python Code for User Greeting

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Otherwise:

Welcome back, Eric!

This is the output you see if the program was already run at least once.
Even though the data in this section is just a single string, the program
would work just as well with any data that can be converted to a JSON-
formatted string.

Refactoring
Often, you’ll come to a point where your code will work, but you’ll recognize
that you could improve the code by breaking it up into a series of functions
that have specific jobs. This process is called refactoring. Refactoring makes
your code cleaner, easier to understand, and easier to extend.
We 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
let’s move all of our existing code into a function called greet_user():

remember from pathlib import Path


_me.py import json

def greet_user():
1 """Greet the user by name."""
path = Path('[Link]')
if [Link]():
contents = path.read_text()
username = [Link](contents)
print(f"Welcome back, {username}!")
else:
username = input("What is your name? ")
contents = [Link](username)
path.write_text(contents)
print(f"We'll remember you when you come back, {username}!")

greet_user()

Because we’re using a function now, we rewrite the comments as a doc-


string that reflects how the program currently works 1. This file is a little
cleaner, but the function greet_user() is doing more than just greeting the
user—it’s also retrieving a stored username if one exists and prompting for
a new username if one doesn’t.
Let’s refactor greet_user() so it’s not doing so many different tasks. We’ll
start by moving the code for retrieving a stored username to a separate
function:

from pathlib import Path


import json

def get_stored_username(path):
1 """Get stored username if available."""

204 Chapter 10

You might also like