Make Each Line Count, Keeping Things Simple in Python
source link: https://pybit.es/articles/make-each-line-count-keeping-things-simple-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Make Each Line Count, Keeping Things Simple in Python
By Bob Belderbos on 24 August 2023
A challenge in software development is to keep things simple
For your code to not grow overly complex over time
Simple is better than complex.
Zen of Python
Complex is better than complicated.
Simplicity in your code means fewer possibilities for bugs to hide and easier debugging when they do arise
It also makes your code more understandable and maintainable, which is crucial in a team setting or when returning to your code after a period of time.
A good example is (not) using Python built-ins.
Photo by Pablo Arroyo on Unsplash
Given you go from supporting checking if one number is divisible:
def is_divisible(num, divisor):
return num % divisor == 0
To multiple numbers:
def is_divisible_by_all(num, divisors):
for divisor in divisors:
if num % divisor != 0:
return False
return True
This is valid and works, but you might write this in a simpler matter using the any() buit-in:
def is_divisible_by_all(num, divisors):
return all(num % divisor == 0 for divisor in divisors)
Very clean / easy to read
Another example is doing dictionary lookups, checking if the key is in the dictionary:
Complex (unnecessary):
def get_value(dictionary, key):
if key in dictionary:
return dictionary[key]
else:
return "Key not found"
Better: leverage the fact that Python dicts have a get()
method:
dictionary.get(key, "Key not found")
Remember, simple code isn’t just about having fewer lines, it’s about being concise, making each line count
This usually means heavily using the Python built-ins and Standard Library
The more you can do with less, the easier your code is to understand and maintain
Code more idiomatically with our collection of 400 Python exercises on our platform
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK