### Initialize an existing project with hatch new --init Source: https://hatch.pypa.io/latest/intro Run inside the project directory to initialize an existing project. If a setup.py file is present, the command automatically migrates setuptools configuration; otherwise it interactively guides through setup. ```shell hatch new --init ``` -------------------------------- ### get_source_install_args Source: https://hatch.pypa.io/latest/plugins/environment/reference Method to get global installer flags for dependencies. ```APIDOC ## get_source_install_args(dependencies: Sequence[Dependency]) -> list[str] ### Description Returns global installer flags derived from the sources that apply to the given dependencies. Currently this surfaces every `IndexSource` as `--extra-index-url`, deduplicated and order-preserving. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters - **dependencies** (Sequence[Dependency]) - Required - The dependencies for which to collect installer flags. ### Request Example N/A ### Response #### Success Response - **list[str]** - The list of installer flags. #### Response Example N/A ``` -------------------------------- ### Verify Hatch installation with hatch --version Source: https://hatch.pypa.io/latest/install After installing Hatch, run this command to verify that the shell can find and run the `hatch` command in your `PATH`. The expected output is shown. ```shell $ hatch --version 1.18.1 ``` -------------------------------- ### Install a Python distribution with hatch python install Source: https://hatch.pypa.io/latest/tutorials/python/manage Installs the Python 3.12 distribution. Downloads it, unpacks it into a directory named '3.12' within the configured default directory, and adds the installation to the user PATH. Restart the shell for PATH changes to take effect. ```bash hatch python install 3.12 ``` -------------------------------- ### app_status_project_installation context manager Source: https://hatch.pypa.io/latest/plugins/environment/reference Context manager that shows installation status, using 'Installing project in development mode' when dev_mode is enabled, otherwise 'Installing project'. ```python @contextmanager def app_status_project_installation(self): """ See the [life cycle of environments](reference.md#life-cycle). """ if self.dev_mode: with self.app.status("Installing project in development mode"): yield else: with self.app.status("Installing project"): yield ``` -------------------------------- ### Enable UV installer in hatch.toml Source: https://hatch.pypa.io/latest/blog/2024/05/02/hatch-v1100 Set the installer option to uv in the hatch.toml configuration file to use UV for the default environment. ```TOML [envs.default] installer = "uv" ``` -------------------------------- ### hatch python install all Source: https://hatch.pypa.io/latest/cli/reference Installs all compatible Python distributions. ```shell hatch python install all ``` -------------------------------- ### Install Hatch via GitHub Actions Source: https://hatch.pypa.io/latest/install Use the pypa/hatch action with the install target to install Hatch in a GitHub Actions workflow. Refer to the official action for more information. ```yaml - name: Install Hatch uses: pypa/hatch@install ``` -------------------------------- ### hatch python install usage Source: https://hatch.pypa.io/latest/cli/reference Shows the usage of the hatch python install subcommand. ```shell hatch python install [OPTIONS] NAMES... ``` -------------------------------- ### Pre-install commands configuration (hatch.toml) Source: https://hatch.pypa.io/latest/config/environment/overview Defines commands to run immediately before the environment installs the project, using the [envs.] table in hatch.toml. ```TOML [envs.] pre-install-commands = [ "...", ] ``` -------------------------------- ### Confirm project installation with pip show Source: https://hatch.pypa.io/latest/environment Confirms the project is installed in the active environment. ```shell (hatch-demo) $ pip show hatch-demo Name: hatch-demo Version: 0.0.1 ... ``` -------------------------------- ### Post-install commands configuration (hatch.toml) Source: https://hatch.pypa.io/latest/config/environment/overview Defines commands to run immediately after environments install your project, using the [envs.] table. ```TOML [envs.] post-install-commands = [ "...", ] ``` -------------------------------- ### Enable UV installer in pyproject.toml Source: https://hatch.pypa.io/latest/blog/2024/05/02/hatch-v1100 Set the installer option to uv in the default environment to use UV in place of virtualenv and pip for virtual environment creation and dependency management. This often results in a significant performance benefit. ```TOML [tool.hatch.envs.default] installer = "uv" ``` -------------------------------- ### Pre-install commands configuration (pyproject.toml) Source: https://hatch.pypa.io/latest/config/environment/overview Defines commands to run immediately before the environment installs the project. Configured under [tool.hatch.envs.] in pyproject.toml. ```TOML [tool.hatch.envs.] pre-install-commands = [ "...", ] ``` -------------------------------- ### get_source_install_args method Source: https://hatch.pypa.io/latest/plugins/environment/reference Returns global installer flags derived from sources, surfacing every IndexSource as --extra-index-url, deduplicated and order-preserving. ```python def get_source_install_args(self, dependencies: Sequence[Dependency]) -> list[str]: """ Returns global installer flags derived from the [sources](../../config/environment/sources.md) that apply to the given dependencies. Currently this surfaces every `IndexSource` as `--extra-index-url`, deduplicated and order-preserving. """ from hatch.project.sources import collect_global_install_args return collect_global_install_args(dependencies, self.sources) ``` -------------------------------- ### Install multiple Python distributions with hatch python install Source: https://hatch.pypa.io/latest/tutorials/python/manage Installs multiple Python distributions at once by providing multiple distribution names. The update and remove commands also support this functionality. ```bash hatch python install 3.12 3.11 pypy3.10 ``` -------------------------------- ### Post-install commands configuration (pyproject.toml) Source: https://hatch.pypa.io/latest/config/environment/overview Defines commands to run immediately after environments install your project, using the [tool.hatch.envs.] table. ```TOML [tool.hatch.envs.] post-install-commands = [ "...", ] ``` -------------------------------- ### List Python distributions with hatch python show Source: https://hatch.pypa.io/latest/tutorials/python/manage Shows all available and installed Python distributions. The output includes a table of installed distributions and a table of available ones with their versions. ```bash $ hatch python show Installed ┏━━━━━━┳━━━━━━━━━┓ ┃ Name ┃ Version ┃ ┡━━━━━━╇━━━━━━━━━┩ │ 3.12 │ 3.12.7 │ └──────┴─────────┘ Available ┏━━━━━━━━━━┳━━━━━━━━━┓ ┃ Name ┃ Version ┃ ┡━━━━━━━━━━╇━━━━━━━━━┩ │ 3.7 │ 3.7.9 │ ├──────────┼─────────┤ │ 3.8 │ 3.8.20 │ ├──────────┼─────────┤ │ 3.9 │ 3.9.20 │ ├──────────┼─────────┤ │ 3.10 │ 3.10.15 │ ├──────────┼─────────┤ │ 3.11 │ 3.11.10 │ ├──────────┼─────────┤ │ 3.13 │ 3.13.0 │ ├──────────┼─────────┤ │ pypy2.7 │ 7.3.15 │ ├──────────┼─────────┤ │ pypy3.9 │ 7.3.15 │ ├──────────┼─────────┤ │ pypy3.10 │ 7.3.15 │ └──────────┴─────────┘ ``` -------------------------------- ### Configure version scheme in hatch.toml Source: https://hatch.pypa.io/latest/plugins/version-scheme/reference Example configuration for the version scheme in hatch.toml, showing the [version] table. ```toml [version] ``` -------------------------------- ### sync_dependencies abstract method Source: https://hatch.pypa.io/latest/plugins/environment/reference Required method that installs the dependencies in the environment. ```python @abstractmethod def sync_dependencies(self): """ :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should install the dependencies in the environment. """ ``` -------------------------------- ### Custom builder example (hatch_build.py) Source: https://hatch.pypa.io/latest/plugins/builder/custom Example of a custom builder class that inherits from BuilderInterface. If multiple subclasses are found, define a get_builder function that returns the desired builder. Any defined PLUGIN_NAME is ignored and will always be 'custom'. ```python from hatchling.builders.plugin.interface import BuilderInterface class CustomBuilder(BuilderInterface): ... ``` -------------------------------- ### Define CLI entry point in pyproject.toml Source: https://hatch.pypa.io/latest/config/metadata Defines a CLI script that will be available on PATH after installation. ```TOML [project.scripts] cli-name = "pkg.subpkg:func" ``` -------------------------------- ### Define GUI entry point in pyproject.toml Source: https://hatch.pypa.io/latest/config/metadata Defines a GUI script, handled specially on Windows to start without a console. ```TOML [project.gui-scripts] gui-name = "pkg.subpkg:func" ``` -------------------------------- ### Expanded environments for hatch-test matrix Source: https://hatch.pypa.io/latest/tutorials/testing/overview Lists the environments that result from expanding the example matrix configuration. ```text hatch-test.py3.12 hatch-test.py3.11 hatch-test.py3.11-foo hatch-test.py3.11-bar ``` -------------------------------- ### Set virtual environment directory to home Source: https://hatch.pypa.io/latest/config/hatch Example of storing virtual environments in a `.virtualenvs` directory within the home directory. ```TOML [dirs.env] virtual = "~/.virtualenvs" ``` -------------------------------- ### Configure version scheme in pyproject.toml Source: https://hatch.pypa.io/latest/plugins/version-scheme/reference Example configuration for the version scheme in pyproject.toml, showing the [tool.hatch.version] table. ```toml [tool.hatch.version] ``` -------------------------------- ### Setuptools vs Hatch build system migration Source: https://hatch.pypa.io/latest/meta/faq Shows the migration path from Setuptools to Hatch for the build system. The source lists setup.py and MANIFEST.in as the files involved in the migration, but no code is displayed for them. ```text setup.py MANIFEST.in ``` -------------------------------- ### Configure default environment dependencies in pyproject.toml Source: https://hatch.pypa.io/latest/tutorials/environment/basic-usage Adds the `tool.hatch.envs.default` table to `pyproject.toml` to customize tools installed into the `default` environment. The example adds the dependencies `pydantic` and `numpy`. ```TOML [tool.hatch.envs.default] dependencies = [ "pydantic", "numpy", ] ``` -------------------------------- ### Name overrides with regex matching in pyproject.toml and hatch.toml Source: https://hatch.pypa.io/latest/config/environment/advanced Uses the name source to match generated environment names with a regular expression. The example sets an environment variable for versions starting with 0. ```toml [tool.hatch.envs.test.overrides] name."^0".env-vars = "TESTING_UNSTABLE=true" [[tool.hatch.envs.test.matrix]] version = ["0.1.0", "0.2.0", "1.0.0"] ``` ```toml [envs.test.overrides] name."^0".env-vars = "TESTING_UNSTABLE=true" [[envs.test.matrix]] version = ["0.1.0", "0.2.0", "1.0.0"] ``` -------------------------------- ### Hatch environment context formatting example Source: https://hatch.pypa.io/latest/config/context Shows the same dependency configuration using Hatch's native TOML syntax. Use this when configuring Hatch environments directly in hatch.toml. ```TOML [envs.test] dependencies = [ "example-project @ {root:parent:parent:uri}/example-project", ] ``` -------------------------------- ### Disable UV in script environment (script.py) Source: https://hatch.pypa.io/latest/how-to/run/python-scripts Example of adding a `[tool.hatch]` table to the script's metadata block to control the environment. Here, `installer = "pip"` disables UV, which is enabled by default for scripts. ```python # /// script # ... # [tool.hatch] # installer = "pip" # /// ``` -------------------------------- ### Create a new project with hatch new Source: https://hatch.pypa.io/latest/intro Run this command to create a new project named 'Hatch Demo'. It generates a standard project structure in the current working directory. ```bash hatch new "Hatch Demo" ``` -------------------------------- ### __enter__ Source: https://hatch.pypa.io/latest/plugins/environment/reference Enter the context manager. ```APIDOC ## __enter__() ### Description Enters the context manager by activating the environment. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **self** - The environment instance. #### Response Example N/A ``` -------------------------------- ### Install a Python distribution privately with --private flag Source: https://hatch.pypa.io/latest/tutorials/python/manage Installs a Python distribution without adding it to the user PATH. When combined with the directory option, this can be used to create private, isolated installations. ```bash hatch python install 3.12 --private ``` -------------------------------- ### View environments with `hatch env show` Source: https://hatch.pypa.io/latest/tutorials/environment/basic-usage Displays all currently created environments and their dependencies in a table. The output may have more columns depending on your environment configuration. ```text $ hatch env show Standalone ┏━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━┓ ┃ Name ┃ Type ┃ Dependencies ┃ ┡━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━┩ │ default │ virtual │ │ ├─────────┼─────────┼──────────────┤ │ test │ virtual │ pytest │ │ │ │ pytest-cov │ └─────────┴─────────┴──────────────┘ ``` -------------------------------- ### Environment preparation logic in src/hatch/project/core.py Source: https://hatch.pypa.io/latest/plugins/environment/reference Life cycle logic run whenever an environment is used. Creates the environment if it does not exist, resets metadata, and runs pre-install commands when configured. ```python def prepare_environment(self, environment: EnvironmentInterface, *, keep_env: bool): if not environment.exists(): with self.managed_environment(environment, keep_env=keep_env): self.env_metadata.reset(environment) with environment.app_status_creation(): environment.create() if not environment.skip_install: if environment.pre_install_commands: with environment.app_status_pre_installation(): self.app.run_shell_commands( ExecutionContext( environment, shell_commands=environment.pre_install_commands, source= ``` -------------------------------- ### Run script with hatch run (command and output) Source: https://hatch.pypa.io/latest/how-to/run/python-scripts Command to run the script directly with `hatch run /path/to/script.py`. The output shows the environment creation and dependency syncing, followed by the pretty-printed list of the first 10 PEPs. The informational text is only shown on the first run. ```bash $ hatch run /path/to/script.py Creating environment: SyB4bPbL Checking dependencies Syncing dependencies [ │ ('1', 'PEP Purpose and Guidelines'), │ ('2', 'Procedure for Adding New Modules'), │ ('3', 'Guidelines for Handling Bug Reports'), │ ('4', 'Deprecation of Standard Modules'), │ ('5', 'Guidelines for Language Evolution'), │ ('6', 'Bug Fix Releases'), │ ('7', 'Style Guide for C Code'), │ ('8', 'Style Guide for Python Code'), │ ('9', 'Sample Plaintext PEP Template'), │ ('10', 'Voting Guidelines') ] ``` -------------------------------- ### Set Python installations directory Source: https://hatch.pypa.io/latest/config/hatch Configures the directory where specific versions of Python are installed. The special value `isolated` (default) maps to `/pythons`. ```TOML [dirs] python = "..." ``` -------------------------------- ### install_project_dev_mode() abstract method Source: https://hatch.pypa.io/latest/plugins/environment/reference Required abstract method that installs the project in the environment so the environment always reflects the current state of the project. Source code is in src/hatch/env/plugin/interface.py. ```python @abstractmethod def install_project_dev_mode(self): """ :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should install the project in the environment such that the environment always reflects the current state of the project. """ ``` -------------------------------- ### Configure dev-mode-dirs in hatch.toml Source: https://hatch.pypa.io/latest/config/build Overrides automatic detection of directories added to Python's search path for dev mode environment installations or editable installs. ```TOML [build] dev-mode-dirs = ["."] ``` -------------------------------- ### Download Hatch installer with curl Source: https://hatch.pypa.io/latest/install Downloads the macOS installer package using curl. The `-o` option specifies the output file name `hatch-universal.pkg` in the current directory. ```shell curl -Lo hatch-universal.pkg https://github.com/pypa/hatch/releases/latest/download/hatch-universal.pkg ``` -------------------------------- ### Show environments with `hatch env show --ascii` Source: https://hatch.pypa.io/latest/environment Displays the standalone and matrix environments generated from the matrix configuration. The output shows the environment names and dependencies. ```text $ hatch env show --ascii Standalone +---------+---------+ | Name | Type | +=========+=========+ | default | virtual | +---------+---------+ Matrices +------+---------+----------------------+--------------+ | Name | Type | Envs | Dependencies | +======+=========+======================+==============+ | test | virtual | test.py3.10-42 | pytest | | | | test.py3.10-3.14 | | | | | test.py3.11-42 | | | | | test.py3.11-3.14 | | | | | test.py3.11-9000-foo | | | | | test.py3.11-9000-bar | | | | | test.py3.12-9000-foo | | | | | test.py3.12-9000-bar | | +------+---------+----------------------+--------------+ ``` -------------------------------- ### Run pytest in the test environment Source: https://hatch.pypa.io/latest/tutorials/environment/basic-usage Runs `pytest` inside the `test` environment defined earlier. The first run creates the environment, installs the project in dev mode, and installs the environment's dependencies. ```text $ hatch run test:pytest ``` -------------------------------- ### Equivalent configuration for packages option in hatch.toml Source: https://hatch.pypa.io/latest/config/build Shows that `packages = ["src/foo"]` for the wheel target is equivalent to setting `only-include` and `sources` as shown. ```toml [build.targets.wheel] only-include = ["src/foo"] sources = ["src"] ``` -------------------------------- ### Configure dev-mode-dirs in pyproject.toml Source: https://hatch.pypa.io/latest/config/build Overrides automatic detection of directories added to Python's search path for dev mode environment installations or editable installs. Set to ["."] to add the project root. ```TOML [tool.hatch.build] dev-mode-dirs = ["."] ``` -------------------------------- ### Configure UV to use private indices with PyPI fallback (hatch.toml) Source: https://hatch.pypa.io/latest/how-to/environment/dependency-resolution Same UV configuration as the pyproject.toml example but placed in hatch.toml under [envs.default.env-vars]. Uses UV_INDEX and UV_DEFAULT_INDEX with token authentication and PyPI as the default index. ```TOML [envs.default.env-vars] UV_INDEX = "https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups//-/packages/pypi/simple/ https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups//-/packages/pypi/simple/" UV_DEFAULT_INDEX = "https://pypi.org/simple/" ``` -------------------------------- ### Path modifier example in pyproject.toml Source: https://hatch.pypa.io/latest/config/context Uses the root path with chained parent modifiers and the uri modifier to reference an example project dependency. The parent modifier can be chained and combined with uri or real, with the latter placed at the end. ```TOML [tool.hatch.envs.test] dependencies = [ "example-project @ {root:parent:parent:uri}/example-project", ] ``` -------------------------------- ### Custom build hook implementation example Source: https://hatch.pypa.io/latest/plugins/build-hook/custom Example implementation of a custom build hook class that inherits from BuildHookInterface. The class can be customized as needed, and if multiple subclasses are found, a get_build_hook function must be defined to return the desired hook. ```python from hatchling.builders.hooks.plugin.interface import BuildHookInterface class CustomBuildHook(BuildHookInterface): ... ``` -------------------------------- ### Create environment with hatch env create Source: https://hatch.pypa.io/latest/environment Creates the default environment for the project. The output shows the environment being created, the project installed in development mode, and dependencies synced. ```shell $ hatch env create Creating environment: default Installing project in development mode Syncing dependencies ``` -------------------------------- ### get_context Source: https://hatch.pypa.io/latest/plugins/environment/reference Method to get an environment context formatter. ```APIDOC ## get_context() -> EnvironmentContextFormatter ### Description Returns a subclass of `EnvironmentContextFormatter`. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **EnvironmentContextFormatter** - A formatter for environment context. #### Response Example N/A ``` -------------------------------- ### get_env_var_option Source: https://hatch.pypa.io/latest/plugins/environment/reference Method to get an environment variable option. ```APIDOC ## get_env_var_option(option: str) -> str ### Description Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE__