Naming Functions Clearly
A well-named function tells you what it does without reading its code. A poorly-named function forces you to dig into implementation details just to understand what's happening. Naming is a skill that improves with practice, and following conventions helps.
Use Verbs
Functions do things, so their names should start with verbs:
# Good: action words
def calculate_tax(amount, rate):
return amount * rate
def get_user_by_id(user_id):
# fetch user from database
pass
def is_valid_email(email):
return "@" in email
def send_notification(user, message):
# send the notification
pass
Common verb prefixes and what they suggest:
get_— retrieves somethingset_— assigns a valuecalculate_— computes a resultis_orhas_— returns True/Falsecreate_— makes something newupdate_— modifies existing datadelete_orremove_— eliminates somethingvalidate_— checks if something is correct
Follow Python Conventions
Python uses snake_case for function names — lowercase words separated by underscores:
# Python style
def calculate_shipping_cost(weight, distance):
pass
# Not Python style (but common in other languages)
def calculateShippingCost(weight, distance): # camelCase
pass
Consistency with the language's conventions makes your code feel natural to other Python developers.
Be Specific, Not Vague
Avoid generic names that don't convey meaning:
# Vague - what does "process" mean?
def process(data):
pass
# Specific - clear what it does
def format_phone_number(raw_number):
pass
# Vague - what kind of calculation?
def calc(x, y):
pass
# Specific - obvious purpose
def calculate_distance(point_a, point_b):
pass
Balance Brevity and Clarity
Names should be descriptive but not excessively long:
# Too short - cryptic
def ct(a, r):
return a * r
# Too long - hard to read
def calculate_the_total_tax_amount_for_purchase(amount, rate):
return amount * rate
# Just right
def calculate_tax(amount, rate):
return amount * rate
Make Code Read Like English
Well-named functions make code almost self-documenting:
if is_valid_email(user_email):
send_welcome_message(user_email)
add_to_mailing_list(user_email)
else:
show_error("Invalid email address")
You can understand this code without seeing any function implementations. That's the power of good naming.