P

Modules & Packages

Python syntax guide

Importing and organizing code with modules and packages

Modules & Packages

Importing and organizing code with modules and packages

Python modules & packages (python)
        
          # Importing modules
import math
print(math.pi)  # 3.141592653589793
print(math.sqrt(16))  # 4.0

# Import specific functions
from math import pi, sqrt
print(pi, sqrt(25))  # 3.141592653589793 5.0

# Import with alias
import numpy as np
# import pandas as pd

# Relative imports (within packages)
# from .utils import helper_function
# from ..parent_module import ParentClass

# Creating a module
# Save this in utils.py
def helper_function():
    return "Helper function"

class UtilityClass:
    pass

# Importing custom module
# import utils
# from utils import helper_function, UtilityClass

# __init__.py for packages
# This file makes a directory a Python package

# Example package structure:
# mypackage/
#   __init__.py
#   module1.py
#   module2.py
#   subpackage/
#       __init__.py
#       submodule.py

# Conditional imports
try:
    import optional_module
    HAS_OPTIONAL = True
except ImportError:
    HAS_OPTIONAL = False

# __name__ and __main__
if __name__ == "__main__":
    print("This module is being run directly")
else:
    print("This module is being imported")
        
      

Explanation

Python organizes code into modules and packages. The import system allows reusing code across projects. __init__.py files define packages.

Common Use Cases

  • Code organization
  • Reusability
  • Dependency management
  • Namespace separation

Related Python Syntax

Master Modules & Packages in Python

Understanding modules & packages is fundamental to writing clean and efficient Python code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using modules & packages effectively in your Python projects.

Key Takeaways

  • Code organization
  • Reusability
  • Dependency management