P

Módulos & Pacotes

Python Syntax Guide

Importar e organizar código com módulos e pacotes

Módulos & Pacotes

Importar e organizar código com módulos e pacotes

Python módulos & pacotes (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 organiza código em módulos e pacotes. O sistema de importação permite reutilizar código através de projetos. Os arquivos __init__.py definem pacotes.

Common Use Cases

  • Organização de código
  • Reutilização
  • Gerenciamento de dependências
  • Separação de namespaces

Related Python Syntax

Master Módulos & Pacotes in Python

Understanding Módulos & Pacotes 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 Módulos & Pacotes effectively in your Python projects.

Key Takeaways

  • Organização de código
  • Reutilização
  • Gerenciamento de dependências