Dev Conventions
  • Dev Conventions
  • Git
    • Branch Flow
    • Conventional Commits
    • Pull requests template
    • Before making the PRs in typescript, keep in mind
  • Typescript
    • Introduction
    • Good practices
    • Solid
    • Using pnpm for Package Management
    • NestJs
    • NextJs
    • React
    • NestJs Testing
    • React Testing
    • Npm Registry
  • PYTHON
    • Introduction
    • Good practices
    • Testing
    • Naming Convention
  • DevOps
    • Introduction
    • Github Actions
    • Creating a Github Actions Workflow
  • Agile
    • Story Points
Powered by GitBook
On this page
  • Strict Typing
  • Variable Typing
  • Function Typing
  • Custom Typing
  • General Conventions
  • Magic String
  • Avoid Any
  • Keep Efficiency in Mind
  • Avoid Code Duplication (DRY)
  • Use List Comprehensions and Generators
  • Project Structure
  • Use Descriptive Names
  • Divide Code into Functions and Classes
  • Documentation
  • Tools and Configuration
  • Follow PEP 8 Style Conventions
  • If You Use PyCharm
  • Integrate Unit Tests
  • Conclusions
  1. PYTHON

Good practices

Strict Typing

Strict typing in Python is a fundamental feature that allows detecting and preventing type errors during the development phase. This helps improve the quality and robustness of the code, as well as facilitating its maintenance and refactoring.

Variable Typing

  • Basic types

  • List typing

  • Dictionary typing

from typing import List, Dict, Union

name: str = "Juan"
name_list: List[str] = ["Juan", "Jose"]
my_dictionary: Dict[str, Union[str, int, bool]] = {
    'name': 'Juan',
    'age': 30,
    'active': True
}

Function Typing

  • Parameters

  • Return types

def convert_to_negative(text: str) -> str:
    text = re.sub(r"\((-?\d+(\.\d+)?)\)", lambda x: "-" + x.group(1), text)
    return text

Custom Typing

from datetime import datetime
from typing import Tuple

from pydantic import BaseModel

class Delivery(BaseModel):
    timestamp: datetime
    dimensions: Tuple[int, int]

m = Delivery(timestamp='2020-01-02T03:04:05Z', dimensions=['10', '20'])
print(m.timestamp)  # Output: datetime.datetime(2020, 1, 2, 3, 4, 5, tzinfo=TzInfo(UTC))
print(m.dimensions)  # Output: (10, 20)

General Conventions

Magic String

Avoid "Magic Strings": Do not use literal strings directly in the code, especially when referring to known constants. Instead, define constants or enumerations to represent these values.

Avoid Any

Avoid using any as much as possible, as it removes type checking and can introduce hard-to-detect errors.

Keep Efficiency in Mind

Write efficient and optimized code, especially in loops and operations that run multiple times. Use tools like the timeit module to measure performance and make optimizations as needed.

Avoid Code Duplication (DRY)

Avoid repeating the same code by writing it once and reusing it in different parts of your program. If you find that you are repeating code, consider refactoring it into a separate function or method.

Use List Comprehensions and Generators

List comprehensions and generators are elegant and efficient ways to create and manipulate lists in Python. Use them instead of traditional for loops whenever possible.

Using a for loop:

numbers = [1, 2, 3, 4, 5]
squares = []

for num in numbers:
    squares.append(num ** 2)

print(squares)  # Output: [1, 4, 9, 16, 25]

Using a list comprehension:

numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]

print(squares)  # Output: [1, 4, 9, 16, 25]

Project Structure

Use Descriptive Names

Use meaningful and descriptive names for variables, functions, and classes. This makes your code more readable and understandable for other developers.

Divide Code into Functions and Classes

Divide your code into small, well-defined functions and classes, each with a single responsibility. This makes your code more modular, reusable, and easier to maintain.

Documentation

Document your code using docstrings for functions, classes, and modules. This provides a quick and useful reference for other developers who use or maintain your code. Example:

def convert_to_negative(text: str) -> str:
    """
    Function that converts text to negative value
    Args:
        text (str): The value to normalize.
    Returns:
        str: The normalized value.
    Exception:
        ValueError: The value is not a negative value.
    Examples:
        >>> convert_to_negative("(25.32)")
        '-25.32'
    """
    text = re.sub(r"\((-?\d+(\.\d+)?)\)", lambda x: "-" + x.group(1), text)
    return text

Tools and Configuration

Follow PEP 8 Style Conventions

PEP 8 is the style guide for writing Python code. Follow PEP 8 rules to maintain consistency in your code style. You can use tools like flake8 or pylint to automatically check PEP 8 compliance.

If You Use PyCharm

We recommend making the following configurations to ensure the code follows the same settings: activate Reformat code, Optimize imports, and Run Black in Settings -> Tools -> Actions on save.

Integrate Unit Tests

Write unit tests to verify the expected behavior of your code. Unit tests help ensure that your code works correctly and provide confidence when refactoring or making changes to the code.

Conclusions

In summary, implementing strict typing in Python is essential for detecting and preventing type errors during the development phase, leading to more robust and higher-quality code. Through the typing of variables, functions, and data structures, along with adherence to recommended general practices such as avoiding "Magic Strings," keeping efficiency in mind, and following PEP 8 style conventions, the readability, maintainability, and efficiency of Python code are improved. Additionally, proper project structuring, complete documentation, and the integration of unit tests are crucial practices to ensure consistency and code quality over time. Together, these measures contribute to more robust, scalable, and maintainable software development in Python.

PreviousIntroductionNextTesting

Last updated 11 months ago