elif statements are not automatically a problem. If you're repeatedly looking up values or repeating the same operation, there may be a cleaner approach. If you're making genuinely different decisions, if / elif may be the clearest option.Use a dictionary
Best when: One input value maps to one output value (for example, a website name maps to a URL).
def get_website_url(website_name: str) -> str:
"""Return the URL associated with a website name."""
websites: dict[str, str] = {
'Google': 'https://www.google.com',
'GitHub': 'https://www.github.com',
'YouTube': 'https://www.youtube.com',
'Reddit': 'https://www.reddit.com'
}
return websites.get(website_name, 'Unknown Website')
print(get_website_url('GitHub')) # https://www.github.com
print(get_website_url('Bing')) # Unknown Website
How does .get() work?
websites.get(website_name, 'Unknown Website') looks for the key stored in website_name. If it exists, Python returns its value. Otherwise, Python returns the fallback string. This avoids writing one elif for each website.
Remember: This is ideal for fixed key → value mappings. A dictionary is not a direct replacement for conditions such as temperature < 10.
Use match / case
Best when: You're checking one value against multiple possible choices, and you want separate, readable blocks for each choice.
def get_website_url(website_name: str) -> str:
"""Return the URL associated with a website name."""
match website_name:
case 'Google':
return 'https://www.google.com'
case 'GitHub':
return 'https://www.github.com'
case 'YouTube':
return 'https://www.youtube.com'
case 'Reddit':
return 'https://www.reddit.com'
case _:
return 'Unknown Website'
What do match, case and _ mean?
match website_name chooses the value to inspect. Each case checks for a match. case _: is the fallback, similar to else:. The return statements also cover all paths, keeping type checkers such as Pyrefly happy.
Remember: match / case arrived in Python 3.10. It's often more readable, but it doesn't necessarily reduce the amount of code.
Use a dictionary of functions
Best when: Each option runs a different function, such as backing up files, downloading files, or scanning folders.
# Assume these functions are already defined:
# backup_files(), download_files(), scan_folders(), cleanup_files()
from typing import Callable
def perform_action(action: str) -> None:
"""Run a chosen action, or print an error if it is unknown."""
actions: dict[str, Callable[[], None]] = {
'backup': backup_files,
'download': download_files,
'scan': scan_folders,
'cleanup': cleanup_files
}
selected_function = actions.get(action)
if selected_function is not None:
selected_function()
else:
print(f'Unknown action: {action}')
Why are there no parentheses in the dictionary?
'backup': backup_files stores a reference to the function. Writing backup_files() would run it immediately while constructing the dictionary. Later, selected_function() executes only the selected function.
Callable[[], None] means a callable that takes no arguments and returns None. This type hint assumes your four action functions have that signature.
Remember: This is called function dispatch. For just a few actions, ordinary if / elif or match / case may still be easier to read.
Use setattr()
Best when: Every branch performs the same operation on a different class attribute—exactly like your original reset_class_attr() function.
def reset_class_attr(wanted_class_attr: str) -> str | None:
"""Reset an existing Share_Text class attribute to ''.
Returns:
str | None: '' when reset, or None if not found.
"""
if hasattr(Share_Text, wanted_class_attr):
setattr(Share_Text, wanted_class_attr, '')
return ''
else:
print(f'Attribute not found: {wanted_class_attr}')
return None
reset_class_attr('cls_GitHub_URL')
What do hasattr(), setattr() and getattr() do?
hasattr(Share_Text, 'cls_GitHub_URL') checks whether the attribute exists.
setattr(Share_Text, 'cls_GitHub_URL', '') does the equivalent of Share_Text.cls_GitHub_URL = ''.
getattr(Share_Text, 'cls_GitHub_URL') retrieves that attribute's value. You don't need getattr() in this function because you already know the new value is ''.
Important: How do I restrict which attributes can be reset?
hasattr() permits any existing attribute, including attributes that weren't in your original elif list. To preserve that restriction, create a set of allowed names:
allowed_attrs: set[str] = {
'cls_GitHub_URL',
'cls_docker_app_name',
'cls_OG_WinPath'
}
if wanted_class_attr in allowed_attrs:
setattr(Share_Text, wanted_class_attr, '')Keep an explicit fallback return in the complete function, just as you learned from your Pyrefly example.
Which approach should I choose?
| What is your code doing? | Try this | Why? |
|---|---|---|
| One name → one value | Dictionary | Compact lookup; simple to expand |
| One value → several distinct branches | match / case | Readable structure with a default case |
| One action name → one function call | Dictionary of functions | Dispatches to the selected function |
| Same assignment → different attribute names | setattr() | Removes repeated assignment code |
| Ranges or complex boolean conditions | if / elif / else | Often still the clearest choice |
Example: When elif is perfectly fine
def get_temperature_status(temperature: float) -> str:
"""Classify a temperature into a simple description."""
if temperature < 10:
return 'Cold'
elif temperature < 20:
return 'Cool'
elif temperature < 30:
return 'Warm'
else:
return 'Hot'
Ask yourself: “Am I repeating an operation with different values, or making genuinely different decisions?”
Learning order: match / case → dictionary lookups → setattr()/getattr() → dictionary of functions. You don't need to refactor everything at once.
↑ Back to top