今日已更新 178 条资讯 | 累计 22368 条内容
关于我们

#04 – Modules & Modern Python Project Structure

Thiruvengadam Sakthivel 2026年07月16日 23:34 3 次阅读 来源:Dev.to

Welcome to Day 4! Today is all about clean architecture, dependency isolation, and modern Python tooling. You will learn how to structure your files, control execution flows, use modern tools like uv to manage virtual environments at lightning speed, and organize a codebase like a professional software engineer. 🚀 1. Modules & Packages 📦 Module: A single .py file containing variables, functions, or classes you want to reuse. Package: A directory of modules. __init__.py : Runs automatically when a package is imported, allowing you to expose a clean top-level API and hide internal folder nesting. Absolute Import: Imports specifying the full path from the project root ( from app.core import analyze ). Preferred by PEP 8 . Relative Import: Imports relative to the current file using dots ( from .utils import clean ). Single dot . is current folder; double dot .. is parent folder. A. Core Modules & Packages 🌱 Easy Starter Example Creating a basic module and importing it: # file: calculator.py (Our module) def add ( a , b ): return a + b # file: main.py (Importing our module) import calculator print ( calculator . add ( 5 , 3 )) # Output: 8 🏛️ Real-World Example: Database Package API Exposing internal package functions cleanly using __init__.py : # Project Layout: database/ ├── __init__.py ├── auth.py (defines login_user()) └── query.py (defines fetch_data()) # database/__init__.py # Expose functions relative to this folder so users don't need deep imports from .auth import login_user from .query import fetch_data # main.py # Clean absolute package import for the end-user from database import login_user , fetch_data login_user ( " admin " , " password123 " ) B. Built-In vs. Third-Party Modules Built-In: Included with Python out-of-the-box (e.g., os , sys , json ). Third-Party: Built by the community and installed from PyPI (e.g., requests , rich ). 🌱 Easy Starter Example import math # Built-in math operations print ( math . sqrt ( 25 )) # Output: 5.0 # import requests # Th

本文内容来源于互联网,版权归原作者所有
查看原文