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
# 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
Common Use Cases
- Organização de código
- Reutilização
- Gerenciamento de dependências
- Separação de namespaces
Related Python Syntax
Variables & Data Types
Python variables and data types
Control Flow
Conditional statements and loops in Python
Functions & Generators
Function definitions and generator functions in Python
Classes & OOP
Object-oriented programming with classes in Python
Exception Handling
Error handling with try/except blocks in Python
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