DEV Community

Tabish Javed
Tabish Javed

Posted on

Pythonic Python: Best Code Practices

Who doesn't love Python? It's easy to write code in Python and it does a lot of the work for you. However, there are several practices that we should follow to improve code readability and performance.

1. Pythonic conditions

Python provides a lot of ease in writing conditions. We are often used to other languages that require long conditions, so we end up doing it here.
Consider the following lines of code.

# Non-Pythonic
if condition:
    x = 10
else:
    x = 5

# Pythonic
x = 10 if condition else 5

Enter fullscreen mode Exit fullscreen mode

This improves the appearance of your code and makes full use of Python's capabilities.

2. Use zip()

The zip function in Python combines multiple iterables (e.g., lists, tuples, or strings) element-wise into a new iterable of tuples. Each tuple contains the corresponding elements from all the input iterables.
It stops when the shortest iterable is exhausted. Here's an example!

items = ['milk', 'banana', 'yoghurt']
quantities = [1, 12, 2]
prices = [1.5, 0.8, 1.8]

combined = zip(items, quantities, prices)
print(list(combined))
Enter fullscreen mode Exit fullscreen mode
[('milk', 1, 1.5), ('banana', 12, 0.8), ('yogurt', 2, 1.8)]
Enter fullscreen mode Exit fullscreen mode

3. Look for built-in functions

You'll be surprised that there's built-in functionality for almost everything in Python. Whether it's to find min, max, or to reverse and sort an iterable, you don't need to write nested loops! Just do a quick Google search to see if an easy way out exists.

4. Use default and keyword arguments

You can define default values for function parameters, so if a user doesn't provide a value for that parameter, the default will be used.
Here's an example.

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")      
greet("Bob", "Hi")  

Enter fullscreen mode Exit fullscreen mode

Similarly, for keyword arguments, instead of relying on their order, you can pass arguments by their names, making the function call more explicit and easier to understand.

def calculate_interest(principal, rate, time):
    return principal * rate * time / 100

# Calling the function using positional arguments
interest1 = calculate_interest(1000, 5, 3)

# Calling the function using keyword arguments
interest2 = calculate_interest(principal=1000, rate=5, time=3)

Enter fullscreen mode Exit fullscreen mode

5. Use PEP 8

Last but not least, follow pep-8 conventions. PEP 8 is the official style guide for Python programming, offering recommendations and best practices for well-structured Python code.
Key aspects covered by PEP 8 include guidelines on indentation, line length, variable and function naming conventions, import statements, and more.
You can read more about it here
Certain libraries can help you follow these conventions. Some famous ones are:

  1. isort (sorts imports in required order)
  2. pylint (checks for errors and suggest good practices)

Top comments (0)