Open markeyser opened 2 months ago
This is the extension:
https://marketplace.visualstudio.com/items?itemName=assisrMatheus.sidebar-markdown-notes
This a good replacement of the Makefile. Let's use the Make file to really automate stuff...
Bellow the cheat sheets I have so far:
Initialize a new Git repository:
git init
Clone an existing repository:
git clone <repository-url>
Set global username:
git config --global user.name "Your Name"
Set global email:
git config --global user.email "your.email@example.com"
View configured username and email:
git config --global --list
Check the status of the working directory and staging area:
git status
✨Show the changes in the working directory:
git diff
Show the changes between the staging area and the latest commit:
git diff --staged
Show the commit history:
git log
Show a single-line log with graph:
git log --oneline --graph --all
Show detailed information about a specific commit:
git show <commit-id>
Add a specific file to the staging area:
git add <file>
Add all changes in the current directory to the staging area:
git add .
Commit changes with a message:
git commit -m "Your commit message"
Commit with a multi-line message:
git commit
Amend the last commit (don't do this if you've already pushed the commit):
git commit --amend -m "Updated commit message"
Create a new branch:
git branch <new-branch-name>
✨List all branches:
git branch
Switch to a different branch:
git checkout <branch-name>
✨Create a new branch and switch to it:
git checkout -b <new-branch-name>
Merge a branch into the current branch:
git merge <branch-name>
✨Delete a branch locally:
git branch -d <branch-name>
✨Delete a branch remotely:
git push origin --delete <branch-name>
Add a remote repository:
git remote add origin <repository-url>
List all remote repositories:
git remote -v
Remove a remote repository:
git remote remove <name>
✨Fetch changes from a remote repository:
git fetch
✨Pull changes from a remote repository and merge:
git pull
✨Push changes to a remote repository:
git push origin <branch-name>
Force push changes to a remote repository (use with caution):
git push origin <branch-name> --force
Stash current changes:
git stash
List stashed changes:
git stash list
Apply the latest stash:
git stash apply
Apply a specific stash:
git stash apply stash@{n}
Drop the latest stash:
git stash drop
Drop a specific stash:
git stash drop stash@{n}
Apply and drop the latest stash:
git stash pop
Start an interactive rebase:
git rebase -i HEAD~n # n is the number of commits to rebase
Continue a rebase after resolving conflicts:
git rebase --continue
Skip a commit during a rebase:
git rebase --skip
Abort a rebase:
git rebase --abort
Unstage changes:
git reset <file>
Unstage all changes:
git reset
Reset the working directory to the last commit:
git reset --hard
Reset to a specific commit (keeps changes in working directory):
git reset <commit-id>
Hard reset to a specific commit (discards all changes):
git reset --hard <commit-id>
Revert a specific commit:
git revert <commit-id>
Create a new tag:
git tag <tag-name>
Create an annotated tag:
git tag -a <tag-name> -m "Tag message"
List all tags:
git tag
Push a specific tag to a remote repository:
git push origin <tag-name>
Push all tags to a remote repository:
git push origin --tags
Delete a local tag:
git tag -d <tag-name>
Delete a remote tag:
git push origin --delete <tag-name>
Add these to your .gitconfig to create shortcuts for commonly used commands:
.gitconfig
[alias] st = status co = checkout ci = commit br = branch lg = log --oneline --graph --all amend = commit --amend
Cherry-pick a commit from another branch:
git cherry-pick <commit-id>
Squash multiple commits into one:
git rebase -i HEAD~n # Mark commits to be squashed
Clean untracked files and directories:
git clean -f -d
Check out a file from another branch without switching branches:
git checkout <branch-name> -- <file-path>
Install Poetry:
curl -sSL https://install.python-poetry.org | python3 -
Configure Poetry to create virtual environments inside the project directory:
poetry config virtualenvs.in-project true
View current Poetry configuration:
poetry config --list
Create a new Poetry project:
poetry new <project-name>
Initialize Poetry in an existing project:
poetry init
Install dependencies listed in pyproject.toml:
pyproject.toml
poetry install
Add a new dependency to the project:
poetry add <package-name>
Add a specific version of a dependency:
poetry add <package-name>@<version>
Add a development dependency:
poetry add --dev <package-name>
Remove a dependency from the project:
poetry remove <package-name>
Update all dependencies to the latest version:
poetry update
Update a specific dependency:
poetry update <package-name>
Create a new virtual environment:
poetry env use <python-version>
List all virtual environments managed by Poetry:
poetry env list
Remove a specific virtual environment:
poetry env remove <virtualenv-name>
Show all installed dependencies:
poetry show
Show details about a specific dependency:
poetry show <package-name>
Generate a requirements.txt file from pyproject.toml:
requirements.txt
poetry export -f requirements.txt --output requirements.txt
Lock dependencies (generate/update poetry.lock file):
poetry.lock
poetry lock
Run a script or command in the context of the project's virtual environment:
poetry run <command>
Open a shell within the project's virtual environment:
poetry shell
Build the project (create source and wheel distributions):
poetry build
Publish the package to a repository (e.g., PyPI):
poetry publish
Publish to a repository with credentials:
poetry publish --username <username> --password <password>
Run a custom script defined in pyproject.toml:
poetry run <script-name>
Install a Poetry plugin:
poetry self add <plugin-name>
List installed Poetry plugins:
poetry self show plugins
Set a global Poetry configuration value:
poetry config <key> <value> --global
Unset a global Poetry configuration value:
poetry config --unset <key> --global
List all configuration values:
Check for Poetry updates:
poetry self update
Get the current Poetry version:
poetry --version
Install Conda (via Miniconda or Anaconda):
# Install Miniconda (recommended for minimal installation) curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh # Install Anaconda (includes many scientific packages by default) curl -O https://repo.anaconda.com/archive/Anaconda3-latest-Linux-x86_64.sh bash Anaconda3-latest-Linux-x86_64.sh
Update Conda to the latest version:
conda update conda
Create a new environment:
conda create --name <env-name>
Create a new environment with specific Python version:
conda create --name <env-name> python=<version>
Create a new environment from an environment.yml file:
conda env create -f environment.yml
Activate an environment:
conda activate <env-name>
Deactivate the current environment:
conda deactivate
List all environments:
conda env list
Export an environment to an environment.yml file:
conda env export > environment.yml
Remove an environment:
conda env remove --name <env-name>
Install a package:
conda install <package-name>
Install a specific version of a package:
conda install <package-name>=<version>
Install packages from a specific channel:
conda install -c <channel-name> <package-name>
Update all packages in the current environment:
conda update --all
Update a specific package:
conda update <package-name>
Remove a package:
conda remove <package-name>
List all installed packages in the current environment:
conda list
Search for a package in the default or specific channel:
conda search <package-name>
Add a new channel to the Conda configuration:
conda config --add channels <channel-name>
Set the default environment path:
conda config --set envs_dirs <path>
List all Conda configuration settings:
conda config --show
Check for Conda updates:
Get the current Conda version:
conda --version
Clean up unused packages and caches:
conda clean --all
Verify the integrity of the Conda environment:
conda check
List package revisions in the current environment:
conda list --revisions
Restore the environment to a previous revision:
conda install --revision <revision-number>
Clone an existing environment:
conda create --name <new-env-name> --clone <existing-env-name>
Install Pytest:
pip install pytest
Verify the installation:
pytest --version
Run all tests in the current directory and subdirectories:
pytest
Run tests in a specific file:
pytest <test_file.py>
Run a specific test function within a file:
pytest <test_file.py>::<test_function>
Run tests with detailed output:
pytest -v
Automatically discover and run all tests:
Specify a custom test discovery pattern:
pytest --maxfail=3
Run tests with a specific marker:
pytest -m <marker_name>
Run tests that do not have a specific marker:
pytest -m "not <marker_name>"
Define a fixture in conftest.py or a test module:
conftest.py
import pytest @pytest.fixture def my_fixture(): return "fixture data"
Use a fixture in a test:
def test_with_fixture(my_fixture): assert my_fixture == "fixture data"
Parametrize a test function:
@pytest.mark.parametrize("input,expected", [(1, 2), (2, 3), (3, 4)]) def test_increment(input, expected): assert input + 1 == expected
Use standard Python assertions:
def test_example(): assert 1 + 1 == 2 assert "pytest" in "pytest is awesome"
Mark a test as expected to fail:
@pytest.mark.xfail def test_will_fail(): assert 0
Skip a test:
@pytest.mark.skip(reason="Not implemented yet") def test_not_implemented(): pass
Capture and test stdout/stderr output:
def test_output(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n"
Create a pytest.ini or tox.ini file for configuration:
pytest.ini
tox.ini
[pytest] addopts = -v testpaths = tests
List all installed plugins:
pytest --trace-config
Install a Pytest plugin:
pip install pytest-cov
Use a Pytest plugin (e.g., coverage):
pytest --cov=<package_name>
Install the coverage plugin:
Run tests with coverage:
pytest --cov=<source_directory>
Generate a coverage report:
pytest --cov=<source_directory> --cov-report=html
Run tests with a specific configuration file:
pytest -c <config_file>
Stop after the first failure:
pytest -x
Show the durations of the slowest tests:
pytest --durations=10
Enter the Python debugger on test failure:
pytest --pdb
Run tests with the debugger:
pytest --trace
Capture log messages:
import logging def test_logging(caplog): logging.warning("This is a warning") assert "This is a warning" in caplog.text
Name test files starting with test_ or ending with _test.py. Name test functions starting with test_.
test_
_test.py
Use multiple test directories:
pytest dir1 dir2
Run tests in parallel (requires pytest-xdist):
pip install pytest-xdist pytest -n 4
Ignore specific files or directories:
pytest --ignore=<path>
Select specific files or directories:
pytest <path>
Install Ruff:
pip install ruff
ruff --version
Lint all Python files in the current directory and subdirectories:
ruff .
Lint a specific file or directory:
ruff <path>
Lint and autofix issues:
ruff --fix <path>
Show detailed output (including codes and explanations):
ruff --show-source <path>
Create a pyproject.toml file for configuration:
[tool.ruff] line-length = 88 select = ["E", "W", "F"] ignore = ["E501", "W503"]
Specify a configuration file:
ruff --config <config_file> <path>
Ignore specific rules in a configuration file:
[tool.ruff] ignore = ["E501", "W503"]
Ignore specific rules in a file using comments:
# ruff: noqa: E501 def my_function(): pass
Ignore a specific line:
def my_function(): # noqa: E501 pass
Autofix issues in the code:
Autofix specific rules:
ruff --fix --select <rule> <path>
Show statistics of linting errors:
ruff --statistics <path>
Show a summary of linting errors:
ruff --summary <path>
Integrate Ruff with pre-commit: Create a .pre-commit-config.yaml file:
.pre-commit-config.yaml
repos: - repo: https://github.com/charliermarsh/ruff-pre-commit rev: v0.0.252 hooks: - id: ruff
Install pre-commit hooks:
pre-commit install
Lint only specific rules:
ruff --select E9,F63,F7,F82 <path>
Exclude specific rules from linting:
ruff --ignore F401 <path>
Exclude specific files or directories:
ruff --exclude <path>
Example with multiple exclusions:
ruff --exclude .git,__pycache__,build,dist <path>
Show only errors and warnings:
ruff --quiet <path>
Show verbose output:
ruff --verbose <path>
Enable caching to speed up linting:
ruff --cache-dir <cache_directory> <path>
Disable caching:
ruff --no-cache <path>
Run specific checks by specifying their codes:
ruff --select E101,E111 <path>
Run all checks except specified ones:
ruff --ignore E101,E111 <path>
Ignore files and directories in the configuration file:
[tool.ruff] exclude = ["build", "dist", ".git"]
Check for updates to Ruff:
pip list --outdated | grep ruff
Show help and available options:
ruff --help
Show Ruff version:
Install pre-commit:
pip install pre-commit
pre-commit --version
Initialize a pre-commit configuration in your repository:
pre-commit init
Create a .pre-commit-config.yaml file:
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.0.1 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml
Run all hooks on all files:
pre-commit run --all-files
Run hooks on changed files:
pre-commit run
Run specific hooks:
pre-commit run <hook-id>
Add a hook to .pre-commit-config.yaml:
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.0.1 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - repo: https://github.com/charliermarsh/ruff-pre-commit rev: v0.0.252 hooks: - id: ruff
Remove a hook by deleting its entry from .pre-commit-config.yaml.
Update hooks to their latest versions:
pre-commit autoupdate
Skip specific hooks during a run:
SKIP=<hook-id> pre-commit run
Temporarily disable pre-commit:
pre-commit uninstall
Re-enable pre-commit:
Manually install hooks:
pre-commit install-hooks
Show installed hooks:
pre-commit run --all-files --show-diff-on-failure
Run hooks on a specific file:
pre-commit run --files <file>
Run hooks on a range of commits:
pre-commit run --from-ref <start_ref> --to-ref <end_ref>
Ignore files in a .pre-commit-ignore file:
.pre-commit-ignore
# Ignore all Markdown files *.md # Ignore specific file path/to/specific_file.py
Define a custom hook in .pre-commit-config.yaml:
repos: - repo: local hooks: - id: custom-hook name: Custom Hook entry: ./path/to/script.sh language: script files: \.py$
Integrate pre-commit with CI/CD: Add the following to your CI configuration to run pre-commit hooks:
jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.x' - name: Install dependencies run: pip install pre-commit - name: Run pre-commit run: pre-commit run --all-files
Some common hooks you might find useful:
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.0.1 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-json - id: check-added-large-files - id: check-merge-conflict - repo: https://github.com/psf/black rev: 21.12b0 hooks: - id: black - repo: https://github.com/PyCQA/flake8 rev: 3.9.2 hooks: - id: flake8 - repo: https://github.com/charliermarsh/ruff-pre-commit rev: v0.0.252 hooks: - id: ruff
Check the status of pre-commit hooks:
pre-commit status
Manually clean up pre-commit caches:
pre-commit clean
Install Black:
pip install black
black --version
Format all Python files in the current directory and subdirectories:
black .
Format a specific file or directory:
black <path>
[tool.black] line-length = 88 target-version = ['py37', 'py38'] include = '\.pyi?$' exclude = ''' /( \.eggs| \.git| \.hg| \.mypy_cache| \.nox| \.tox| \.venv| _build| buck-out| build| dist )/ '''
Check if files would be reformatted without making changes:
black --check <path>
Show changes that would be made without making changes:
black --diff <path>
Force reformatting even if the file contains syntax errors:
black --fast <path>
Set the line length for code formatting:
black --line-length 120 <path>
Set the target Python versions for compatibility:
black --target-version py37 --target-version py38 <path>
black --exclude <pattern> <path>
Integrate Black with pre-commit: Create a .pre-commit-config.yaml file:
repos: - repo: https://github.com/psf/black rev: 21.12b0 hooks: - id: black language_version: python3.7
Run pre-commit hooks:
Install the Black formatter extension or add it to your settings.json:
"python.formatting.provider": "black", "editor.formatOnSave": true
Preferences
Tools
External Tools
-m black $FilePathRelativeToProjectRoot$
$ProjectFileDir$
Run Black in verbose mode:
black --verbose <path>
Exclude specific cells in Jupyter notebooks from formatting:
# black: skip def example(): pass
Add a .gitignore-style file named .blackignore to exclude files or directories from being formatted by Black:
.gitignore
.blackignore
# Exclude all .pyc files *.pyc # Exclude a specific directory path/to/dir/
Automatically run Black before each commit using a pre-commit hook:
echo '#!/bin/sh\nblack .' > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit
black --help
Limit the number of concurrent jobs:
black --workers 4 <path>
Skip formatting of specific lines or blocks in your code:
# fmt: off some_code_that_will_not_be_formatted() # fmt: on
How can I push my code on GitHub repository
This is the extension:
https://marketplace.visualstudio.com/items?itemName=assisrMatheus.sidebar-markdown-notes
This a good replacement of the Makefile. Let's use the Make file to really automate stuff...
Bellow the cheat sheets I have so far:
Git Commands Cheat Sheet
Initialization and Configuration
Initialize a new Git repository:
Clone an existing repository:
Set global username:
Set global email:
View configured username and email:
Status and Information
Check the status of the working directory and staging area:
✨Show the changes in the working directory:
Show the changes between the staging area and the latest commit:
Show the commit history:
Show a single-line log with graph:
Show detailed information about a specific commit:
Staging and Committing
Add a specific file to the staging area:
Add all changes in the current directory to the staging area:
Commit changes with a message:
Commit with a multi-line message:
Amend the last commit (don't do this if you've already pushed the commit):
Branching and Merging
Create a new branch:
✨List all branches:
Switch to a different branch:
✨Create a new branch and switch to it:
Merge a branch into the current branch:
✨Delete a branch locally:
✨Delete a branch remotely:
Remote Repositories
Add a remote repository:
List all remote repositories:
Remove a remote repository:
✨Fetch changes from a remote repository:
✨Pull changes from a remote repository and merge:
✨Push changes to a remote repository:
Force push changes to a remote repository (use with caution):
Stashing Changes
Stash current changes:
List stashed changes:
Apply the latest stash:
Apply a specific stash:
Drop the latest stash:
Drop a specific stash:
Apply and drop the latest stash:
Rebasing
Start an interactive rebase:
Continue a rebase after resolving conflicts:
Skip a commit during a rebase:
Abort a rebase:
Resetting and Reverting
Unstage changes:
Unstage all changes:
Reset the working directory to the last commit:
Reset to a specific commit (keeps changes in working directory):
Hard reset to a specific commit (discards all changes):
Revert a specific commit:
Tagging
Create a new tag:
Create an annotated tag:
List all tags:
Push a specific tag to a remote repository:
Push all tags to a remote repository:
Delete a local tag:
Delete a remote tag:
Git Aliases
Add these to your
.gitconfig
to create shortcuts for commonly used commands:Advanced Commands
Cherry-pick a commit from another branch:
Squash multiple commits into one:
Clean untracked files and directories:
Check out a file from another branch without switching branches:
Cheat sheet for Poetry commands
Installation and Configuration
Install Poetry:
Configure Poetry to create virtual environments inside the project directory:
View current Poetry configuration:
Project Initialization and Management
Create a new Poetry project:
Initialize Poetry in an existing project:
Install dependencies listed in
pyproject.toml
:Add a new dependency to the project:
Add a specific version of a dependency:
Add a development dependency:
Remove a dependency from the project:
Update all dependencies to the latest version:
Update a specific dependency:
Virtual Environments
Create a new virtual environment:
List all virtual environments managed by Poetry:
Remove a specific virtual environment:
Dependency Management
Show all installed dependencies:
Show details about a specific dependency:
Generate a
requirements.txt
file frompyproject.toml
:Lock dependencies (generate/update
poetry.lock
file):Running and Building
Run a script or command in the context of the project's virtual environment:
Open a shell within the project's virtual environment:
Build the project (create source and wheel distributions):
Publish the package to a repository (e.g., PyPI):
Publish to a repository with credentials:
Scripts and Plugins
Run a custom script defined in
pyproject.toml
:Install a Poetry plugin:
List installed Poetry plugins:
Configuration and Settings
Set a global Poetry configuration value:
Unset a global Poetry configuration value:
List all configuration values:
Miscellaneous
Check for Poetry updates:
Get the current Poetry version:
Cheat sheet for Conda commands
Installation and Configuration
Install Conda (via Miniconda or Anaconda):
Update Conda to the latest version:
Environment Management
Create a new environment:
Create a new environment with specific Python version:
Create a new environment from an environment.yml file:
Activate an environment:
Deactivate the current environment:
List all environments:
Export an environment to an environment.yml file:
Remove an environment:
Package Management
Install a package:
Install a specific version of a package:
Install packages from a specific channel:
Update all packages in the current environment:
Update a specific package:
Remove a package:
List all installed packages in the current environment:
Searching for Packages
Search for a package in the default or specific channel:
Conda Configuration
Add a new channel to the Conda configuration:
Set the default environment path:
List all Conda configuration settings:
Miscellaneous
Check for Conda updates:
Get the current Conda version:
Clean up unused packages and caches:
Verify the integrity of the Conda environment:
List package revisions in the current environment:
Restore the environment to a previous revision:
Environment Cloning
Clone an existing environment:
Cheat sheet for Pytest
Installation
Install Pytest:
Verify the installation:
Running Tests
Run all tests in the current directory and subdirectories:
Run tests in a specific file:
Run a specific test function within a file:
Run tests with detailed output:
Test Discovery
Automatically discover and run all tests:
Specify a custom test discovery pattern:
Markers and Fixtures
Run tests with a specific marker:
Run tests that do not have a specific marker:
Fixtures
Define a fixture in
conftest.py
or a test module:Use a fixture in a test:
Parametrized Tests
Parametrize a test function:
Assertions
Use standard Python assertions:
XFail and Skip
Mark a test as expected to fail:
Skip a test:
Capturing Output
Capture and test stdout/stderr output:
Configuration
Create a
pytest.ini
ortox.ini
file for configuration:Plugins
List all installed plugins:
Install a Pytest plugin:
Use a Pytest plugin (e.g., coverage):
Coverage
Install the coverage plugin:
Run tests with coverage:
Generate a coverage report:
Command Line Options
Run tests with a specific configuration file:
Stop after the first failure:
Show the durations of the slowest tests:
Debugging
Enter the Python debugger on test failure:
Run tests with the debugger:
Logging
Capture log messages:
Test Naming and Structuring
Name test files starting with
test_
or ending with_test.py
. Name test functions starting withtest_
.Advanced Usage
Use multiple test directories:
Run tests in parallel (requires pytest-xdist):
Ignoring and Selecting Tests
Ignore specific files or directories:
Select specific files or directories:
Cheat sheet for Ruff (Lint)
Installation
Install Ruff:
Verify the installation:
Basic Usage
Lint all Python files in the current directory and subdirectories:
Lint a specific file or directory:
Lint and autofix issues:
Show detailed output (including codes and explanations):
Configuration
Create a
pyproject.toml
file for configuration:Specify a configuration file:
Ignoring Rules
Ignore specific rules in a configuration file:
Ignore specific rules in a file using comments:
Ignore a specific line:
Autofixing Issues
Autofix issues in the code:
Autofix specific rules:
Advanced Usage
Show statistics of linting errors:
Show a summary of linting errors:
Integration with Other Tools
Integrate Ruff with pre-commit: Create a
.pre-commit-config.yaml
file:Install pre-commit hooks:
Selective Linting
Lint only specific rules:
Exclude specific rules from linting:
Excluding Files and Directories
Exclude specific files or directories:
Example with multiple exclusions:
Output Options
Show only errors and warnings:
Show verbose output:
Caching
Enable caching to speed up linting:
Disable caching:
Running Specific Checks
Run specific checks by specifying their codes:
Run all checks except specified ones:
Ignoring Files in Configuration
Ignore files and directories in the configuration file:
Checking for Updates
Check for updates to Ruff:
Miscellaneous
Show help and available options:
Show Ruff version:
Pre-commit hooks
Installation
Install pre-commit:
Verify the installation:
Basic Usage
Initialize a pre-commit configuration in your repository:
Create a
.pre-commit-config.yaml
file:Install pre-commit hooks:
Run all hooks on all files:
Run hooks on changed files:
Run specific hooks:
Managing Hooks
Add a hook to
.pre-commit-config.yaml
:Remove a hook by deleting its entry from
.pre-commit-config.yaml
.Update hooks to their latest versions:
Configuration Options
Skip specific hooks during a run:
Temporarily disable pre-commit:
Re-enable pre-commit:
Advanced Usage
Manually install hooks:
Show installed hooks:
Run hooks on a specific file:
Run hooks on a range of commits:
Ignoring Files
Ignore files in a
.pre-commit-ignore
file:Custom Hooks
Define a custom hook in
.pre-commit-config.yaml
:Integrations
Integrate pre-commit with CI/CD: Add the following to your CI configuration to run pre-commit hooks:
Frequently Used Hooks
Some common hooks you might find useful:
Miscellaneous
Check the status of pre-commit hooks:
Manually clean up pre-commit caches:
Black
Installation
Install Black:
Verify the installation:
Basic Usage
Format all Python files in the current directory and subdirectories:
Format a specific file or directory:
Configuration
Create a
pyproject.toml
file for configuration:Command Line Options
Check if files would be reformatted without making changes:
Show changes that would be made without making changes:
Force reformatting even if the file contains syntax errors:
Set the line length for code formatting:
Set the target Python versions for compatibility:
Exclude specific files or directories:
Integration with Other Tools
Integrate Black with pre-commit: Create a
.pre-commit-config.yaml
file:Install pre-commit hooks:
Run pre-commit hooks:
Using Black with Editors
VS Code
Install the Black formatter extension or add it to your settings.json:
PyCharm
Preferences
>Tools
>External Tools
.-m black $FilePathRelativeToProjectRoot$
$ProjectFileDir$
Advanced Usage
Run Black in verbose mode:
Exclude specific cells in Jupyter notebooks from formatting:
Ignoring Files
Add a
.gitignore
-style file named.blackignore
to exclude files or directories from being formatted by Black:Git Integration
Automatically run Black before each commit using a pre-commit hook:
Additional Options
Show help and available options:
Performance Options
Limit the number of concurrent jobs:
Skipping Formatting
Skip formatting of specific lines or blocks in your code: