Programmation Orientée Objet en Python
  • Back to Main Website
  • Home
  • Introduction: Histoire et Concepts
    • Introduction: Histoire et Concepts
    • Histoire de la programmation
    • Première Structuration des données
    • Naissance de la POO
    • Python: tout n’est qu’objet
    • Python : Simplicité des objets et performance sous-jacente
    • Classes en Python : Concepts fondamentaux

    • Travaux Pratiques
    • Construire sa propre Liste
    • Construire son propre DataFrame
  • Encapsulation, Héritage, Composition et Dunder
    • Encapsulation, Heritage, Composition et Dunder
    • Encapsulation en Python
    • Héritage en Python : Concept et intérêt
    • Héritage vs Composition
    • Méthodes Dunder en Python
    • Python call Method: A Fun Exploration

    • Travaux Pratiques
    • TP: Heritage avec le pricing d’option
    • TP : Ajouter des méthodes dunder à DataFrameSimple
    • TP : Étendre la classe Liste avec des méthodes dunder
    • TP: Dunder Method with Tensor for Automatic Differentiation
  • Polymorphisme et Surcharge
    • Polymorphisme et Surcharge
    • Polymorphism in Object-Oriented Programming
    • Polymorphism in Python: Function Overloading and Type Checking
    • Class Creation: Standard vs type()
    • Type Hinting, Typing Module, and Linters in Python
    • Abstract Classes
    • Protocol Classes

    • Travaux Pratiques
    • TP
  • Decorators
    • Design Patterns
    • The decorator pattern
    • Decorator Practically
    • Built-in Decorators and Standard Library Decorators in Python
    • Practical Decorators in Python Libraries

    • Travaux Pratiques
    • TP: Monte Carlo Option Pricing with Decorators
    • TP: Optimizing Heston Model Monte Carlo Simulation
  • Project Management and Packaging
    • Project and Package
    • Organizing Python Projects
    • Understanding imports
    • Python Package Management and Virtual Environments
    • Unit Testing in Python

    • Travaux Pratiques
    • TP: Creating a Linear Regression Package
  • Design Patterns
    • OOP Design Patterns
    • Python-Specific Design Patterns
    • Creation Design Patterns
    • Structural Design Patterns
    • Behavioral Design Pattern

    • Travaux Pratiques
    • TP
  • Sujets de Projets possibles
    • Projets
    • Projets POO - 2024-2025
  • Code source
  1. Organizing Python Projects
  • Project and Package
  • Organizing Python Projects
  • Understanding imports
  • Python Package Management and Virtual Environments
  • Unit Testing in Python
  • Travaux Pratiques
    • TP: Creating a Linear Regression Package

On this page

  • Organizing Python Projects and Creating Packages
    • 1. Understanding Python Imports and Project Structure (45 minutes)
      • How Python Imports Work
      • Best Practices for Directory Layout
      • Separating Source Code, Tests, and Documentation
      • Practical Example

Organizing Python Projects

Cours
Fondamentaux
Learn how to organize Python projects effectively and create packages for distribution.
Author

Remi Genet

Published

2024-10-21

Organizing Python Projects and Creating Packages


1. Understanding Python Imports and Project Structure (45 minutes)

How Python Imports Work

The Python Import System

Python’s import system is fundamental to how we organize and use code across multiple files and directories. Understanding it is crucial for structuring projects effectively.

  • When you use an import statement, Python searches for the module in several locations:
    1. The directory containing the script
    2. PYTHONPATH (if set)
    3. Standard library directories
    4. Site-packages directory (for installed third-party packages)

Understanding PATH and PYTHONPATH

  • PATH: An environment variable that tells the operating system where to look for executables. It’s not directly related to Python imports but is important for running Python from the command line.

  • PYTHONPATH: An environment variable that you can set to add additional directories where Python will look for modules and packages.

Importing from the Current Directory

To import modules from the current directory, you have several options:

  1. Run Python from the directory containing your modules:

    python my_script.py
  2. Add the current directory to PYTHONPATH:

    export PYTHONPATH=$PYTHONPATH:.
  3. Modify sys.path in your script:

    import sys
    import os
    sys.path.append(os.path.dirname(os.path.realpath(__file__)))

Viewing the Module Search Path

You can view the current module search path using:

import sys
print(sys.path)

Absolute vs. Relative Imports

  • Absolute imports use the full path from the project’s root:
from mypackage.submodule import myfunction
  • Relative imports use dots to refer to the current and parent packages:
from . import sibling_module
from .. import parent_package_module
  • Generally, absolute imports are preferred for clarity and to avoid confusion.

Best Practices for Directory Layout

A well-organized project structure enhances readability and maintainability. Here’s a common layout:

my_project/
│
├── my_package/
│   ├── __init__.py
│   ├── module1.py
│   └── module2.py
│
├── tests/
│   ├── test_module1.py
│   └── test_module2.py
│
├── docs/
│   └── index.md
│
├── pyproject.toml
└── README.md

Note: Some projects use a src/ directory (e.g., src/my_package/) to separate package code. While this can be beneficial for larger projects or when building distributions, it’s not mandatory and can add complexity for smaller projects.

Separating Source Code, Tests, and Documentation

  • Source Code (my_package/): Contains the actual package code
  • Tests (tests/): Keeps tests separate from source code
  • Documentation (docs/): Separates documentation from code
  • Project Files: pyproject.toml for project configuration, README.md for project overview

Practical Example

Let’s create a simple project structure:

# Create project directory
mkdir my_project
cd my_project

# Create package directory
mkdir my_package
touch my_package/__init__.py
touch my_package/module1.py

# Create tests directory
mkdir tests
touch tests/test_module1.py

# Create docs directory
mkdir docs
touch docs/index.md

# Create project files
touch pyproject.toml README.md

This structure sets the foundation for a well-organized Python project, making it easier to develop, test, and maintain your code.

Back to top
Project and Package
Understanding imports

Programmation Orienté Object en Python, Rémi Genet.
Licence
Code source disponible sur Github

 

Site construit avec et Quarto
Inspiration pour la mise en forme du site ici
Code source disponible sur GitHub