Clean Coding Principles in Python Py
Clean Coding Principles in Python Py
**Clean code is a set of rules and principles that help to keep our code readable,
maintainable, and extendable.**

4. **Meaningful Names** ✌
- Use descriptive and meaningful names for variables, functions, and classes.
- This improves code readability and helps others understand the purpose of each
component.
These principles help ensure your code is clean, readable, and maintainable.
# Unclean Code:
def print_user_details(name, age):
print(f"Name: {name}")
print(f"Age: {age}")
print_user_details("Alice", 30)
print_employee_details("Bob", 25, "E123")
print_details("Alice", 30)
print_details("Bob", 25, "E123")
"""
# Unclean Code:
def calculate_area(length, width):
return length * width
length = 5
width = 3
area = calculate_area(length, width)
perimeter = calculate_perimeter(length, width)
print(f"Area: {area}, Perimeter: {perimeter}")
length = 5
width = 3
area, perimeter = calculate_area_and_perimeter(length, width)
print(f"Area: {area}, Perimeter: {perimeter}")
"""
# Unclean Code:
def is_even(number):
if number % 2 == 0:
return True
else:
return False
# Clean Code:
def is_even(number):
return number % 2 == 0
"""
"""
# Unclean Code
def get_even_numbers(numbers):
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
return even_numbers
#Clean Code:
def get_even_numbers(numbers):
return [number for number in numbers if number % 2 == 0]
SOLID is a set of five object-oriented design principles that can help you write
more maintainable, flexible, and scalable code based on well-designed, cleanly
structured classes.
# Unclean Code:
class User:
def __init__(self, name, email):
self.name = name
self.email = email
# Clean Code:
class User:
def __init__(self, name, email):
self.name = name
self.email = email
class EmailService:
def send_email(self, user, message):
# Code to send email
pass
* Software entities should be open for extension but closed for modification.
"""
# Unclean code
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# This code violates OCP because adding a new shape requires modifying existing
classes.
# Clean code:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# New shapes can be added by extending the Shape class without modifying existing
code.
"""
class Bird:
def fly(self):
pass
class Ostrich(Bird):
def fly(self):
# This violates LSP because Ostrich cannot fly, which breaks the expected
behavior of Bird.
raise Exception("Ostriches can't fly")
class Bird:
def move(self):
pass
class FlyingBird(Bird):
def move(self):
print("Flying")
class Ostrich(Bird):
def move(self):
print("Running")
# The move method is used instead of fly, allowing Ostrich to have a different
behavior without violating LSP.
"""
# Unclean Code:
class Worker:
def work(self):
pass
def eat(self):
# This violates ISP because not all workers may need to implement the eat
method.
pass
# Clean Code
class Workable:
def work(self):
pass
class Eatable:
def eat(self):
pass
def eat(self):
pass
# Separate interfaces for work and eat ensure that classes only implement what they
need.
"""
# Unclean Code:
class BackendDeveloper:
def develop(self):
return "Writing Python code"
class FrontendDeveloper:
def develop(self):
return "Writing JavaScript code"
class Project:
def __init__(self):
self.backend = BackendDeveloper()
self.frontend = FrontendDeveloper()
def develop(self):
# This violates DIP because Project depends directly on BackendDeveloper
and FrontendDeveloper.
return f"{self.backend.develop()} and {self.frontend.develop()}"
# Clean Code:
class Developer:
def develop(self):
pass
class BackendDeveloper(Developer):
def develop(self):
return "Writing Python code"
class FrontendDeveloper(Developer):
def develop(self):
return "Writing JavaScript code"
class Project:
def __init__(self, developers):
self.developers = developers
def develop(self):
# Project depends on the abstract Developer class, not specific
implementations.
return " and ".join([developer.develop() for developer in self.developers])
"""
# Unclean Code:
def calc(x, y):
return x + y
a = 5
b = 3
result = calc(a, b)
print(result)
# Clean Code:
def calculate_sum(first_number, second_number):
return first_number + second_number
first_number = 5
second_number = 3
result = calculate_sum(first_number, second_number)
print(result)
# This is bad
genyyyymmddhhmmss = datetime.strptime('04/27/95 07:14:22', '%m/%d/%y %H:%M:%S')
# This is good
generation_datetime = datetime.strptime('04/27/95 07:14:22', '%m/%d/%y %H:%M:%S')
# This is good
first_name = 'Bob'
creation_timestamp = 1621535852
# This is good
client_first_name = 'Bob'
client_last_name = 'Smith'
# This is good
class Person:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
"""
# Unclean Code:
def add(a, b):
# This function adds two numbers
return a + b
Parameters:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of the two numbers.
"""
return a + b
**PEP 8 whitespace: **
**PEP 8 comments:**
# Bad Code
def example():
a = 1
b = 2
print(a + b)
# Good Code
def example():
a = 1
b = 2
print(a + b)
# Bad Code
def example():
print("This is a very long line that exceeds the recommended line length of 79
characters.")
# Good Code
def example():
print("This is a line that adheres to the recommended line length.")
# Bad Code
import os, sys
import numpy as np
# Good Code
import os
import sys
import numpy as np
# Bad Code
def myFunction():
myVariable = 10
return myVariable
# Good Code
def my_function():
my_variable = 10
return my_variable