Become a Better Coder: 10 Tips

Asad iqbal
5 min readJun 9, 2024

--

Follow these laws or get fired.

There are hundreds or probably thousands of Python best practices out there and depending on who you ask, you would get some slight variation on a given practice.

The internet has given everyone the right to voice an opinion. Including even me. But in this article, we will be dealing with 20 Python best practices that are set in stone.

Pandas Cheatsheet: https://www.deepnexus.tech/2024/07/python-cheatsheet.html

Git Commands cheatsheet: https://www.deepnexus.tech/2024/07/git-commands-cheat-sheet-master-your.html

Top 50+ SQL Interview Questions: https://www.deepnexus.tech/2024/07/top-50-sql-questions-asked-in-interview.html

Tip 1: Functions Should Specify The Parameter And Return Type

When defining a function, you want to always specify what the arguments’ types are and also what data type the result of the function returns. This would help both you and the devs in your team know what to expect without always having to use print statements to get a visual understanding.

Good:

def greet(name: str) -> None:
"""Greets the user by name."""
print(f"Hello, {name}!")

def calculate_area(length: int, width: int) -> int:
"""Calculates the area of a rectangle."""
area = length * width
return area

Bad:

def do_something():
print("This function does something, but it's unclear what!")

# Calling the function
do_something("This is a mistake!") # This might cause errors

Tip 2: Functions Should Be At The Same Level Of Abstraction

When we talk about functions being at the same level of abstraction, we’re referring to the idea that a function should perform a single, well-defined task. That task should be at a consistent level of abstraction throughout the function. In other words, the function should focus on a specific level of detail or complexity, and all the functions’ operations should operate at that same level.

Good:

def calculate_average(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
return average

Bad:

def get_numbers():
numbers = [2,3,4,1,4,1,416,6]
return numbers

def calculate_average():
numbers = get_numbers()
numbers_plus_30 = [num + 30 for num in numbers]

total = sum(numbers_plus_30)
count = len(numbers)
average = total / count
return average

calculate_average()

Tip 3: Functions Should Be Small

A function is meant to be reusable. And the bigger the function gets, the less likely it is to be reusable. This also correlates to why a function should do only one thing. If it does only one thing, there’s a high chance it’s going to be small.

Tip 4: Open Closed Principles

The open-closed principle (OCP) states that a class, method, or function must be open for extension but not modification. This means that any class, method, or function defined can be easily reused or extended for multiple instances without changing its code.

Let’s take for instance, we have a class called address.

class Address:
def __init__(self, country):
self.country = country

def get_capital(self):
if self.country == 'canada':
return "ottawa"
if self.country == 'america':
return "Washington D.C"
if self.country == 'united Kingdom':
return "London"

address = Address('united Kingdom')
print(address.get_capital())

This fails to adhere to OCP because whenever there’s a new country, we would need to write a new if statement to complement that. This might seem simple now but imagine we have 100 or more countries to take into account. How would that look?

This is where OCP comes into play.

capitals = {
'canada': "Ottawa",
'america': "Washington D.C",
'united Kingdom': "London"
}

class Address:
def __init__(self, country):
self.country = country

def get_capital(self):
return capitals.get(self.country, "Capital not found")

address = Address('united Kingdom')
print(address.get_capital())

Tip 5: Avoid Comments At All Cost

Comments have a way of being falsely true. They deviate the mind of the reader from what the code is actually doing to what someone else says it’s doing.

This can become very problematic as time passes and the code receives updates or changes. At some point, the comment becomes a lie and everyone now has to observe the truth through the lens of the lie.

Comments must be avoided at all costs. A comment forces the reader to inherit your thinking which at best is in the past. When a function or class changes, most likely, its comments do not change along with it. Most likely, they block the reader from thinking forward.

A comment signifies that the writer was mentally incapable of providing a well-descriptive class, function, or variable name. It exposes the lackluster attitude of the programmer and forces the team to inherit such an attitude.

Tip 6: Avoid Magic Numbers

A Magic Number is a hard-coded value that may change at a later stage, but that can be therefore hard to update.

For example, let’s say you have a Page that displays the last 50 Orders in a “Your Orders” Overview Page. 50 is the Magic Number here because it’s not set through standard or convention, it’s a number that you made up for reasons outlined in the spec.

Now, what you do is you have the 50 in different places — your SQL script (SELECT TOP 50 * FROM orders), your Website (Your Last 50 Orders), your order login (for (i = 0; i < 50; i++)) and possibly many other places.

Good:

NUM_OF_ORDERS = 50
SELECT TOP NUM_OF_ORDERS * FROM orders

Bad:

SELECT TOP 50 * FROM orders

Tip 7: Avoid Deep Nesting

Limit the levels of nesting within loops, conditionals, or functions to improve readability.

Good:

if x and y:
do_something()

Bad:

if x:
if y:
do_something()

Tip 8: Avoid Hardcoding Paths

Refrain from hardcoding file paths or URLs; use configuration files or environment variables instead.

Good:

import os
file_path = os.getenv("FILE_PATH")

Bad:

file_path = "/path/to/file.txt"

Tip 9: Classes should be small

Yep! Classes should be as small as possible. Just like functions.

The only difference is that in functions, size is determined by the number of lines in that function while in classes, it is determined by the number of responsibilities in that class.

Usually, a class name represents the kind of responsibilities it might possess but when the name is ambiguous or too general, most likely we are giving it too much responsibility.

This takes us back to SRP (single responsibility principle) which states that a class should only have one reason — one responsibility — to change.

Tip 10: Avoid Complex Ternary Expressions

Refrain from using overly complex ternary expressions; favor readability over brevity to make code more understandable.

Good:

if number % 2 == 0:
result = "even"
elif number % 3 == 0:
result = "odd"
else:
result = "neither"

Bad:

result = "even" if number % 2 == 0 else "odd" if number % 3 == 0 else "neither"

Thanks for reading✨; if you liked my content and want to support me, the best way to supporting me on Patreon

--

--