- Mengapa Virtual Environment?
- venv β Built-in Virtual Env
- pip dan requirements.txt
- pip-tools β Dependency Pinning
- Poetry β Modern Package Manager
- Conda β Data Science Environment
- uv β Ultra-fast Package Manager
- pyproject.toml β Modern Config
- Workflow Sehari-hari
- Virtual Env + Docker
- Best Practices
- Quiz Pemahaman
1. Mengapa Virtual Environment?
Bayangkan kamu mengerjakan dua proyek: Proyek A memerlukan requests==2.28 sedangkan Proyek B memerlukan requests==2.31. Jika kamu menginstal keduanya secara global, akan terjadi konflik versi. Virtual environment menyelesaikan masalah ini.
Masalah Tanpa Virtual Environment
Tanpa virtual environment, semua package terinstal di satu tempat global. Jika Proyek A butuh Django 4.2 dan Proyek B butuh Django 3.2, kamu tidak bisa keduanya terinstal bersamaan. Satu-satunya solusi adalah meng-uninstall dan install ulang setiap kali ganti proyek β sangat merepotkan dan rentan error.
Apa Itu Virtual Environment?
| Aspek | Penjelasan |
|---|---|
| Definisi | Environment Python terisolasi dengan package dan dependency sendiri |
| Isolasi | Setiap venv memiliki folder site-packages sendiri |
| Python Version | Bisa menggunakan versi Python yang berbeda per proyek |
| No Conflict | Package di satu proyek tidak mempengaruhi proyek lain |
| Reproducible | Bisa di-share via requirements.txt untuk replikasi |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β VIRTUAL ENVIRONMENT β β β β Python Global Install β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β python3.11 β β β β pip (global) β β β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Project A: .venv/ Project B: .venv/ β β ββββββββββββββββββββ ββββββββββββββββββββ β β β bin/python3.11 β β bin/python3.11 β β β β bin/pip β β bin/pip β β β β site-packages/ β β site-packages/ β β β β βββ django==4.2 β β βββ django==3.2 β β β β βββ requests β β βββ flask==3.0 β β β β βββ pandas β β βββ sqlalchemy β β β ββββββββββββββββββββ ββββββββββββββββββββ β β β β Kedua environment terisolasi β TIDAK saling mempengaruhi β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Perbandingan Tools
| Tool | Type | Keunggulan | Cocok Untuk |
|---|---|---|---|
venv | Built-in | Sederhana, tidak perlu install | Proyek sederhana |
pip | Built-in | Package installer standar | Package management dasar |
pip-tools | Third-party | Dependency pinning, reproducible | Proyek production |
Poetry | Third-party | All-in-one (env + package + build + publish) | Library/app development |
Conda | Third-party | Multi-language, binary packages | Data science, ML |
uv | Third-party | Sangat cepat (Rust-based) | Semua proyek (modern) |
2. venv β Built-in Virtual Environment
venv adalah modul standar Python untuk membuat virtual environment. Sudah included sejak Python 3.3, tidak perlu instalasi tambahan.
Membuat Virtual Environment
# ===== Membuat virtual environment ===== # Nama konvensi: .venv atau venv python3 -m venv .venv # Dengan Python versi spesifik python3.11 -m venv .venv python3.12 -m venv .venv # Dengan pip versi terbaru python3 -m venv --upgrade-deps .venv # Tanpa pip (hemat space) python3 -m venv --without-pip .venv # ===== Mengaktifkan virtual environment ===== # Linux / macOS: source .venv/bin/activate # Windows (Command Prompt): .venv\Scripts\activate.bat # Windows (PowerShell): .venv\Scripts\Activate.ps1 # Windows (Git Bash): source .venv/Scripts/activate # ===== Setelah aktif, prompt berubah ===== # (.venv) user@machine:~/project$ # ===== Verifikasi ===== which python # β /home/user/project/.venv/bin/python which pip # β /home/user/project/.venv/bin/pip python --version # ===== Deactivate ===== deactivate # ===== Menghapus virtual environment ===== rm -rf .venv # Linux/Mac rmdir /s /q .venv # Windows
Struktur Virtual Environment
# Struktur folder venv (Linux/macOS): .venv/ βββ bin/ β βββ activate # Script aktivasi (bash) β βββ activate.csh # Script aktivasi (csh) β βββ activate.fish # Script aktivasi (fish) β βββ python # Symlink ke Python interpreter β βββ python3 # Symlink ke Python interpreter β βββ pip # pip executable βββ include/ # Header files (C extensions) βββ lib/ β βββ python3.11/ β βββ site-packages/ # β Packages terinstal di sini β βββ pip/ β βββ setuptools/ β βββ ... βββ pyvenv.cfg # Konfigurasi venv βββ share/ # Shared data # Struktur folder venv (Windows): .venv/ βββ Scripts/ β βββ activate.bat β βββ activate.ps1 β βββ python.exe β βββ pip.exe βββ Lib/ β βββ site-packages/ βββ Include/ βββ pyvenv.cfg βββ tcl/ # Isi pyvenv.cfg: # home = /usr/bin # include-system-site-packages = false # version = 3.11.4 # executable = /usr/bin/python3.11 # command = /usr/bin/python3 -m venv /home/user/project/.venv
Tambahkan .venv/ ke .gitignore agar virtual environment tidak masuk ke repository. Setiap developer bisa membuat venv sendiri dari requirements.txt.
3. pip dan requirements.txt
pip adalah package installer standar untuk Python. Digunakan bersama requirements.txt untuk mengelola dependency.
pip Commands
# ===== Instalasi packages ===== # Instal package terbaru pip install requests # Instal versi spesifik pip install requests==2.31.0 # Instal dengan batasan versi pip install "requests>=2.28,<3.0" pip install "django~=4.2" # Compatible release (>=4.2, ==4.*) pip install "flask>=3.0" # Minimum version # Instal dari git pip install git+https://github.com/user/repo.git pip install git+https://github.com/user/repo.git@branch-name pip install git+https://github.com/user/repo.git@v1.0.0 # Instal dari local directory pip install ./my-package/ pip install -e ./my-package/ # Editable mode (development) # Instal beberapa packages sekaligus pip install requests flask sqlalchemy # ===== Upgrade dan Uninstall ===== # Upgrade package pip install --upgrade requests pip install -U requests # Upgrade pip itu sendiri pip install --upgrade pip # Uninstall pip uninstall requests # ===== List dan Info ===== # List semua package terinstal pip list # List dengan format columns pip list --format=columns # List outdated packages pip list --outdated # Info tentang package pip show requests # ===== Requirements File ===== # Generate requirements.txt dari environment saat ini pip freeze > requirements.txt # Instal dari requirements.txt pip install -r requirements.txt # Instal dari requirements.txt dengan upgrade pip install -r requirements.txt --upgrade # ===== Cache ===== # Lihat cache pip cache info # Hapus cache pip cache purge
requirements.txt Best Practices
# requirements.txt β Production (pinned versions) # Untuk reproducible builds # Web framework django==4.2.13 djangorestframework==3.15.2 # Database psycopg2-binary==2.9.9 sqlalchemy==2.0.31 # HTTP requests==2.32.3 httpx==0.27.0 # Task queue celery==5.4.0 redis==5.0.7 # Testing pytest==8.2.2 pytest-django==4.8.0 pytest-cov==5.0.0 # Development ruff==0.5.0 mypy==1.10.0 ipython==8.25.0
# requirements.in β Base requirements (unpinned) # Digunakan dengan pip-tools untuk generate pinned requirements.txt django>=4.2,<5.0 djangorestframework>=3.15 psycopg2-binary>=2.9 sqlalchemy>=2.0 requests>=2.28 httpx>=0.27 celery>=5.4 redis>=5.0 # Dev dependencies (opsional, pisahkan ke requirements-dev.in) pytest pytest-django ruff mypy
Constraints dan Layering
# Pisahkan dependency berdasarkan environment: # requirements-base.txt β shared dependencies # requirements.txt β production (includes base) # requirements-dev.txt β development (includes base + testing tools) # requirements-test.txt β testing only # Contoh requirements-dev.txt: # -r requirements.txt pytest>=8.0 pytest-cov>=5.0 ruff>=0.5 mypy>=1.10 ipython>=8.0 debugpy>=1.8 # Menggunakan constraint file # constraints.txt: membatasi versi tanpa menginstall # django==4.2.13 # sqlalchemy==2.0.31 pip install -r requirements.txt -c constraints.txt # Instal requirements-dev pip install -r requirements-dev.txt
4. pip-tools β Dependency Pinning
pip-tools menyediakan workflow yang lebih baik untuk mengelola dependency dengan memisahkan antara requirement yang diinginkan (unpinned) dan requirement yang di-resolve (pinned).
# ===== Instalasi pip-tools ===== pip install pip-tools # ===== Workflow pip-tools ===== # 1. Buat requirements.in (input β apa yang kamu butuhkan) # requirements.in: # django>=4.2 # requests>=2.28 # sqlalchemy>=2.0 # 2. Compile ke requirements.txt (output β resolved, pinned) pip-compile requirements.in # Menghasilkan requirements.txt dengan versi exact + hash # django==4.2.13 (via django>=4.2) # requests==2.32.3 (via requests>=2.28) # sqlalchemy==2.0.31 (via sqlalchemy>=2.0) # ... beserta semua transitive dependencies # 3. Sync environment dengan requirements.txt pip-sync requirements.txt # Menginstall yang kurang, menghapus yang tidak perlu # ===== Advanced pip-tools ===== # Compile dengan upgrade semua pip-compile --upgrade requirements.in # Compile dengan upgrade package tertentu pip-compile --upgrade-package django requirements.in # Output ke file berbeda pip-compile requirements.in -o requirements.txt # Dev dependencies pip-compile requirements-dev.in -o requirements-dev.txt # Generate dengan hashes (untuk security) pip-compile --generate-hashes requirements.in # Sync dari multiple requirements files pip-sync requirements.txt requirements-dev.txt # ===== pip-tools Configuration (pyproject.toml) ===== # [tool.pip-tools] # generate-hashes = true # allow-unsafe = false # strip-extras = true
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β PIP-TOOLS WORKFLOW β β β β requirements.in requirements.txt β β ββββββββββββββββ ββββββββββββββββββββββββββββ β β β django>=4.2 β ββcompileβββ β django==4.2.13 β β β β requests>=2 β β requests==2.32.3 β β β β sqlalchemy>2 β β sqlalchemy==2.0.31 β β β ββββββββββββββββ β certifi==2024.6.2 β β β (apa yang kamu mau) β urllib3==2.2.2 β β β β ... (20+ transitive) β β β βββββββββββββ¬βββββββββββββββ β β β β β βΌ β β ββββββββββββββββ β β β pip-sync β β β β (install + β β β β uninstall) β β β ββββββββββββββββ β β β β β βΌ β β ββββββββββββββββ β β β .venv/ β β β β (ter-sync) β β β ββββββββββββββββ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
5. Poetry β Modern Package Manager
Poetry adalah all-in-one tool untuk dependency management, virtual environment, building, dan publishing Python packages. Ini menjadi standar de facto untuk proyek Python modern.
Instalasi dan Setup
# ===== Instalasi Poetry ===== # Linux / macOS / WSL curl -sSL https://install.python-poetry.org | python3 - # Windows (PowerShell) (Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python - # Atau via pip (kurang recommended) pip install poetry # Verifikasi poetry --version # ===== Konfigurasi ===== # Membuat venv di dalam project folder (recommended) poetry config virtualenvs.in-project true # Lihat semua konfigurasi poetry config --list # ===== Membuat Project Baru ===== poetry new my-project # Menghasilkan: # my-project/ # βββ pyproject.toml # βββ README.md # βββ my_project/ # β βββ __init__.py # βββ tests/ # βββ __init__.py # Inisialisasi di project yang sudah ada cd existing-project poetry init
Dependency Management dengan Poetry
# ===== Menambah dependencies ===== # Add production dependency poetry add requests poetry add "django>=4.2,<5.0" poetry add sqlalchemy@^2.0 # Add dev dependency poetry add --group dev pytest ruff mypy poetry add -G dev pytest # Add optional dependency poetry add --group optional redis # ===== Menghapus dependencies ===== poetry remove requests poetry remove --group dev pytest # ===== Install semua dependencies ===== poetry install # Install tanpa dev dependencies poetry install --only main # Install hanya dev poetry install --only dev # ===== Update dependencies ===== # Update semua poetry update # Update package tertentu poetry update requests # ===== Lock file ===== # poetry.lock otomatis dibuat/diupdate # SELALU commit poetry.lock ke git! # Re-resolve semua dependencies poetry lock # Lock tanpa update poetry lock --no-update # ===== List dependencies ===== poetry show poetry show --tree # Dengan dependency tree poetry show --outdated # Package yang bisa diupdate # ===== Export ke requirements.txt ===== poetry export -f requirements.txt --output requirements.txt poetry export -f requirements.txt --without-hashes -o requirements.txt
pyproject.toml dengan Poetry
[tool.poetry]
name = "my-awesome-project"
version = "1.0.0"
description = "Deskripsi project kamu"
authors = ["Budi Santoso <budi@email.com>"]
license = "MIT"
readme = "README.md"
repository = "https://github.com/user/my-project"
keywords = ["python", "tutorial"]
packages = [{include = "my_project"}]
[tool.poetry.dependencies]
python = "^3.11"
django = "^4.2"
djangorestframework = "^3.15"
requests = "^2.31"
sqlalchemy = "^2.0"
celery = {version = "^5.4", extras = ["redis"]}
redis = "^5.0"
gunicorn = {version = "^22.0", optional = true}
[tool.poetry.group.dev.dependencies]
pytest = "^8.2"
pytest-cov = "^5.0"
pytest-django = "^4.8"
ruff = "^0.5"
mypy = "^1.10"
ipython = "^8.25"
[tool.poetry.group.docs.dependencies]
sphinx = "^7.3"
sphinx-rtd-theme = "^2.0"
[tool.poetry.scripts]
myproject = "my_project.cli:main"
[tool.poetry.plugins."my_project.plugins"]
myplugin = "my_project.plugins:MyPlugin"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
Poetry Commands Lengkap
# ===== Virtual Environment ===== poetry env info # Info tentang venv poetry env list # List semua venv poetry env use python3.11 # Ganti Python version poetry env remove .venv # Hapus venv # ===== Running ===== poetry run python script.py # Jalankan script di venv poetry run pytest # Jalankan pytest di venv poetry run python -m mymodule # Shell di dalam venv poetry shell # Sekarang semua command berjalan di venv exit # Keluar dari shell # ===== Building dan Publishing ===== # Build package poetry build # Menghasilkan dist/my_project-1.0.0.tar.gz dan .whl # Publish ke PyPI poetry publish # Build + Publish poetry publish --build # Publish ke private repository poetry config repositories.private https://private.pypi.org/simple/ poetry publish -r private # ===== Check dan Versioning ===== poetry check # Validasi pyproject.toml poetry version # Lihat versi poetry version patch # 1.0.0 β 1.0.1 poetry version minor # 1.0.0 β 1.1.0 poetry version major # 1.0.0 β 2.0.0
6. Conda β Data Science Environment
Conda adalah package dan environment manager yang sangat populer di kalangan data scientist. Berbeda dengan pip yang hanya mengelola Python packages, Conda bisa mengelola packages dari berbagai bahasa (C, C++, R, dll).
Instalasi Miniconda
# ===== Instalasi Miniconda (recommended, lebih ringan dari Anaconda) ===== # Linux wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh # macOS wget https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh bash Miniconda3-latest-MacOSX-arm64.sh # Windows: Download installer dari https://docs.conda.io/en/latest/miniconda.html # Verifikasi conda --version conda info # ===== Konfigurasi ===== # Auto-activate base environment (optional) conda config --set auto_activate_base false # Tambah channel conda config --add channels conda-forge conda config --set channel_priority strict
Conda Environment Management
# ===== Membuat Environment ===== # Buat env dengan Python versi spesifik conda create -n myproject python=3.11 # Buat env dengan beberapa packages conda create -n datascience python=3.11 numpy pandas scikit-learn jupyter # Buat env dari file conda env create -f environment.yml # Buat env di folder spesifik conda create --prefix ./envs python=3.11 # ===== Mengaktifkan / Deactivate ===== conda activate myproject conda deactivate # ===== List Environments ===== conda env list # atau conda info --envs # ===== Install / Update / Remove Packages ===== # Install conda install numpy pandas matplotlib conda install -c conda-forge scikit-learn conda install "numpy>=1.24,<2.0" # Update conda update numpy conda update --all # Remove conda remove numpy # ===== Export / Import Environment ===== # Export ke YAML conda env export > environment.yml conda env export --no-builds > environment.yml # Tanpa build numbers # Export hanya packages yang diinstall secara eksplisit conda env export --from-history > environment.yml # Import dari YAML conda env create -f environment.yml # Update existing env dari YAML conda env update -f environment.yml --prune # ===== YAML File ===== # environment.yml: # name: myproject # channels: # - conda-forge # - defaults # dependencies: # - python=3.11 # - numpy>=1.24 # - pandas>=2.0 # - scikit-learn>=1.3 # - pip: # - some-pip-package>=1.0
7. uv β Ultra-fast Package Manager
uv adalah package manager baru yang ditulis dalam Rust, menawarkan kecepatan 10-100x lebih cepat dari pip. Dikembangkan oleh tim Astral (pembuat Ruff).
# ===== Instalasi uv ===== # Linux / macOS curl -LsSf https://astral.sh/uv/install.sh | sh # Windows (PowerShell) powershell -c "irm https://astral.sh/uv/install.ps1 | iex" # Atau via pip pip install uv # Verifikasi uv --version # ===== Virtual Environment ===== # Buat venv dengan uv (sangat cepat!) uv venv uv venv --python 3.11 uv venv .venv --python 3.12 # ===== Install Packages ===== # Install packages (10-100x lebih cepat dari pip!) uv pip install requests uv pip install "django>=4.2" sqlalchemy # Install dari requirements.txt uv pip install -r requirements.txt # Compile requirements uv pip compile requirements.in -o requirements.txt # Sync environment uv pip sync requirements.txt # ===== uv sebagai Python Manager ===== # Install Python versions uv python install 3.11 3.12 3.13 uv python list # ===== uv Project Management (v0.4+) ===== # Inisialisasi project uv init my-project cd my-project # Tambah dependency uv add requests uv add "django>=4.2" uv add --dev pytest ruff # Remove dependency uv remove requests # Run command uv run python script.py uv run pytest # Lock dependencies uv lock # Sync environment uv sync # ===== Benchmark ===== # pip install (dengan cache): ~10 detik # uv pip install (dengan cache): ~0.3 detik # Perbedaan sangat signifikan untuk CI/CD!
uv ditulis dalam Rust dan menggunakan parallel downloading + caching yang sangat efisien. Untuk CI/CD pipeline yang perlu menginstal dependencies berkali-kali, uv bisa menghemat waktu build secara drastis. uv juga bisa menggantikan pip, pip-tools, dan bahkan virtualenv.
8. pyproject.toml β Modern Configuration
pyproject.toml adalah file konfigurasi standar modern untuk proyek Python (PEP 518, PEP 621). Menggantikan setup.py, setup.cfg, requirements.txt untuk banyak kasus.
# pyproject.toml β Standalone (tanpa Poetry)
[project]
name = "my-project"
version = "1.0.0"
description = "Deskripsi project"
readme = "README.md"
license = {text = "MIT"}
requires-python = ">=3.11"
authors = [
{name = "Budi Santoso", email = "budi@email.com"},
]
keywords = ["python", "web", "api"]
classifiers = [
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
]
# Dependencies
dependencies = [
"django>=4.2,<5.0",
"djangorestframework>=3.15",
"requests>=2.28",
"sqlalchemy>=2.0",
]
# Optional dependencies
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"pytest-cov>=5.0",
"ruff>=0.5",
"mypy>=1.10",
]
docs = [
"sphinx>=7.3",
"sphinx-rtd-theme>=2.0",
]
all = [
"my-project[dev,docs]",
]
# Entry points / CLI
[project.scripts]
myproject = "my_project.cli:main"
# URLs
[project.urls]
Homepage = "https://github.com/user/my-project"
Documentation = "https://my-project.readthedocs.io"
Repository = "https://github.com/user/my-project"
Issues = "https://github.com/user/my-project/issues"
# ===== Build System =====
[build-system]
requires = ["setuptools>=68.0", "wheel"]
build-backend = "setuptools.backends._legacy:_Backend"
# ===== Tool Configurations =====
# Ruff (linter + formatter)
[tool.ruff]
target-version = "py311"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "N", "W", "UP", "B", "A", "SIM"]
# Pytest
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = "test_*.py"
addopts = "-v --tb=short --cov=my_project"
# MyPy
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
# Coverage
[tool.coverage.run]
source = ["my_project"]
omit = ["tests/*"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"if TYPE_CHECKING:",
"if __name__ == .__main__.",
]
9. Workflow Sehari-hari
Workflow Standar dengan venv + pip
# ===== Setup Awal Project ===== mkdir my-project && cd my-project git init # Buat virtual environment python3 -m venv .venv source .venv/bin/activate # Linux/Mac # .venv\Scripts\activate # Windows # Buat file standar touch README.md echo ".venv/" >> .gitignore echo "__pycache__/" >> .gitignore echo "*.pyc" >> .gitignore # Install dependencies pip install django pytest ruff pip freeze > requirements.txt # ===== Daily Development ===== # Aktivasi (setiap buka terminal baru) source .venv/bin/activate # Install package baru pip install new-package pip freeze > requirements.txt # Update requirements! git add requirements.txt git commit -m "Add new-package dependency" # ===== Join Project yang Sudah Ada ===== git clone https://github.com/user/project.git cd project python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt # ===== Deployment Preparation ===== pip install -r requirements.txt python manage.py test # Jalankan test ruff check . # Lint check python manage.py collectstatic # Django specific
Workflow dengan Poetry
# ===== Setup Awal ===== poetry new my-project cd my-project git init # Tambah dependencies poetry add django requests sqlalchemy poetry add --group dev pytest ruff mypy # ===== Daily Development ===== # Tidak perlu aktivasi manual β poetry handle semuanya! poetry run python manage.py runserver poetry run pytest poetry run ruff check . # Atau masuk ke shell poetry shell python manage.py runserver pytest exit # Tambah dependency baru poetry add httpx # Poetry otomatis update pyproject.toml dan poetry.lock! # Commit ke git git add pyproject.toml poetry.lock git commit -m "Add httpx dependency" # ===== Join Project ===== git clone https://github.com/user/project.git cd project poetry install # Poetry baca pyproject.toml + poetry.lock, install semua! # ===== Update Dependencies ===== poetry update # Update semua poetry update requests # Update satu package poetry show --outdated # Cek yang bisa diupdate
10. Virtual Env + Docker
# ===== Dockerfile dengan venv =====
FROM python:3.11-slim
WORKDIR /app
# Buat virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application
COPY . .
# Run
CMD ["python", "app.py"]
# ===== Dockerfile dengan Poetry =====
FROM python:3.11-slim
WORKDIR /app
# Install Poetry
RUN pip install poetry && \
poetry config virtualenvs.in-project true
# Copy dependency files
COPY pyproject.toml poetry.lock ./
# Install dependencies (tanpa dev)
RUN poetry install --only main --no-interaction
# Copy application
COPY . .
# Activate venv
ENV PATH="/app/.venv/bin:$PATH"
CMD ["python", "app.py"]
# ===== Multi-stage build (lebih kecil) =====
FROM python:3.11-slim AS builder
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.11-slim AS runtime
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY . .
CMD ["python", "app.py"]
# ===== docker-compose.yml =====
# version: "3.8"
# services:
# app:
# build: .
# volumes:
# - .:/app
# ports:
# - "8000:8000"
# environment:
# - DATABASE_URL=postgresql://user:pass@db:5432/mydb
# db:
# image: postgres:15
# environment:
# - POSTGRES_PASSWORD=pass
11. Best Practices
Golden Rules
| Rule | Penjelasan |
|---|---|
| π₯ SELALU gunakan venv | Jangan pernah install package ke system Python secara global |
| π Pin versi di production | Gunakan exact versions (==) di requirements.txt |
| π Commit lock files | poetry.lock dan requirements.txt harus masuk git |
| π« Jangan commit venv | Selalu tambahkan .venv/ ke .gitignore |
| π Pisahkan deps | Pisahkan production deps dan dev deps |
| π Update berkala | Jalankan pip-audit atau pip list --outdated secara berkala |
# .gitignore β Python project # Virtual environments .venv/ venv/ env/ ENV/ # Python __pycache__/ *.py[cod] *$py.class *.so *.egg-info/ dist/ build/ *.egg # IDE .vscode/ .idea/ *.swp *.swo # OS .DS_Store Thumbs.db # Environment variables .env .env.local # Coverage .coverage htmlcov/ # Mypy .mypy_cache/ # Ruff .ruff_cache/ # Pytest .pytest_cache/ # Jupyter .ipynb_checkpoints/
Kapan Menggunakan Tool Apa?
# ===== Decision Tree ===== # # Kamu membuat apa? # β # βββ π Library yang akan di-publish ke PyPI? # β βββ β Poetry atau Hatchling # β # βββ π Web application / API? # β βββ β venv + pip-tools (atau Poetry) # β # βββ π Data Science / Machine Learning? # β βββ β Conda (atau mamba) # β # βββ π€ Script / Automation? # β βββ β venv + pip (simplest) # β # βββ β‘ Performance-critical CI/CD? # β βββ β uv (sangat cepat) # β # βββ π’ Enterprise / Tim besar? # βββ β Poetry (atau PDM) + Docker # # ===== Quick Reference ===== # # Tool β Buat Venv β Install β Lock β Build β Publish # ββββββββββββΌββββββββββββΌββββββββββΌβββββββΌββββββββΌββββββββ # venv+pip β β β β β β β β β β # pip-tools β β β β β β β β β β # Poetry β β β β β β β β β β # Conda β β β β β β β β β β # uv β β β β β β β β β β # PDM β β β β β β β β β β
12. Quiz: Uji Pemahamanmu!
Setelah membaca tutorial di atas, jawablah 5 pertanyaan berikut: