Sunday 4 August 2024

Guidelines for Writing Clean and Maintainable Python Functions

 

1. Simplicity and Clarity

Keep It Simple: Avoid unnecessary complexity. Each function should do one thing and do it well.


Descriptive Naming: Use clear, descriptive names for functions and variables. Avoid abbreviations unless they are widely understood.


Type Annotations: Use type hints to clarify what types of arguments a function expects and what it returns.


def calculate_area(radius: float) -> float:

    return 3.14 * radius * radius


#clcoding.com


2. Avoid Hardcoding

Use Constants: Define constants for values that shouldn't change. Avoid magic numbers.


Parameterization: Make functions flexible by passing parameters instead of hardcoding values. python


PI = 3.14159


def calculate_circumference(radius: float, pi: 

                            float = PI) -> float:

    return 2 * pi * radius


#clcoding.com


3. Readability

Docstrings: Include a docstring that explains what the function does, its parameters, and its return value.


Consistent Indentation: Stick to 4 spaces per indentation level.


Avoid Long Lines: Break lines at 79 characters where possible.


def calculate_bmi(weight: float, height: float) -> float:

    """

    Calculate the Body Mass Index (BMI).


    :param weight: Weight in kilograms.

    :param height: Height in meters.

    :return: BMI value.

    """

    return weight / (height ** 2)


#clcoding.com


4. Testing and Error Handling

Input Validation: Check for invalid inputs and handle them gracefully.


Unit Tests: Write tests for each function. Ensure edge cases are covered.


def divide_numbers(numerator: float, denominator: float) -> float:

    if denominator == 0:

        raise ValueError("Denominator cannot be zero.")

    return numerator / denominator


#clcoding.com


5. Performance

Efficiency: Avoid unnecessary computations. Optimize for performance if the function will be called frequently or handle large data sets.


Avoid Global State: Don’t rely on or modify global variables


def is_prime(n: int) -> bool:

    if n <= 1:

        return False

    if n <= 3:

        return True

    if n % 2 == 0 or n % 3 == 0:

        return False

    i = 5

    while i * i <= n:

        if n % i == 0 or n % (i + 2) == 0:

            return False

        i += 6

    return True


#clcoding.com


6. DRY Principle

Don’t Repeat Yourself: Reuse code by abstracting common functionality into separate functions or modules.


def get_positive_input(prompt: str) -> float:

    value = float(input(prompt))

    if value <= 0:

        raise ValueError("Input must be a +ve number.")

    return value


#clcoding.com

0 Comments:

Post a Comment

Popular Posts

Categories

AI (29) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (122) C (77) C# (12) C++ (82) Course (67) Coursera (195) Cybersecurity (24) data management (11) Data Science (100) Data Strucures (7) Deep Learning (11) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (840) Python Coding Challenge (279) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses