Python Clean
Code Practice
Zack-MF
2024-09-05
Clean Code Rules and Tips
Naming Convertions
Function-oriented programming
identation, breaking, spacing and more
Contents Case Analysis
Single Principle
Code Extraction
Code Refactor
Summary
Easy to read and descrptive
Consistency
Naming Convertions
Naming
Detailed Naming
“There’re two most difficult things in
computer science: one is cache
invalidataion and the other is naming
in programs.”
General Naming Rules
Naming Conventions (PEP 8)
object usage examples remark
Variable Lowercase letters or words seperated by current_date lower snake case
underscores. spark_env
Constan Uppercase letters or words seperated by CONFIG_FILE upper snake case
t underscores. ROOT_PATH
Class Start each word with a capital letter. Do not RetryMiddleware Upper camel case
seperate words by underscores. DataHandler
Functio Lowercase words seperated by underscore get_token lower snake case
n parse_json
Method Lowercase words seperated by underscore request lower snake case
save_file
Package Lowercase words seperated by underscore utils lower snake case
libs
Module Lowercase words seperated by underscore spider lower snake case
db_handler
Non-pythonic: lower camel case: getURL, personDF
Detailed Guidance
Naming Integer Naming String
Variables
age_in_years Variables
name
age_in_months title
number_of_failure year_as_str
num_of_retry year_str
failure_count price_str
Naming Boolean Naming Collection
Variables
is_disabled
if is_disabled is False:
(List/Set) Variables
has_errors
did_updated xxxx customers customer_list
should_updated if not is_disabled: processed_customers
will_updated xxxx card_data
card_categories
Naming Dictionary Naming Pair Variables
Variables height_and_width = (100, 200)
height_width_and_depth = (100,
customer_name_to_order_dict 200, 300)
customer_dict
Naming Object Naming Function
Variables
agent_df Variables
def save()
def show()
def get_token()
def get_parsed_data()
General Naming Rules
Use short, common names
Pick one term and use it consistently
Avoid obsecure abbreviations
Avoid too short or meaningless or confusing names
Use descrptive and understandable names
Code is more often read than written.
Identation, Break and Space
Practical tips with Annotation, Docstring and f-string
Real Cases
Error Handling, Decorator and Chain
Calls
Code Block and Code Extraction
Summa
ry
Naming, Identation, Break and
Space
Summary Annotation, Docstring, Function
Error Handling, Decorator and Chain
Calls
Code Block and Code Extraction
T hink about it...
1. What is duck typing in Python specifically?
2. What are the distinctions between function-oriented
programming and object-oriented programming?
3. How is a Python file executed? What are the steps involved in
the process?