diff --git a/dev/build/index.html b/dev/build/index.html index ea7d979f9..61e5965c0 100644 --- a/dev/build/index.html +++ b/dev/build/index.html @@ -38,4 +38,4 @@ [wheel] Building `wheel` version `standard` dist/hatch_demo-1rc0-py3-none-any.whl -

Packaging ecosystem

Hatch complies with modern Python packaging specs and therefore your projects can be used by other tools with Hatch serving as just the build backend.

So you could use tox as an alternative to Hatch's environment management, or cibuildwheel to distribute packages for every platform, and they both will transparently use Hatch without any extra modification.

\ No newline at end of file +

Packaging ecosystem

Hatch complies with modern Python packaging specs and therefore your projects can be used by other tools with Hatch serving as just the build backend.

So you could use tox as an alternative to Hatch's environment management, or cibuildwheel to distribute packages for every platform, and they both will transparently use Hatch without any extra modification.

\ No newline at end of file diff --git a/dev/config/build/index.html b/dev/config/build/index.html index 20e5c0836..fcb7f1d70 100644 --- a/dev/config/build/index.html +++ b/dev/config/build/index.html @@ -170,4 +170,4 @@ enable-by-default = false
[build.hooks.<HOOK_NAME>]
 enable-by-default = false
-

Environment variables

Variable Default Description
HATCH_BUILD_CLEAN false Whether or not existing artifacts should first be removed
HATCH_BUILD_CLEAN_HOOKS_AFTER false Whether or not build hook artifacts should be removed after each build
HATCH_BUILD_HOOKS_ONLY false Whether or not to only execute build hooks
HATCH_BUILD_NO_HOOKS false Whether or not to disable all build hooks; this takes precedence over other options
HATCH_BUILD_HOOKS_ENABLE false Whether or not to enable all build hooks
HATCH_BUILD_HOOK_ENABLE_<HOOK_NAME> false Whether or not to enable the build hook named <HOOK_NAME>
HATCH_BUILD_LOCATION dist The location with which to build the targets; only used by the build command
\ No newline at end of file +

Environment variables

Variable Default Description
HATCH_BUILD_CLEAN false Whether or not existing artifacts should first be removed
HATCH_BUILD_CLEAN_HOOKS_AFTER false Whether or not build hook artifacts should be removed after each build
HATCH_BUILD_HOOKS_ONLY false Whether or not to only execute build hooks
HATCH_BUILD_NO_HOOKS false Whether or not to disable all build hooks; this takes precedence over other options
HATCH_BUILD_HOOKS_ENABLE false Whether or not to enable all build hooks
HATCH_BUILD_HOOK_ENABLE_<HOOK_NAME> false Whether or not to enable the build hook named <HOOK_NAME>
HATCH_BUILD_LOCATION dist The location with which to build the targets; only used by the build command
\ No newline at end of file diff --git a/dev/config/context/index.html b/dev/config/context/index.html index 2834d4495..388a2ae54 100644 --- a/dev/config/context/index.html +++ b/dev/config/context/index.html @@ -13,4 +13,4 @@ display = "echo {env:FOO:{env:BAR:{home}}}"
[envs.test.scripts]
 display = "echo {env:FOO:{env:BAR:{home}}}"
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/config/dependency/index.html b/dev/config/dependency/index.html index 1e1979a0b..8cabd9f60 100644 --- a/dev/config/dependency/index.html +++ b/dev/config/dependency/index.html @@ -56,4 +56,4 @@ pytorch @ https://download.pytorch.org/whl/cu102/torch-1.10.0%2Bcu102-cp39-cp39-linux_x86_64.whl

An expected hash value may be specified by appending a #<HASH_ALGORITHM>=<EXPECTED_HASH> component:

requests @ https://github.com/psf/requests/archive/refs/tags/v2.26.0.zip#sha256=eb729a757f01c10546ebd179ae2aec852dd0d7f8ada2328ccf4558909d859985
 

If the hash differs from the expected hash, the installation will fail.

It is recommended that only hashes which are unconditionally provided by the latest version of the standard library's hashlib module be used for hashes. As of Python 3.10, that list consists of:

Complex syntax

The following is an example that uses features and environment markers:

pkg[feature1,feature2] @ <REFERENCE> ; python_version < "3.7"
-

Note that the space before the semicolon is required.

\ No newline at end of file +

Note that the space before the semicolon is required.

\ No newline at end of file diff --git a/dev/config/environment/advanced/index.html b/dev/config/environment/advanced/index.html index 99e23ce5c..cecaaa325 100644 --- a/dev/config/environment/advanced/index.html +++ b/dev/config/environment/advanced/index.html @@ -112,13 +112,13 @@ matrix.version.env-vars = "PRODUCT_VERSION" matrix.auth.features = [ { value = "oauth", if = ["oauth2"] }, - { value = "kerberos", if = ["krb5"] }, + { value = "kerberos", if = ["kerberos"] }, ] [[tool.hatch.envs.test.matrix]] python = ["2.7", "3.8"] version = ["legacy", "latest"] -auth = ["oauth2", "krb5", "noauth"] +auth = ["oauth2", "kerberos", "noauth"]
[envs.test.overrides]
 matrix.version.env-vars = "PRODUCT_VERSION"
 matrix.auth.features = [
@@ -234,4 +234,4 @@
 
 [[envs.test.matrix]]
 version = ["42", "3.14"]
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/config/environment/overview/index.html b/dev/config/environment/overview/index.html index 12de5f102..020c3b344 100644 --- a/dev/config/environment/overview/index.html +++ b/dev/config/environment/overview/index.html @@ -212,4 +212,4 @@ description = """ Lorem ipsum ... """ -

Type

An environment's type determines which environment plugin will be used for management. The only built-in environment type is virtual, which uses virtual Python environments.

\ No newline at end of file +

Type

An environment's type determines which environment plugin will be used for management. The only built-in environment type is virtual, which uses virtual Python environments.

\ No newline at end of file diff --git a/dev/config/hatch/index.html b/dev/config/hatch/index.html index efcb2cddf..f1dbcd551 100644 --- a/dev/config/hatch/index.html +++ b/dev/config/hatch/index.html @@ -47,4 +47,4 @@ ...

Cross-platform terminal capabilities are provided by Rich.

Output levels

The levels of output are as follows. Note that the verbosity indicates the minimum level at which the output is displayed.

Level Default Verbosity Description
debug bold 1 - 3 Messages that are not useful for most user experiences
error bold red -2 Messages indicating some unrecoverable error
info bold 0 Messages conveying basic information
success bold cyan 0 Messages indicating some positive outcome
waiting bold magenta 0 Messages shown before potentially time consuming operations
warning bold yellow -1 Messages conveying important information

See the documentation and color reference for guidance on valid values.

Spinner

You can select the sequence used for waiting animations with the spinner option.

[terminal.styles]
 spinner = "..."
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/config/metadata/index.html b/dev/config/metadata/index.html index af53f061f..3de820f6a 100644 --- a/dev/config/metadata/index.html +++ b/dev/config/metadata/index.html @@ -102,4 +102,4 @@ allow-ambiguous-features = true
[metadata]
 allow-ambiguous-features = true
-

Deprecated

This option temporarily exists to provide better interoperability with tools that do not yet support PEP 685 and will be removed in the first minor release after Jan 1, 2024.

\ No newline at end of file +

Deprecated

This option temporarily exists to provide better interoperability with tools that do not yet support PEP 685 and will be removed in the first minor release after Jan 1, 2024.

\ No newline at end of file diff --git a/dev/config/project-templates/index.html b/dev/config/project-templates/index.html index e9ecb6e28..deaf2df79 100644 --- a/dev/config/project-templates/index.html +++ b/dev/config/project-templates/index.html @@ -23,4 +23,4 @@ ci = false

src layout

See this blog post.

[template.plugins.default]
 src-layout = true
-

Feature flags

Command line interface

The --cli flag adds a CLI backed by Click that can also be invoked with python -m <PKG_NAME>.

\ No newline at end of file +

Feature flags

Command line interface

The --cli flag adds a CLI backed by Click that can also be invoked with python -m <PKG_NAME>.

\ No newline at end of file diff --git a/dev/environment/index.html b/dev/environment/index.html index d366faf80..c373928da 100644 --- a/dev/environment/index.html +++ b/dev/environment/index.html @@ -97,4 +97,4 @@ | | | test.py3.9-9000-foo | | | | | test.py3.9-9000-bar | | +------+---------+---------------------+--------------+ -

Removal

You can remove a single environment or environment matrix by using the env remove command or all of a project's environments by using the env prune command.

\ No newline at end of file +

Removal

You can remove a single environment or environment matrix by using the env remove command or all of a project's environments by using the env prune command.

\ No newline at end of file diff --git a/dev/how-to/environment/package-indices/index.html b/dev/how-to/environment/package-indices/index.html index da065376e..8c896efd1 100644 --- a/dev/how-to/environment/package-indices/index.html +++ b/dev/how-to/environment/package-indices/index.html @@ -15,4 +15,4 @@
[envs.default.env-vars]
 PIP_INDEX_URL = "https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group1_path>/-/packages/pypi/simple/"
 PIP_EXTRA_INDEX_URL = "https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group2_path>/-/packages/pypi/simple/ https://pypi.org/simple/"
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/intro/index.html b/dev/intro/index.html index f0308e198..7694721af 100644 --- a/dev/intro/index.html +++ b/dev/intro/index.html @@ -43,4 +43,4 @@
option = "..."
 table1.option = "..."
 table2.option = "..."
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/meta/faq/index.html b/dev/meta/faq/index.html index 4aec7d32c..f17aef8c5 100644 --- a/dev/meta/faq/index.html +++ b/dev/meta/faq/index.html @@ -126,54 +126,54 @@ 9000: PRODUCT_VERSION=9000 {foo,bar}: EXPERIMENTAL=true

Invocation:

hatch run test
-
[envs.default]
+
[tool.hatch.envs.default]
 dependencies = [
   "coverage[toml]",
   "pytest",
   "pytest-cov",
 ]
 
-[envs.default.scripts]
+[tool.hatch.envs.default.scripts]
 test = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'
 
-[envs.default.overrides]
+[tool.hatch.envs.default.overrides]
 matrix.version.env-vars = "PRODUCT_VERSION"
 matrix.features.env-vars = "EXPERIMENTAL=true"
 matrix.features.dependencies = [
   { value = "cryptography", if = ["foo"] },
 ]
 
-[[envs.default.matrix]]
+[[tool.hatch.envs.default.matrix]]
 python = ["2.7", "3.8"]
 version = ["42", "3.14"]
 
-[[envs.default.matrix]]
+[[tool.hatch.envs.default.matrix]]
 python = ["3.8", "3.9"]
 version = ["9000"]
 features = ["foo", "bar"]
-
[tool.hatch.envs.default]
+
[envs.default]
 dependencies = [
   "coverage[toml]",
   "pytest",
   "pytest-cov",
 ]
 
-[tool.hatch.envs.default.scripts]
+[envs.default.scripts]
 test = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'
 
-[tool.hatch.envs.default.overrides]
+[envs.default.overrides]
 matrix.version.env-vars = "PRODUCT_VERSION"
 matrix.features.env-vars = "EXPERIMENTAL=true"
 matrix.features.dependencies = [
   { value = "cryptography", if = ["foo"] },
 ]
 
-[[tool.hatch.envs.default.matrix]]
+[[envs.default.matrix]]
 python = ["2.7", "3.8"]
 version = ["42", "3.14"]
 
-[[tool.hatch.envs.default.matrix]]
+[[envs.default.matrix]]
 python = ["3.8", "3.9"]
 version = ["9000"]
 features = ["foo", "bar"]
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/next-steps/index.html b/dev/next-steps/index.html index 3f7abc333..0bf145c67 100644 --- a/dev/next-steps/index.html +++ b/dev/next-steps/index.html @@ -13,4 +13,4 @@
.. image:: https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg
    :alt: Hatch project
    :target: https://github.com/pypa/hatch
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/plugins/about/index.html b/dev/plugins/about/index.html index fbdd8cc37..a46591efe 100644 --- a/dev/plugins/about/index.html +++ b/dev/plugins/about/index.html @@ -31,4 +31,4 @@ "Framework :: Hatch", ... ] -

Types

Hatchling

These are all involved in building projects and therefore any defined dependencies are automatically installed in each build environment.

Hatch

These must be installed in the same environment as Hatch itself.

\ No newline at end of file +

Types

Hatchling

These are all involved in building projects and therefore any defined dependencies are automatically installed in each build environment.

Hatch

These must be installed in the same environment as Hatch itself.

\ No newline at end of file diff --git a/dev/plugins/build-hook/custom/index.html b/dev/plugins/build-hook/custom/index.html index c603e16df..05268165e 100644 --- a/dev/plugins/build-hook/custom/index.html +++ b/dev/plugins/build-hook/custom/index.html @@ -18,4 +18,4 @@ class CustomBuildHook(BuildHookInterface): ... -

If multiple subclasses are found, you must define a function named get_build_hook that returns the desired build hook.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

\ No newline at end of file +

If multiple subclasses are found, you must define a function named get_build_hook that returns the desired build hook.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

\ No newline at end of file diff --git a/dev/plugins/build-hook/reference/index.html b/dev/plugins/build-hook/reference/index.html index ca1e8cc7c..5594f212d 100644 --- a/dev/plugins/build-hook/reference/index.html +++ b/dev/plugins/build-hook/reference/index.html @@ -29,160 +29,147 @@ """ Example usage: - === ":octicons-file-code-16: plugin.py" - - ```python - from hatchling.builders.hooks.plugin.interface import BuildHookInterface - - - class SpecialBuildHook(BuildHookInterface): - PLUGIN_NAME = 'special' - ... - ``` - - === ":octicons-file-code-16: hooks.py" - - ```python - from hatchling.plugin import hookimpl - - from .plugin import SpecialBuildHook - - - @hookimpl - def hatch_register_build_hook(): - return SpecialBuildHook - ``` - """ - - PLUGIN_NAME = '' - """The name used for selection.""" - - def __init__( - self, - root: str, - config: dict[str, Any], - build_config: BuilderConfigBound, - metadata: ProjectMetadata, - directory: str, - target_name: str, - app: Application | None = None, - ) -> None: - self.__root = root - self.__config = config - self.__build_config = build_config - self.__metadata = metadata - self.__directory = directory - self.__target_name = target_name - self.__app = app - - @property - def app(self) -> Application: - """ - An instance of [Application](../utilities.md#hatchling.bridge.app.Application). - """ - if self.__app is None: - from hatchling.bridge.app import Application + ```python tab="plugin.py" + from hatchling.builders.hooks.plugin.interface import BuildHookInterface + + + class SpecialBuildHook(BuildHookInterface): + PLUGIN_NAME = 'special' + ... + ``` + + ```python tab="hooks.py" + from hatchling.plugin import hookimpl + + from .plugin import SpecialBuildHook + + + @hookimpl + def hatch_register_build_hook(): + return SpecialBuildHook + ``` + """ + + PLUGIN_NAME = '' + """The name used for selection.""" + + def __init__( + self, + root: str, + config: dict[str, Any], + build_config: BuilderConfigBound, + metadata: ProjectMetadata, + directory: str, + target_name: str, + app: Application | None = None, + ) -> None: + self.__root = root + self.__config = config + self.__build_config = build_config + self.__metadata = metadata + self.__directory = directory + self.__target_name = target_name + self.__app = app + + @property + def app(self) -> Application: + """ + An instance of [Application](../utilities.md#hatchling.bridge.app.Application). + """ + if self.__app is None: + from hatchling.bridge.app import Application + + self.__app = cast(Application, Application().get_safe_application()) + + return self.__app - self.__app = cast(Application, Application().get_safe_application()) - - return self.__app - - @property - def root(self) -> str: - """ - The root of the project tree. - """ - return self.__root - - @property - def config(self) -> dict[str, Any]: - """ - The cumulative hook configuration. - - === ":octicons-file-code-16: pyproject.toml" - - ```toml - [tool.hatch.build.hooks.<PLUGIN_NAME>] - [tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>] - ``` - - === ":octicons-file-code-16: hatch.toml" - - ```toml - [build.hooks.<PLUGIN_NAME>] - [build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>] - ``` - """ - return self.__config - - @property - def metadata(self) -> ProjectMetadata: - # Undocumented for now - return self.__metadata - - @property - def build_config(self) -> BuilderConfigBound: - """ - An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig). - """ - return self.__build_config - - @property - def directory(self) -> str: + @property + def root(self) -> str: + """ + The root of the project tree. + """ + return self.__root + + @property + def config(self) -> dict[str, Any]: + """ + The cumulative hook configuration. + + ```toml config-example + [tool.hatch.build.hooks.<PLUGIN_NAME>] + [tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>] + ``` + """ + return self.__config + + @property + def metadata(self) -> ProjectMetadata: + # Undocumented for now + return self.__metadata + + @property + def build_config(self) -> BuilderConfigBound: + """ + An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig). + """ + return self.__build_config + + @property + def directory(self) -> str: + """ + The build directory. + """ + return self.__directory + + @property + def target_name(self) -> str: + """ + The plugin name of the build target. + """ + return self.__target_name + + def clean(self, versions: list[str]) -> None: """ - The build directory. - """ - return self.__directory - - @property - def target_name(self) -> str: + This occurs before the build process if the `-c`/`--clean` flag was passed to + the [`build`](../../cli/reference.md#hatch-build) command, or when invoking + the [`clean`](../../cli/reference.md#hatch-clean) command. + """ + + def initialize(self, version: str, build_data: dict[str, Any]) -> None: """ - The plugin name of the build target. - """ - return self.__target_name - - def clean(self, versions: list[str]) -> None: - """ - This occurs before the build process if the `-c`/`--clean` flag was passed to - the [`build`](../../cli/reference.md#hatch-build) command, or when invoking - the [`clean`](../../cli/reference.md#hatch-clean) command. - """ - - def initialize(self, version: str, build_data: dict[str, Any]) -> None: - """ - This occurs immediately before each build. - - Any modifications to the build data will be seen by the build target. - """ - - def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None: - """ - This occurs immediately after each build and will not run if the `--hooks-only` flag - was passed to the [`build`](../../cli/reference.md#hatch-build) command. - - The build data will reflect any modifications done by the target during the build. - """ + This occurs immediately before each build. + + Any modifications to the build data will be seen by the build target. + """ + + def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None: + """ + This occurs immediately after each build and will not run if the `--hooks-only` flag + was passed to the [`build`](../../cli/reference.md#hatch-build) command. + + The build data will reflect any modifications done by the target during the build. + """

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

app: Application property

An instance of Application.

root: str property

The root of the project tree.

config: dict[str, Any] property

The cumulative hook configuration.

[tool.hatch.build.hooks.<PLUGIN_NAME>]
 [tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]
 
[build.hooks.<PLUGIN_NAME>]
 [build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]
-

build_config: BuilderConfigBound property

An instance of BuilderConfig.

target_name: str property

The plugin name of the build target.

directory: str property

The build directory.

clean(versions: list[str]) -> None

This occurs before the build process if the -c/--clean flag was passed to the build command, or when invoking the clean command.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def clean(self, versions: list[str]) -> None:
-    """
-    This occurs before the build process if the `-c`/`--clean` flag was passed to
-    the [`build`](../../cli/reference.md#hatch-build) command, or when invoking
-    the [`clean`](../../cli/reference.md#hatch-clean) command.
-    """
-

initialize(version: str, build_data: dict[str, Any]) -> None

This occurs immediately before each build.

Any modifications to the build data will be seen by the build target.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def initialize(self, version: str, build_data: dict[str, Any]) -> None:
-    """
-    This occurs immediately before each build.
-
-    Any modifications to the build data will be seen by the build target.
-    """
-

finalize(version: str, build_data: dict[str, Any], artifact_path: str) -> None

This occurs immediately after each build and will not run if the --hooks-only flag was passed to the build command.

The build data will reflect any modifications done by the target during the build.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:
-    """
-    This occurs immediately after each build and will not run if the `--hooks-only` flag
-    was passed to the [`build`](../../cli/reference.md#hatch-build) command.
-
-    The build data will reflect any modifications done by the target during the build.
-    """
+

build_config: BuilderConfigBound property

An instance of BuilderConfig.

target_name: str property

The plugin name of the build target.

directory: str property

The build directory.

clean(versions: list[str]) -> None

This occurs before the build process if the -c/--clean flag was passed to the build command, or when invoking the clean command.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def clean(self, versions: list[str]) -> None:
+    """
+    This occurs before the build process if the `-c`/`--clean` flag was passed to
+    the [`build`](../../cli/reference.md#hatch-build) command, or when invoking
+    the [`clean`](../../cli/reference.md#hatch-clean) command.
+    """
+

initialize(version: str, build_data: dict[str, Any]) -> None

This occurs immediately before each build.

Any modifications to the build data will be seen by the build target.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def initialize(self, version: str, build_data: dict[str, Any]) -> None:
+    """
+    This occurs immediately before each build.
+
+    Any modifications to the build data will be seen by the build target.
+    """
+

finalize(version: str, build_data: dict[str, Any], artifact_path: str) -> None

This occurs immediately after each build and will not run if the --hooks-only flag was passed to the build command.

The build data will reflect any modifications done by the target during the build.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:
+    """
+    This occurs immediately after each build and will not run if the `--hooks-only` flag
+    was passed to the [`build`](../../cli/reference.md#hatch-build) command.
+
+    The build data will reflect any modifications done by the target during the build.
+    """
 
\ No newline at end of file diff --git a/dev/plugins/build-hook/version/index.html b/dev/plugins/build-hook/version/index.html index 164440043..d4e8ad140 100644 --- a/dev/plugins/build-hook/version/index.html +++ b/dev/plugins/build-hook/version/index.html @@ -13,4 +13,4 @@ [tool.hatch.build.targets.<TARGET_NAME>.hooks.version]
[build.hooks.version]
 [build.targets.<TARGET_NAME>.hooks.version]
-

Options

Option Description
path (required) A relative path to the desired file
template A string representing the entire contents of path that will be formatted with a version variable
pattern Rather than updating the entire file, a regular expression may be used that has a named group called version that represents the version. If set to true, a pattern will be used that looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v.
\ No newline at end of file +

Options

Option Description
path (required) A relative path to the desired file
template A string representing the entire contents of path that will be formatted with a version variable
pattern Rather than updating the entire file, a regular expression may be used that has a named group called version that represents the version. If set to true, a pattern will be used that looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v.
\ No newline at end of file diff --git a/dev/plugins/builder/app/index.html b/dev/plugins/builder/app/index.html index afc318a07..36d02cf04 100644 --- a/dev/plugins/builder/app/index.html +++ b/dev/plugins/builder/app/index.html @@ -11,4 +11,4 @@ body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);}
Skip to content

Application builder


This uses PyApp to build an application that is able to bootstrap itself at runtime.

Note

This requires an installation of Rust.

Configuration

The builder plugin name is app.

[tool.hatch.build.targets.app]
 
[build.targets.app]
-

Options

Option Default Description
scripts all defined An array of defined script names to limit what gets built
python-version latest compatible Python minor version The Python version ID to use
pyapp-version The version of PyApp to use

Build behavior

If any scripts are defined then each one will be built (limited by the scripts option). Otherwise, a single executable will be built based on the project name assuming there is an equivalently named module with a __main__.py file.

Every executable will be built inside an app directory in the output directory.

If the CARGO environment variable is set then that path will be used as the executable for performing builds.

If the CARGO_BUILD_TARGET environment variable is set then its value will be appended to the file name stems.

If the PYAPP_REPO environment variable is set then a local build will be performed inside that directory rather than installing from crates.io. Note that this is required if the CARGO environment variable refers to cross.

\ No newline at end of file +

Options

Option Default Description
scripts all defined An array of defined script names to limit what gets built
python-version latest compatible Python minor version The Python version ID to use
pyapp-version The version of PyApp to use

Build behavior

If any scripts are defined then each one will be built (limited by the scripts option). Otherwise, a single executable will be built based on the project name assuming there is an equivalently named module with a __main__.py file.

Every executable will be built inside an app directory in the output directory.

If the CARGO environment variable is set then that path will be used as the executable for performing builds.

If the CARGO_BUILD_TARGET environment variable is set then its value will be appended to the file name stems.

If the PYAPP_REPO environment variable is set then a local build will be performed inside that directory rather than installing from crates.io. Note that this is required if the CARGO environment variable refers to cross.

\ No newline at end of file diff --git a/dev/plugins/builder/custom/index.html b/dev/plugins/builder/custom/index.html index 64ff11f5f..1cc0cbe0c 100644 --- a/dev/plugins/builder/custom/index.html +++ b/dev/plugins/builder/custom/index.html @@ -16,4 +16,4 @@ class CustomBuilder(BuilderInterface): ... -

If multiple subclasses are found, you must define a function named get_builder that returns the desired builder.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

\ No newline at end of file +

If multiple subclasses are found, you must define a function named get_builder that returns the desired builder.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

\ No newline at end of file diff --git a/dev/plugins/builder/reference/index.html b/dev/plugins/builder/reference/index.html index fbd6de6a6..e6178b529 100644 --- a/dev/plugins/builder/reference/index.html +++ b/dev/plugins/builder/reference/index.html @@ -27,461 +27,441 @@ """ Example usage: - === ":octicons-file-code-16: plugin.py" - - ```python - from hatchling.builders.plugin.interface import BuilderInterface - - - class SpecialBuilder(BuilderInterface): - PLUGIN_NAME = 'special' - ... - ``` - - === ":octicons-file-code-16: hooks.py" - - ```python - from hatchling.plugin import hookimpl - - from .plugin import SpecialBuilder - - - @hookimpl - def hatch_register_builder(): - return SpecialBuilder - ``` - """ - - PLUGIN_NAME = '' - """The name used for selection.""" - - def __init__( - self, - root: str, - plugin_manager: PluginManagerBound | None = None, - config: dict[str, Any] | None = None, - metadata: ProjectMetadata | None = None, - app: Application | None = None, - ) -> None: - self.__root = root - self.__plugin_manager = cast(PluginManagerBound, plugin_manager) - self.__raw_config = config - self.__metadata = metadata - self.__app = app - self.__config = cast(BuilderConfigBound, None) - self.__project_config: dict[str, Any] | None = None - self.__hatch_config: dict[str, Any] | None = None - self.__build_config: dict[str, Any] | None = None - self.__build_targets: list[str] | None = None - self.__target_config: dict[str, Any] | None = None - - # Metadata - self.__project_id: str | None = None - - def build( - self, - directory: str | None = None, - versions: list[str] | None = None, - hooks_only: bool | None = None, - clean: bool | None = None, - clean_hooks_after: bool | None = None, - clean_only: bool | None = False, # noqa: FBT002 - ) -> Generator[str, None, None]: - # Fail early for invalid project metadata - self.metadata.validate_fields() - - if directory is None: - directory = ( - self.config.normalize_build_directory(os.environ[BuildEnvVars.LOCATION]) - if BuildEnvVars.LOCATION in os.environ - else self.config.directory - ) - - if not os.path.isdir(directory): - os.makedirs(directory) - - version_api = self.get_version_api() - - versions = versions or self.config.versions - if versions: - unknown_versions = set(versions) - set(version_api) - if unknown_versions: - message = ( - f'Unknown versions for target `{self.PLUGIN_NAME}`: {", ".join(map(str, sorted(unknown_versions)))}' - ) - raise ValueError(message) - - if hooks_only is None: - hooks_only = env_var_enabled(BuildEnvVars.HOOKS_ONLY) - - configured_build_hooks = self.get_build_hooks(directory) - build_hooks = list(configured_build_hooks.values()) - - if clean_only: - clean = True - elif clean is None: - clean = env_var_enabled(BuildEnvVars.CLEAN) - if clean: - if not hooks_only: - self.clean(directory, versions) - - for build_hook in build_hooks: - build_hook.clean(versions) - - if clean_only: - return - - if clean_hooks_after is None: - clean_hooks_after = env_var_enabled(BuildEnvVars.CLEAN_HOOKS_AFTER) - - for version in versions: - self.app.display_debug(f'Building `{self.PLUGIN_NAME}` version `{version}`') - - build_data = self.get_default_build_data() - self.set_build_data_defaults(build_data) - - # Allow inspection of configured build hooks and the order in which they run - build_data['build_hooks'] = tuple(configured_build_hooks) + ```python tab="plugin.py" + from hatchling.builders.plugin.interface import BuilderInterface + + + class SpecialBuilder(BuilderInterface): + PLUGIN_NAME = 'special' + ... + ``` + + ```python tab="hooks.py" + from hatchling.plugin import hookimpl + + from .plugin import SpecialBuilder + + + @hookimpl + def hatch_register_builder(): + return SpecialBuilder + ``` + """ + + PLUGIN_NAME = '' + """The name used for selection.""" + + def __init__( + self, + root: str, + plugin_manager: PluginManagerBound | None = None, + config: dict[str, Any] | None = None, + metadata: ProjectMetadata | None = None, + app: Application | None = None, + ) -> None: + self.__root = root + self.__plugin_manager = cast(PluginManagerBound, plugin_manager) + self.__raw_config = config + self.__metadata = metadata + self.__app = app + self.__config = cast(BuilderConfigBound, None) + self.__project_config: dict[str, Any] | None = None + self.__hatch_config: dict[str, Any] | None = None + self.__build_config: dict[str, Any] | None = None + self.__build_targets: list[str] | None = None + self.__target_config: dict[str, Any] | None = None + + # Metadata + self.__project_id: str | None = None + + def build( + self, + directory: str | None = None, + versions: list[str] | None = None, + hooks_only: bool | None = None, + clean: bool | None = None, + clean_hooks_after: bool | None = None, + clean_only: bool | None = False, # noqa: FBT002 + ) -> Generator[str, None, None]: + # Fail early for invalid project metadata + self.metadata.validate_fields() + + if directory is None: + directory = ( + self.config.normalize_build_directory(os.environ[BuildEnvVars.LOCATION]) + if BuildEnvVars.LOCATION in os.environ + else self.config.directory + ) + + if not os.path.isdir(directory): + os.makedirs(directory) + + version_api = self.get_version_api() + + versions = versions or self.config.versions + if versions: + unknown_versions = set(versions) - set(version_api) + if unknown_versions: + message = ( + f'Unknown versions for target `{self.PLUGIN_NAME}`: {", ".join(map(str, sorted(unknown_versions)))}' + ) + raise ValueError(message) + + if hooks_only is None: + hooks_only = env_var_enabled(BuildEnvVars.HOOKS_ONLY) + + configured_build_hooks = self.get_build_hooks(directory) + build_hooks = list(configured_build_hooks.values()) + + if clean_only: + clean = True + elif clean is None: + clean = env_var_enabled(BuildEnvVars.CLEAN) + if clean: + if not hooks_only: + self.clean(directory, versions) + + for build_hook in build_hooks: + build_hook.clean(versions) + + if clean_only: + return + + if clean_hooks_after is None: + clean_hooks_after = env_var_enabled(BuildEnvVars.CLEAN_HOOKS_AFTER) + + for version in versions: + self.app.display_debug(f'Building `{self.PLUGIN_NAME}` version `{version}`') + + build_data = self.get_default_build_data() + self.set_build_data_defaults(build_data) + + # Allow inspection of configured build hooks and the order in which they run + build_data['build_hooks'] = tuple(configured_build_hooks) + + # Execute all `initialize` build hooks + for build_hook in build_hooks: + build_hook.initialize(version, build_data) - # Execute all `initialize` build hooks - for build_hook in build_hooks: - build_hook.initialize(version, build_data) + if hooks_only: + self.app.display_debug(f'Only ran build hooks for `{self.PLUGIN_NAME}` version `{version}`') + continue - if hooks_only: - self.app.display_debug(f'Only ran build hooks for `{self.PLUGIN_NAME}` version `{version}`') - continue + # Build the artifact + with self.config.set_build_data(build_data): + artifact = version_api[version](directory, **build_data) - # Build the artifact - with self.config.set_build_data(build_data): - artifact = version_api[version](directory, **build_data) + # Execute all `finalize` build hooks + for build_hook in build_hooks: + build_hook.finalize(version, build_data, artifact) - # Execute all `finalize` build hooks - for build_hook in build_hooks: - build_hook.finalize(version, build_data, artifact) + if clean_hooks_after: + for build_hook in build_hooks: + build_hook.clean([version]) - if clean_hooks_after: - for build_hook in build_hooks: - build_hook.clean([version]) - - yield artifact - - def recurse_included_files(self) -> Iterable[IncludedFile]: - """ - Returns a consistently generated series of file objects for every file that should be distributed. Each file - object has three `str` attributes: - - - `path` - the absolute path - - `relative_path` - the path relative to the project root; will be an empty string for external files - - `distribution_path` - the path to be distributed as - """ - yield from self.recurse_selected_project_files() - yield from self.recurse_forced_files(self.config.get_force_include()) - - def recurse_selected_project_files(self) -> Iterable[IncludedFile]: - if self.config.only_include: - yield from self.recurse_explicit_files(self.config.only_include) - else: - yield from self.recurse_project_files() + yield artifact + + def recurse_included_files(self) -> Iterable[IncludedFile]: + """ + Returns a consistently generated series of file objects for every file that should be distributed. Each file + object has three `str` attributes: + + - `path` - the absolute path + - `relative_path` - the path relative to the project root; will be an empty string for external files + - `distribution_path` - the path to be distributed as + """ + yield from self.recurse_selected_project_files() + yield from self.recurse_forced_files(self.config.get_force_include()) + + def recurse_selected_project_files(self) -> Iterable[IncludedFile]: + if self.config.only_include: + yield from self.recurse_explicit_files(self.config.only_include) + else: + yield from self.recurse_project_files() + + def recurse_project_files(self) -> Iterable[IncludedFile]: + for root, dirs, files in safe_walk(self.root): + relative_path = get_relative_path(root, self.root) - def recurse_project_files(self) -> Iterable[IncludedFile]: - for root, dirs, files in safe_walk(self.root): - relative_path = get_relative_path(root, self.root) - - dirs[:] = sorted(d for d in dirs if not self.config.directory_is_excluded(d, relative_path)) - - files.sort() - is_package = '__init__.py' in files - for f in files: - relative_file_path = os.path.join(relative_path, f) - if self.config.include_path(relative_file_path, is_package=is_package): - yield IncludedFile( - os.path.join(root, f), relative_file_path, self.config.get_distribution_path(relative_file_path) - ) - - def recurse_forced_files(self, inclusion_map: dict[str, str]) -> Iterable[IncludedFile]: - for source, target_path in inclusion_map.items(): - external = not source.startswith(self.root) - if os.path.isfile(source): - yield IncludedFile( - source, - '' if external else os.path.relpath(source, self.root), - self.config.get_distribution_path(target_path), - ) - elif os.path.isdir(source): - for root, dirs, files in safe_walk(source): - relative_directory = get_relative_path(root, source) - - dirs[:] = sorted(d for d in dirs if d not in EXCLUDED_DIRECTORIES) - - files.sort() - for f in files: - relative_file_path = os.path.join(target_path, relative_directory, f) - if not self.config.path_is_reserved(relative_file_path): - yield IncludedFile( - os.path.join(root, f), - '' if external else relative_file_path, - self.config.get_distribution_path(relative_file_path), - ) - - def recurse_explicit_files(self, inclusion_map: dict[str, str]) -> Iterable[IncludedFile]: - for source, target_path in inclusion_map.items(): - external = not source.startswith(self.root) - if os.path.isfile(source): - yield IncludedFile( - source, - '' if external else os.path.relpath(source, self.root), - self.config.get_distribution_path(target_path), - ) - elif os.path.isdir(source): - for root, dirs, files in safe_walk(source): - relative_directory = get_relative_path(root, source) - - dirs[:] = sorted(d for d in dirs if d not in EXCLUDED_DIRECTORIES) - - files.sort() - is_package = '__init__.py' in files - for f in files: - relative_file_path = os.path.join(target_path, relative_directory, f) - if self.config.include_path(relative_file_path, explicit=True, is_package=is_package): - yield IncludedFile( - os.path.join(root, f), - '' if external else relative_file_path, - self.config.get_distribution_path(relative_file_path), - ) - - @property - def root(self) -> str: - """ - The root of the project tree. - """ - return self.__root - - @property - def plugin_manager(self) -> PluginManagerBound: - if self.__plugin_manager is None: - from hatchling.plugin.manager import PluginManager + dirs[:] = sorted(d for d in dirs if not self.config.directory_is_excluded(d, relative_path)) + + files.sort() + is_package = '__init__.py' in files + for f in files: + relative_file_path = os.path.join(relative_path, f) + if self.config.include_path(relative_file_path, is_package=is_package): + yield IncludedFile( + os.path.join(root, f), relative_file_path, self.config.get_distribution_path(relative_file_path) + ) + + def recurse_forced_files(self, inclusion_map: dict[str, str]) -> Iterable[IncludedFile]: + for source, target_path in inclusion_map.items(): + external = not source.startswith(self.root) + if os.path.isfile(source): + yield IncludedFile( + source, + '' if external else os.path.relpath(source, self.root), + self.config.get_distribution_path(target_path), + ) + elif os.path.isdir(source): + for root, dirs, files in safe_walk(source): + relative_directory = get_relative_path(root, source) + + dirs[:] = sorted(d for d in dirs if d not in EXCLUDED_DIRECTORIES) + + files.sort() + for f in files: + relative_file_path = os.path.join(target_path, relative_directory, f) + if not self.config.path_is_reserved(relative_file_path): + yield IncludedFile( + os.path.join(root, f), + '' if external else relative_file_path, + self.config.get_distribution_path(relative_file_path), + ) + + def recurse_explicit_files(self, inclusion_map: dict[str, str]) -> Iterable[IncludedFile]: + for source, target_path in inclusion_map.items(): + external = not source.startswith(self.root) + if os.path.isfile(source): + yield IncludedFile( + source, + '' if external else os.path.relpath(source, self.root), + self.config.get_distribution_path(target_path), + ) + elif os.path.isdir(source): + for root, dirs, files in safe_walk(source): + relative_directory = get_relative_path(root, source) + + dirs[:] = sorted(d for d in dirs if d not in EXCLUDED_DIRECTORIES) + + files.sort() + is_package = '__init__.py' in files + for f in files: + relative_file_path = os.path.join(target_path, relative_directory, f) + if self.config.include_path(relative_file_path, explicit=True, is_package=is_package): + yield IncludedFile( + os.path.join(root, f), + '' if external else relative_file_path, + self.config.get_distribution_path(relative_file_path), + ) + + @property + def root(self) -> str: + """ + The root of the project tree. + """ + return self.__root + + @property + def plugin_manager(self) -> PluginManagerBound: + if self.__plugin_manager is None: + from hatchling.plugin.manager import PluginManager + + self.__plugin_manager = PluginManager() + + return self.__plugin_manager - self.__plugin_manager = PluginManager() - - return self.__plugin_manager - - @property - def metadata(self) -> ProjectMetadata: - if self.__metadata is None: - from hatchling.metadata.core import ProjectMetadata + @property + def metadata(self) -> ProjectMetadata: + if self.__metadata is None: + from hatchling.metadata.core import ProjectMetadata + + self.__metadata = ProjectMetadata(self.root, self.plugin_manager, self.__raw_config) + + return self.__metadata - self.__metadata = ProjectMetadata(self.root, self.plugin_manager, self.__raw_config) - - return self.__metadata - - @property - def app(self) -> Application: - """ - An instance of [Application](../utilities.md#hatchling.bridge.app.Application). - """ - if self.__app is None: - from hatchling.bridge.app import Application + @property + def app(self) -> Application: + """ + An instance of [Application](../utilities.md#hatchling.bridge.app.Application). + """ + if self.__app is None: + from hatchling.bridge.app import Application + + self.__app = cast(Application, Application().get_safe_application()) + + return self.__app - self.__app = cast(Application, Application().get_safe_application()) - - return self.__app - - @property - def raw_config(self) -> dict[str, Any]: - if self.__raw_config is None: - self.__raw_config = self.metadata.config - - return self.__raw_config - - @property - def project_config(self) -> dict[str, Any]: - if self.__project_config is None: - self.__project_config = self.metadata.core.config - - return self.__project_config - - @property - def hatch_config(self) -> dict[str, Any]: - if self.__hatch_config is None: - self.__hatch_config = self.metadata.hatch.config - - return self.__hatch_config - - @property - def config(self) -> BuilderConfigBound: - """ - An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig). - """ - if self.__config is None: - self.__config = self.get_config_class()( - self, self.root, self.PLUGIN_NAME, self.build_config, self.target_config - ) - - return self.__config - - @property - def build_config(self) -> dict[str, Any]: - """ - === ":octicons-file-code-16: pyproject.toml" - - ```toml - [tool.hatch.build] - ``` - - === ":octicons-file-code-16: hatch.toml" - - ```toml - [build] - ``` + @property + def raw_config(self) -> dict[str, Any]: + if self.__raw_config is None: + self.__raw_config = self.metadata.config + + return self.__raw_config + + @property + def project_config(self) -> dict[str, Any]: + if self.__project_config is None: + self.__project_config = self.metadata.core.config + + return self.__project_config + + @property + def hatch_config(self) -> dict[str, Any]: + if self.__hatch_config is None: + self.__hatch_config = self.metadata.hatch.config + + return self.__hatch_config + + @property + def config(self) -> BuilderConfigBound: + """ + An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig). + """ + if self.__config is None: + self.__config = self.get_config_class()( + self, self.root, self.PLUGIN_NAME, self.build_config, self.target_config + ) + + return self.__config + + @property + def build_config(self) -> dict[str, Any]: + """ + ```toml config-example + [tool.hatch.build] + ``` + """ + if self.__build_config is None: + self.__build_config = self.metadata.hatch.build_config + + return self.__build_config + + @property + def target_config(self) -> dict[str, Any]: + """ + ```toml config-example + [tool.hatch.build.targets.<PLUGIN_NAME>] + ``` """ - if self.__build_config is None: - self.__build_config = self.metadata.hatch.build_config - - return self.__build_config - - @property - def target_config(self) -> dict[str, Any]: - """ - === ":octicons-file-code-16: pyproject.toml" + if self.__target_config is None: + target_config: dict[str, Any] = self.metadata.hatch.build_targets.get(self.PLUGIN_NAME, {}) + if not isinstance(target_config, dict): + message = f'Field `tool.hatch.build.targets.{self.PLUGIN_NAME}` must be a table' + raise TypeError(message) + + self.__target_config = target_config + + return self.__target_config - ```toml - [tool.hatch.build.targets.<PLUGIN_NAME>] - ``` - - === ":octicons-file-code-16: hatch.toml" - - ```toml - [build.targets.<PLUGIN_NAME>] - ``` - """ - if self.__target_config is None: - target_config: dict[str, Any] = self.metadata.hatch.build_targets.get(self.PLUGIN_NAME, {}) - if not isinstance(target_config, dict): - message = f'Field `tool.hatch.build.targets.{self.PLUGIN_NAME}` must be a table' - raise TypeError(message) - - self.__target_config = target_config - - return self.__target_config - - @property - def project_id(self) -> str: - if self.__project_id is None: - self.__project_id = f'{self.normalize_file_name_component(self.metadata.core.name)}-{self.metadata.version}' - - return self.__project_id - - def get_build_hooks(self, directory: str) -> dict[str, BuildHookInterface]: - configured_build_hooks = {} - for hook_name, config in self.config.hook_config.items(): - build_hook = self.plugin_manager.build_hook.get(hook_name) - if build_hook is None: - from hatchling.plugin.exceptions import UnknownPluginError - - message = f'Unknown build hook: {hook_name}' - raise UnknownPluginError(message) - - configured_build_hooks[hook_name] = build_hook( - self.root, config, self.config, self.metadata, directory, self.PLUGIN_NAME, self.app - ) - - return configured_build_hooks - - @abstractmethod - def get_version_api(self) -> dict[str, Callable]: - """ - A mapping of `str` versions to a callable that is used for building. - Each callable must have the following signature: - - ```python - def ...(build_dir: str, build_data: dict) -> str: - ``` - - The return value must be the absolute path to the built artifact. - """ - - def get_default_versions(self) -> list[str]: - """ - A list of versions to build when users do not specify any, defaulting to all versions. - """ - return list(self.get_version_api()) - - def get_default_build_data(self) -> dict[str, Any]: - """ - A mapping that can be modified by [build hooks](../build-hook/reference.md) to influence the behavior of builds. - """ - return {} - - def set_build_data_defaults(self, build_data: dict[str, Any]) -> None: - build_data.setdefault('artifacts', []) - build_data.setdefault('force_include', {}) - - def clean(self, directory: str, versions: list[str]) -> None: - """ - Called before builds if the `-c`/`--clean` flag was passed to the - [`build`](../../cli/reference.md#hatch-build) command. - """ - - @classmethod - def get_config_class(cls) -> type[BuilderConfig]: - """ - Must return a subclass of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig). - """ - return BuilderConfig - - @staticmethod - def normalize_file_name_component(file_name: str) -> str: - """ - https://peps.python.org/pep-0427/#escaping-and-unicode - """ - return re.sub(r'[^\w\d.]+', '_', file_name, re.UNICODE) + @property + def project_id(self) -> str: + if self.__project_id is None: + self.__project_id = f'{self.normalize_file_name_component(self.metadata.core.name)}-{self.metadata.version}' + + return self.__project_id + + def get_build_hooks(self, directory: str) -> dict[str, BuildHookInterface]: + configured_build_hooks = {} + for hook_name, config in self.config.hook_config.items(): + build_hook = self.plugin_manager.build_hook.get(hook_name) + if build_hook is None: + from hatchling.plugin.exceptions import UnknownPluginError + + message = f'Unknown build hook: {hook_name}' + raise UnknownPluginError(message) + + configured_build_hooks[hook_name] = build_hook( + self.root, config, self.config, self.metadata, directory, self.PLUGIN_NAME, self.app + ) + + return configured_build_hooks + + @abstractmethod + def get_version_api(self) -> dict[str, Callable]: + """ + A mapping of `str` versions to a callable that is used for building. + Each callable must have the following signature: + + ```python + def ...(build_dir: str, build_data: dict) -> str: + ``` + + The return value must be the absolute path to the built artifact. + """ + + def get_default_versions(self) -> list[str]: + """ + A list of versions to build when users do not specify any, defaulting to all versions. + """ + return list(self.get_version_api()) + + def get_default_build_data(self) -> dict[str, Any]: + """ + A mapping that can be modified by [build hooks](../build-hook/reference.md) to influence the behavior of builds. + """ + return {} + + def set_build_data_defaults(self, build_data: dict[str, Any]) -> None: + build_data.setdefault('artifacts', []) + build_data.setdefault('force_include', {}) + + def clean(self, directory: str, versions: list[str]) -> None: + """ + Called before builds if the `-c`/`--clean` flag was passed to the + [`build`](../../cli/reference.md#hatch-build) command. + """ + + @classmethod + def get_config_class(cls) -> type[BuilderConfig]: + """ + Must return a subclass of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig). + """ + return BuilderConfig + + @staticmethod + def normalize_file_name_component(file_name: str) -> str: + """ + https://peps.python.org/pep-0427/#escaping-and-unicode + """ + return re.sub(r'[^\w\d.]+', '_', file_name, re.UNICODE)

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

app: Application property

An instance of Application.

root: str property

The root of the project tree.

build_config: dict[str, Any] property

[tool.hatch.build]
 
[build]
 

target_config: dict[str, Any] property

[tool.hatch.build.targets.<PLUGIN_NAME>]
 
[build.targets.<PLUGIN_NAME>]
-

config: BuilderConfigBound property

An instance of BuilderConfig.

get_config_class() -> type[BuilderConfig] classmethod

Must return a subclass of BuilderConfig.

Source code in backend/src/hatchling/builders/plugin/interface.py
@classmethod
-def get_config_class(cls) -> type[BuilderConfig]:
-    """
-    Must return a subclass of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).
-    """
-    return BuilderConfig
+

config: BuilderConfigBound property

An instance of BuilderConfig.

get_config_class() -> type[BuilderConfig] classmethod

Must return a subclass of BuilderConfig.

Source code in backend/src/hatchling/builders/plugin/interface.py
@classmethod
+def get_config_class(cls) -> type[BuilderConfig]:
+    """
+    Must return a subclass of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).
+    """
+    return BuilderConfig
 

get_version_api() -> dict[str, Callable] abstractmethod

A mapping of str versions to a callable that is used for building. Each callable must have the following signature:

def ...(build_dir: str, build_data: dict) -> str:
-

The return value must be the absolute path to the built artifact.

Source code in backend/src/hatchling/builders/plugin/interface.py
@abstractmethod
-def get_version_api(self) -> dict[str, Callable]:
-    """
-    A mapping of `str` versions to a callable that is used for building.
-    Each callable must have the following signature:
-
-    ```python
-    def ...(build_dir: str, build_data: dict) -> str:
-    ```
-
-    The return value must be the absolute path to the built artifact.
-    """
-

get_default_versions() -> list[str]

A list of versions to build when users do not specify any, defaulting to all versions.

Source code in backend/src/hatchling/builders/plugin/interface.py
def get_default_versions(self) -> list[str]:
-    """
-    A list of versions to build when users do not specify any, defaulting to all versions.
-    """
-    return list(self.get_version_api())
-

clean(directory: str, versions: list[str]) -> None

Called before builds if the -c/--clean flag was passed to the build command.

Source code in backend/src/hatchling/builders/plugin/interface.py
def clean(self, directory: str, versions: list[str]) -> None:
-    """
-    Called before builds if the `-c`/`--clean` flag was passed to the
-    [`build`](../../cli/reference.md#hatch-build) command.
-    """
-

recurse_included_files() -> Iterable[IncludedFile]

Returns a consistently generated series of file objects for every file that should be distributed. Each file object has three str attributes:

Source code in backend/src/hatchling/builders/plugin/interface.py
def recurse_included_files(self) -> Iterable[IncludedFile]:
-    """
-    Returns a consistently generated series of file objects for every file that should be distributed. Each file
-    object has three `str` attributes:
-
-    - `path` - the absolute path
-    - `relative_path` - the path relative to the project root; will be an empty string for external files
-    - `distribution_path` - the path to be distributed as
-    """
-    yield from self.recurse_selected_project_files()
-    yield from self.recurse_forced_files(self.config.get_force_include())
-

get_default_build_data() -> dict[str, Any]

A mapping that can be modified by build hooks to influence the behavior of builds.

Source code in backend/src/hatchling/builders/plugin/interface.py
def get_default_build_data(self) -> dict[str, Any]:
-    """
-    A mapping that can be modified by [build hooks](../build-hook/reference.md) to influence the behavior of builds.
-    """
-    return {}
+

The return value must be the absolute path to the built artifact.

Source code in backend/src/hatchling/builders/plugin/interface.py
@abstractmethod
+def get_version_api(self) -> dict[str, Callable]:
+    """
+    A mapping of `str` versions to a callable that is used for building.
+    Each callable must have the following signature:
+
+    ```python
+    def ...(build_dir: str, build_data: dict) -> str:
+    ```
+
+    The return value must be the absolute path to the built artifact.
+    """
+

get_default_versions() -> list[str]

A list of versions to build when users do not specify any, defaulting to all versions.

Source code in backend/src/hatchling/builders/plugin/interface.py
def get_default_versions(self) -> list[str]:
+    """
+    A list of versions to build when users do not specify any, defaulting to all versions.
+    """
+    return list(self.get_version_api())
+

clean(directory: str, versions: list[str]) -> None

Called before builds if the -c/--clean flag was passed to the build command.

Source code in backend/src/hatchling/builders/plugin/interface.py
def clean(self, directory: str, versions: list[str]) -> None:
+    """
+    Called before builds if the `-c`/`--clean` flag was passed to the
+    [`build`](../../cli/reference.md#hatch-build) command.
+    """
+

recurse_included_files() -> Iterable[IncludedFile]

Returns a consistently generated series of file objects for every file that should be distributed. Each file object has three str attributes:

Source code in backend/src/hatchling/builders/plugin/interface.py
def recurse_included_files(self) -> Iterable[IncludedFile]:
+    """
+    Returns a consistently generated series of file objects for every file that should be distributed. Each file
+    object has three `str` attributes:
+
+    - `path` - the absolute path
+    - `relative_path` - the path relative to the project root; will be an empty string for external files
+    - `distribution_path` - the path to be distributed as
+    """
+    yield from self.recurse_selected_project_files()
+    yield from self.recurse_forced_files(self.config.get_force_include())
+

get_default_build_data() -> dict[str, Any]

A mapping that can be modified by build hooks to influence the behavior of builds.

Source code in backend/src/hatchling/builders/plugin/interface.py
def get_default_build_data(self) -> dict[str, Any]:
+    """
+    A mapping that can be modified by [build hooks](../build-hook/reference.md) to influence the behavior of builds.
+    """
+    return {}
 
\ No newline at end of file diff --git a/dev/plugins/builder/sdist/index.html b/dev/plugins/builder/sdist/index.html index 222b293c4..8780bc82d 100644 --- a/dev/plugins/builder/sdist/index.html +++ b/dev/plugins/builder/sdist/index.html @@ -11,4 +11,4 @@ body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);}
Skip to content

Source distribution builder


A source distribution, or sdist, is an archive of Python "source code". Although largely unspecified, by convention it should include everything that is required to build a wheel without making network requests.

Configuration

The builder plugin name is sdist.

[tool.hatch.build.targets.sdist]
 
[build.targets.sdist]
-

Options

Option Default Description
core-metadata-version "2.1" The version of core metadata to use
strict-naming true Whether or not file names should contain the normalized version of the project name
support-legacy false Whether or not to include a setup.py file to support legacy installation mechanisms

Versions

Version Description
standard (default) The latest conventional format

Default file selection

When the user has not set any file selection options, all files that are not ignored by your VCS will be included.

Note

The following files are always included and cannot be excluded:

  • /pyproject.toml
  • /hatch.toml
  • /hatch_build.py
  • /.gitignore or /.hgignore
  • Any defined readme file
  • All defined license-files

Reproducibility

Reproducible builds are supported.

Build data

This is data that can be modified by build hooks.

Data Default Description
dependencies Extra project dependencies
\ No newline at end of file +

Options

Option Default Description
core-metadata-version "2.1" The version of core metadata to use
strict-naming true Whether or not file names should contain the normalized version of the project name
support-legacy false Whether or not to include a setup.py file to support legacy installation mechanisms

Versions

Version Description
standard (default) The latest conventional format

Default file selection

When the user has not set any file selection options, all files that are not ignored by your VCS will be included.

Note

The following files are always included and cannot be excluded:

Reproducibility

Reproducible builds are supported.

Build data

This is data that can be modified by build hooks.

Data Default Description
dependencies Extra project dependencies
\ No newline at end of file diff --git a/dev/plugins/builder/wheel/index.html b/dev/plugins/builder/wheel/index.html index 4eb10544e..879bc9f1a 100644 --- a/dev/plugins/builder/wheel/index.html +++ b/dev/plugins/builder/wheel/index.html @@ -11,4 +11,4 @@ body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);}
Skip to content

Wheel builder


A wheel is a binary distribution of a Python package that can be installed directly into an environment.

Configuration

The builder plugin name is wheel.

[tool.hatch.build.targets.wheel]
 
[build.targets.wheel]
-

Options

Option Default Description
core-metadata-version "2.1" The version of core metadata to use
shared-data A mapping similar to the forced inclusion option corresponding to data that will be installed globally in a given Python environment, usually under sys.prefix
extra-metadata A mapping similar to the forced inclusion option corresponding to extra metadata that will be shipped in a directory named extra_metadata
strict-naming true Whether or not file names should contain the normalized version of the project name
macos-max-compat true Whether or not on macOS, when build hooks have set the infer_tag build data, the wheel name should signal broad support rather than specific versions for newer SDK versions.

Note: The default will become false, and this option eventually removed, sometime after consumers like pip start supporting these newer SDK versions.

Versions

Version Description
standard (default) The latest standardized format
editable A wheel that only ships .pth files or import hooks for real-time development

Default file selection

When the user has not set any file selection options, the project name will be used to determine the package to ship in the following heuristic order:

  1. <NAME>/__init__.py
  2. src/<NAME>/__init__.py
  3. <NAME>.py
  4. <NAMESPACE>/<NAME>/__init__.py
  5. Otherwise, every Python package and file that does not start with the word test will be included

Reproducibility

Reproducible builds are supported.

Build data

This is data that can be modified by build hooks.

Data Default Description
tag The full tag part of the filename (e.g. py3-none-any), defaulting to a cross-platform wheel with the supported major versions of Python based on project metadata
infer_tag False When tag is not set, this may be enabled to use the one most specific to the platform, Python interpreter, and ABI
pure_python True Whether or not to write metadata indicating that the package does not contain any platform-specific files
dependencies Extra project dependencies
extra_metadata Additional extra-metadata entries, which take precedence in case of conflicts
force_include_editable Similar to the force_include option but specifically for the editable version and takes precedence
\ No newline at end of file +

Options

Option Default Description
core-metadata-version "2.1" The version of core metadata to use
shared-data A mapping similar to the forced inclusion option corresponding to data that will be installed globally in a given Python environment, usually under sys.prefix
extra-metadata A mapping similar to the forced inclusion option corresponding to extra metadata that will be shipped in a directory named extra_metadata
strict-naming true Whether or not file names should contain the normalized version of the project name
macos-max-compat true Whether or not on macOS, when build hooks have set the infer_tag build data, the wheel name should signal broad support rather than specific versions for newer SDK versions.

Note: The default will become false, and this option eventually removed, sometime after consumers like pip start supporting these newer SDK versions.

Versions

Version Description
standard (default) The latest standardized format
editable A wheel that only ships .pth files or import hooks for real-time development

Default file selection

When the user has not set any file selection options, the project name will be used to determine the package to ship in the following heuristic order:

  1. <NAME>/__init__.py
  2. src/<NAME>/__init__.py
  3. <NAME>.py
  4. <NAMESPACE>/<NAME>/__init__.py
  5. Otherwise, every Python package and file that does not start with the word test will be included

Reproducibility

Reproducible builds are supported.

Build data

This is data that can be modified by build hooks.

Data Default Description
tag The full tag part of the filename (e.g. py3-none-any), defaulting to a cross-platform wheel with the supported major versions of Python based on project metadata
infer_tag False When tag is not set, this may be enabled to use the one most specific to the platform, Python interpreter, and ABI
pure_python True Whether or not to write metadata indicating that the package does not contain any platform-specific files
dependencies Extra project dependencies
extra_metadata Additional extra-metadata entries, which take precedence in case of conflicts
force_include_editable Similar to the force_include option but specifically for the editable version and takes precedence
\ No newline at end of file diff --git a/dev/plugins/environment-collector/custom/index.html b/dev/plugins/environment-collector/custom/index.html index 35e11dcf3..5fe776132 100644 --- a/dev/plugins/environment-collector/custom/index.html +++ b/dev/plugins/environment-collector/custom/index.html @@ -11,9 +11,9 @@ body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);}
Skip to content

Custom environment collector


This is a custom class in a given Python file that inherits from the EnvironmentCollectorInterface.

Configuration

The environment collector plugin name is custom.

[tool.hatch.env.collectors.custom]
 
[env.collectors.custom]
-

Options

Option Default Description
path hatch_plugins.py The path of the Python file

Example

from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface
+

Options

Option Default Description
path hatch_plugins.py The path of the Python file

Example

    from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface
 
 
-class CustomEnvironmentCollector(EnvironmentCollectorInterface):
-    ...
-

If multiple subclasses are found, you must define a function named get_environment_collector that returns the desired environment collector.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

\ No newline at end of file + class CustomEnvironmentCollector(EnvironmentCollectorInterface): + ... +

If multiple subclasses are found, you must define a function named get_environment_collector that returns the desired environment collector.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

\ No newline at end of file diff --git a/dev/plugins/environment-collector/default/index.html b/dev/plugins/environment-collector/default/index.html index 008e0f603..febfa18f2 100644 --- a/dev/plugins/environment-collector/default/index.html +++ b/dev/plugins/environment-collector/default/index.html @@ -11,4 +11,4 @@ body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);}
Skip to content

Default environment collector


This adds the default environment with type set to virtual and will always be applied.

Configuration

The environment collector plugin name is default.

[tool.hatch.env.collectors.default]
 
[env.collectors.default]
-

Options

There are no options available currently.

\ No newline at end of file +

Options

There are no options available currently.

\ No newline at end of file diff --git a/dev/plugins/environment-collector/reference/index.html b/dev/plugins/environment-collector/reference/index.html index 23b240db4..7f7842bdb 100644 --- a/dev/plugins/environment-collector/reference/index.html +++ b/dev/plugins/environment-collector/reference/index.html @@ -17,120 +17,108 @@ requires = [ "...", ] -

EnvironmentCollectorInterface

Example usage:

from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface
+

EnvironmentCollectorInterface

Example usage:

    from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface
 
 
-class SpecialEnvironmentCollector(EnvironmentCollectorInterface):
-    PLUGIN_NAME = 'special'
-    ...
-
from hatchling.plugin import hookimpl
+    class SpecialEnvironmentCollector(EnvironmentCollectorInterface):
+        PLUGIN_NAME = 'special'
+        ...
+
    from hatchling.plugin import hookimpl
 
-from .plugin import SpecialEnvironmentCollector
+    from .plugin import SpecialEnvironmentCollector
 
 
-@hookimpl
-def hatch_register_environment_collector():
-    return SpecialEnvironmentCollector
+    @hookimpl
+    def hatch_register_environment_collector():
+        return SpecialEnvironmentCollector
 
Source code in src/hatch/env/collectors/plugin/interface.py
class EnvironmentCollectorInterface:
     """
     Example usage:
 
-    === ":octicons-file-code-16: plugin.py"
-
-        ```python
-        from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface
-
-
-        class SpecialEnvironmentCollector(EnvironmentCollectorInterface):
-            PLUGIN_NAME = 'special'
-            ...
-        ```
-
-    === ":octicons-file-code-16: hooks.py"
-
-        ```python
-        from hatchling.plugin import hookimpl
-
-        from .plugin import SpecialEnvironmentCollector
-
-
-        @hookimpl
-        def hatch_register_environment_collector():
-            return SpecialEnvironmentCollector
-        ```
-    """
-
-    PLUGIN_NAME = ''
-    """The name used for selection."""
+    ```python tab="plugin.py"
+        from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface
+
+
+        class SpecialEnvironmentCollector(EnvironmentCollectorInterface):
+            PLUGIN_NAME = 'special'
+            ...
+    ```
+
+    ```python tab="hooks.py"
+        from hatchling.plugin import hookimpl
+
+        from .plugin import SpecialEnvironmentCollector
+
+
+        @hookimpl
+        def hatch_register_environment_collector():
+            return SpecialEnvironmentCollector
+    ```
+    """
+
+    PLUGIN_NAME = ''
+    """The name used for selection."""
+
+    def __init__(self, root, config):
+        self.__root = root
+        self.__config = config
 
-    def __init__(self, root, config):
-        self.__root = root
-        self.__config = config
-
-    @property
-    def root(self):
-        """
-        The root of the project tree as a path-like object.
-        """
-        return self.__root
-
-    @property
-    def config(self) -> dict:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
+    @property
+    def root(self):
+        """
+        The root of the project tree as a path-like object.
+        """
+        return self.__root
+
+    @property
+    def config(self) -> dict:
+        """
+        ```toml config-example
+        [tool.hatch.env.collectors.<PLUGIN_NAME>]
+        ```
+        """
+        return self.__config
 
-            ```toml
-            [tool.hatch.env.collectors.<PLUGIN_NAME>]
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
+    def get_initial_config(self) -> dict[str, dict]:
+        """
+        Returns configuration for environments keyed by the environment or matrix name.
+        """
+        return {}
 
-            ```toml
-            [env.collectors.<PLUGIN_NAME>]
-            ```
-        """
-        return self.__config
-
-    def get_initial_config(self) -> dict[str, dict]:
-        """
-        Returns configuration for environments keyed by the environment or matrix name.
-        """
-        return {}
-
-    def finalize_config(self, config: dict[str, dict]):
-        """
-        Finalizes configuration for environments keyed by the environment or matrix name. This will override
-        any user-defined settings and any collectors that ran before this call.
-
-        This is called before matrices are turned into concrete environments.
-        """
-
-    def finalize_environments(self, config: dict[str, dict]):
-        """
-        Finalizes configuration for environments keyed by the environment name. This will override
-        any user-defined settings and any collectors that ran before this call.
-
-        This is called after matrices are turned into concrete environments.
-        """
+    def finalize_config(self, config: dict[str, dict]):
+        """
+        Finalizes configuration for environments keyed by the environment or matrix name. This will override
+        any user-defined settings and any collectors that ran before this call.
+
+        This is called before matrices are turned into concrete environments.
+        """
+
+    def finalize_environments(self, config: dict[str, dict]):
+        """
+        Finalizes configuration for environments keyed by the environment name. This will override
+        any user-defined settings and any collectors that ran before this call.
+
+        This is called after matrices are turned into concrete environments.
+        """
 

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

root property

The root of the project tree as a path-like object.

config: dict property

[tool.hatch.env.collectors.<PLUGIN_NAME>]
 
[env.collectors.<PLUGIN_NAME>]
-

get_initial_config() -> dict[str, dict]

Returns configuration for environments keyed by the environment or matrix name.

Source code in src/hatch/env/collectors/plugin/interface.py
def get_initial_config(self) -> dict[str, dict]:
-    """
-    Returns configuration for environments keyed by the environment or matrix name.
-    """
-    return {}
-

finalize_config(config: dict[str, dict])

Finalizes configuration for environments keyed by the environment or matrix name. This will override any user-defined settings and any collectors that ran before this call.

This is called before matrices are turned into concrete environments.

Source code in src/hatch/env/collectors/plugin/interface.py
def finalize_config(self, config: dict[str, dict]):
-    """
-    Finalizes configuration for environments keyed by the environment or matrix name. This will override
-    any user-defined settings and any collectors that ran before this call.
-
-    This is called before matrices are turned into concrete environments.
-    """
-

finalize_environments(config: dict[str, dict])

Finalizes configuration for environments keyed by the environment name. This will override any user-defined settings and any collectors that ran before this call.

This is called after matrices are turned into concrete environments.

Source code in src/hatch/env/collectors/plugin/interface.py
def finalize_environments(self, config: dict[str, dict]):
-    """
-    Finalizes configuration for environments keyed by the environment name. This will override
-    any user-defined settings and any collectors that ran before this call.
-
-    This is called after matrices are turned into concrete environments.
-    """
-
\ No newline at end of file +

get_initial_config() -> dict[str, dict]

Returns configuration for environments keyed by the environment or matrix name.

Source code in src/hatch/env/collectors/plugin/interface.py
def get_initial_config(self) -> dict[str, dict]:
+    """
+    Returns configuration for environments keyed by the environment or matrix name.
+    """
+    return {}
+

finalize_config(config: dict[str, dict])

Finalizes configuration for environments keyed by the environment or matrix name. This will override any user-defined settings and any collectors that ran before this call.

This is called before matrices are turned into concrete environments.

Source code in src/hatch/env/collectors/plugin/interface.py
def finalize_config(self, config: dict[str, dict]):
+    """
+    Finalizes configuration for environments keyed by the environment or matrix name. This will override
+    any user-defined settings and any collectors that ran before this call.
+
+    This is called before matrices are turned into concrete environments.
+    """
+

finalize_environments(config: dict[str, dict])

Finalizes configuration for environments keyed by the environment name. This will override any user-defined settings and any collectors that ran before this call.

This is called after matrices are turned into concrete environments.

Source code in src/hatch/env/collectors/plugin/interface.py
def finalize_environments(self, config: dict[str, dict]):
+    """
+    Finalizes configuration for environments keyed by the environment name. This will override
+    any user-defined settings and any collectors that ran before this call.
+
+    This is called after matrices are turned into concrete environments.
+    """
+
\ No newline at end of file diff --git a/dev/plugins/environment/reference/index.html b/dev/plugins/environment/reference/index.html index 56706778d..9582041a9 100644 --- a/dev/plugins/environment/reference/index.html +++ b/dev/plugins/environment/reference/index.html @@ -44,947 +44,873 @@ if not dependencies_in_sync: with self.status('Syncing dependencies'): environment.sync_dependencies() -

Build environments

All environment types should offer support for a special sub-environment in which projects can be built. This environment is used in the following scenarios:

EnvironmentInterface

Example usage:

from hatch.env.plugin.interface import EnvironmentInterface
+

Build environments

All environment types should offer support for a special sub-environment in which projects can be built. This environment is used in the following scenarios:

EnvironmentInterface

Example usage:

    from hatch.env.plugin.interface import EnvironmentInterface
 
 
-class SpecialEnvironment(EnvironmentInterface):
-    PLUGIN_NAME = 'special'
-    ...
-
from hatchling.plugin import hookimpl
+    class SpecialEnvironment(EnvironmentInterface):
+        PLUGIN_NAME = 'special'
+        ...
+
    from hatchling.plugin import hookimpl
 
-from .plugin import SpecialEnvironment
+    from .plugin import SpecialEnvironment
 
 
-@hookimpl
-def hatch_register_environment():
-    return SpecialEnvironment
+    @hookimpl
+    def hatch_register_environment():
+        return SpecialEnvironment
 
Source code in src/hatch/env/plugin/interface.py
class EnvironmentInterface(ABC):
     """
     Example usage:
 
-    === ":octicons-file-code-16: plugin.py"
-
-        ```python
-        from hatch.env.plugin.interface import EnvironmentInterface
-
-
-        class SpecialEnvironment(EnvironmentInterface):
-            PLUGIN_NAME = 'special'
-            ...
-        ```
-
-    === ":octicons-file-code-16: hooks.py"
-
-        ```python
-        from hatchling.plugin import hookimpl
-
-        from .plugin import SpecialEnvironment
-
-
-        @hookimpl
-        def hatch_register_environment():
-            return SpecialEnvironment
-        ```
-    """
-
-    PLUGIN_NAME = ''
-    """The name used for selection."""
-
-    def __init__(
-        self,
-        root,
-        metadata,
-        name,
-        config,
-        matrix_variables,
-        data_directory,
-        isolated_data_directory,
-        platform,
-        verbosity,
-        app=None,
-    ):
-        self.__root = root
-        self.__metadata = metadata
-        self.__name = name
-        self.__config = config
-        self.__matrix_variables = matrix_variables
-        self.__data_directory = data_directory
-        self.__isolated_data_directory = isolated_data_directory
-        self.__platform = platform
-        self.__verbosity = verbosity
-        self.__app = app
-        self.__context = None
-
-        self._system_python = None
-        self._env_vars = None
-        self._env_include = None
-        self._env_exclude = None
-        self._environment_dependencies_complex = None
-        self._environment_dependencies = None
-        self._dependencies_complex = None
-        self._dependencies = None
-        self._platforms = None
-        self._skip_install = None
-        self._dev_mode = None
-        self._features = None
-        self._description = None
-        self._scripts = None
-        self._pre_install_commands = None
-        self._post_install_commands = None
+    ```python tab="plugin.py"
+        from hatch.env.plugin.interface import EnvironmentInterface
+
+
+        class SpecialEnvironment(EnvironmentInterface):
+            PLUGIN_NAME = 'special'
+            ...
+    ```
+
+    ```python tab="hooks.py"
+        from hatchling.plugin import hookimpl
+
+        from .plugin import SpecialEnvironment
+
+
+        @hookimpl
+        def hatch_register_environment():
+            return SpecialEnvironment
+    ```
+    """
+
+    PLUGIN_NAME = ''
+    """The name used for selection."""
+
+    def __init__(
+        self,
+        root,
+        metadata,
+        name,
+        config,
+        matrix_variables,
+        data_directory,
+        isolated_data_directory,
+        platform,
+        verbosity,
+        app=None,
+    ):
+        self.__root = root
+        self.__metadata = metadata
+        self.__name = name
+        self.__config = config
+        self.__matrix_variables = matrix_variables
+        self.__data_directory = data_directory
+        self.__isolated_data_directory = isolated_data_directory
+        self.__platform = platform
+        self.__verbosity = verbosity
+        self.__app = app
+        self.__context = None
+
+        self._system_python = None
+        self._env_vars = None
+        self._env_include = None
+        self._env_exclude = None
+        self._environment_dependencies_complex = None
+        self._environment_dependencies = None
+        self._dependencies_complex = None
+        self._dependencies = None
+        self._platforms = None
+        self._skip_install = None
+        self._dev_mode = None
+        self._features = None
+        self._description = None
+        self._scripts = None
+        self._pre_install_commands = None
+        self._post_install_commands = None
+
+    @property
+    def matrix_variables(self):
+        return self.__matrix_variables
 
     @property
-    def matrix_variables(self):
-        return self.__matrix_variables
-
-    @property
-    def app(self):
-        """
-        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).
-        """
-        if self.__app is None:
-            from hatchling.bridge.app import Application
+    def app(self):
+        """
+        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).
+        """
+        if self.__app is None:
+            from hatchling.bridge.app import Application
+
+            self.__app = Application().get_safe_application()
+
+        return self.__app
 
-            self.__app = Application().get_safe_application()
-
-        return self.__app
-
-    @property
-    def context(self):
-        if self.__context is None:
-            self.__context = self.get_context()
-
-        return self.__context
+    @property
+    def context(self):
+        if self.__context is None:
+            self.__context = self.get_context()
+
+        return self.__context
+
+    @property
+    def verbosity(self):
+        return self.__verbosity
 
     @property
-    def verbosity(self):
-        return self.__verbosity
-
-    @property
-    def root(self):
-        """
-        The root of the project tree as a path-like object.
-        """
-        return self.__root
+    def root(self):
+        """
+        The root of the project tree as a path-like object.
+        """
+        return self.__root
+
+    @property
+    def metadata(self):
+        return self.__metadata
 
     @property
-    def metadata(self):
-        return self.__metadata
-
-    @property
-    def name(self) -> str:
-        """
-        The name of the environment.
-        """
-        return self.__name
-
-    @property
-    def platform(self):
-        """
-        An instance of [Platform](../utilities.md#hatch.utils.platform.Platform).
-        """
-        return self.__platform
-
-    @property
-    def data_directory(self):
-        """
-        The [directory](../../config/hatch.md#environments) this plugin should use for storage as a path-like object.
-        If the user has not configured one then this will be the same as the
-        [isolated data directory](reference.md#hatch.env.plugin.interface.EnvironmentInterface.isolated_data_directory).
-        """
-        return self.__data_directory
-
-    @property
-    def isolated_data_directory(self):
-        """
-        The default [directory](../../config/hatch.md#environments) reserved exclusively for this plugin as a path-like
-        object.
-        """
-        return self.__isolated_data_directory
-
-    @property
-    def config(self) -> dict:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
+    def name(self) -> str:
+        """
+        The name of the environment.
+        """
+        return self.__name
+
+    @property
+    def platform(self):
+        """
+        An instance of [Platform](../utilities.md#hatch.utils.platform.Platform).
+        """
+        return self.__platform
+
+    @property
+    def data_directory(self):
+        """
+        The [directory](../../config/hatch.md#environments) this plugin should use for storage as a path-like object.
+        If the user has not configured one then this will be the same as the
+        [isolated data directory](reference.md#hatch.env.plugin.interface.EnvironmentInterface.isolated_data_directory).
+        """
+        return self.__data_directory
+
+    @property
+    def isolated_data_directory(self):
+        """
+        The default [directory](../../config/hatch.md#environments) reserved exclusively for this plugin as a path-like
+        object.
+        """
+        return self.__isolated_data_directory
+
+    @property
+    def config(self) -> dict:
+        """
+        ```toml config-example
+        [tool.hatch.envs.<ENV_NAME>]
+        ```
+        """
+        return self.__config
 
-            ```toml
-            [tool.hatch.envs.<ENV_NAME>]
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [envs.<ENV_NAME>]
-            ```
-        """
-        return self.__config
-
-    @property
-    def system_python(self):
-        if self._system_python is None:
-            system_python = os.environ.get(AppEnvVars.PYTHON)
-            if system_python == 'self':
-                system_python = sys.executable
-
-            system_python = (
-                system_python
-                or self.platform.modules.shutil.which('python')
-                or self.platform.modules.shutil.which('python3')
-                or sys.executable
-            )
-            if not isabs(system_python):
-                system_python = self.platform.modules.shutil.which(system_python)
-
-            self._system_python = system_python
-
-        return self._system_python
-
-    @property
-    def env_vars(self) -> dict:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
-
-            ```toml
-            [tool.hatch.envs.<ENV_NAME>.env-vars]
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [envs.<ENV_NAME>.env-vars]
-            ```
-        """
-        if self._env_vars is None:
-            env_vars = self.config.get('env-vars', {})
-            if not isinstance(env_vars, dict):
-                message = f'Field `tool.hatch.envs.{self.name}.env-vars` must be a mapping'
-                raise TypeError(message)
-
-            for key, value in env_vars.items():
-                if not isinstance(value, str):
-                    message = (
-                        f'Environment variable `{key}` of field `tool.hatch.envs.{self.name}.env-vars` must be a string'
-                    )
-                    raise TypeError(message)
-
-            new_env_vars = {}
-            with self.metadata.context.apply_context(self.context):
-                for key, value in env_vars.items():
-                    new_env_vars[key] = self.metadata.context.format(value)
-
-            new_env_vars[AppEnvVars.ENV_ACTIVE] = self.name
-            self._env_vars = new_env_vars
-
-        return self._env_vars
-
-    @property
-    def env_include(self) -> list[str]:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
-
-            ```toml
-            [tool.hatch.envs.<ENV_NAME>]
-            env-include = [...]
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [envs.<ENV_NAME>]
-            env-include = [...]
-            ```
-        """
-        if self._env_include is None:
-            env_include = self.config.get('env-include', [])
-            if not isinstance(env_include, list):
-                message = f'Field `tool.hatch.envs.{self.name}.env-include` must be an array'
-                raise TypeError(message)
-
-            for i, pattern in enumerate(env_include, 1):
-                if not isinstance(pattern, str):
-                    message = f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-include` must be a string'
-                    raise TypeError(message)
-
-            if env_include:
-                self._env_include = ['HATCH_BUILD_*', *env_include]
-            else:
-                self._env_include = env_include
-
-        return self._env_include
-
-    @property
-    def env_exclude(self) -> list[str]:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
-
-            ```toml
-            [tool.hatch.envs.<ENV_NAME>]
-            env-exclude = [...]
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [envs.<ENV_NAME>]
-            env-exclude = [...]
-            ```
-        """
-        if self._env_exclude is None:
-            env_exclude = self.config.get('env-exclude', [])
-            if not isinstance(env_exclude, list):
-                message = f'Field `tool.hatch.envs.{self.name}.env-exclude` must be an array'
-                raise TypeError(message)
-
-            for i, pattern in enumerate(env_exclude, 1):
-                if not isinstance(pattern, str):
-                    message = f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-exclude` must be a string'
-                    raise TypeError(message)
-
-            self._env_exclude = env_exclude
-
-        return self._env_exclude
+    @property
+    def system_python(self):
+        if self._system_python is None:
+            system_python = os.environ.get(AppEnvVars.PYTHON)
+            if system_python == 'self':
+                system_python = sys.executable
+
+            system_python = (
+                system_python
+                or self.platform.modules.shutil.which('python')
+                or self.platform.modules.shutil.which('python3')
+                or sys.executable
+            )
+            if not isabs(system_python):
+                system_python = self.platform.modules.shutil.which(system_python)
+
+            self._system_python = system_python
+
+        return self._system_python
+
+    @property
+    def env_vars(self) -> dict:
+        """
+        ```toml config-example
+        [tool.hatch.envs.<ENV_NAME>.env-vars]
+        ```
+        """
+        if self._env_vars is None:
+            env_vars = self.config.get('env-vars', {})
+            if not isinstance(env_vars, dict):
+                message = f'Field `tool.hatch.envs.{self.name}.env-vars` must be a mapping'
+                raise TypeError(message)
+
+            for key, value in env_vars.items():
+                if not isinstance(value, str):
+                    message = (
+                        f'Environment variable `{key}` of field `tool.hatch.envs.{self.name}.env-vars` must be a string'
+                    )
+                    raise TypeError(message)
+
+            new_env_vars = {}
+            with self.metadata.context.apply_context(self.context):
+                for key, value in env_vars.items():
+                    new_env_vars[key] = self.metadata.context.format(value)
+
+            new_env_vars[AppEnvVars.ENV_ACTIVE] = self.name
+            self._env_vars = new_env_vars
+
+        return self._env_vars
+
+    @property
+    def env_include(self) -> list[str]:
+        """
+        ```toml config-example
+        [tool.hatch.envs.<ENV_NAME>]
+        env-include = [...]
+        ```
+        """
+        if self._env_include is None:
+            env_include = self.config.get('env-include', [])
+            if not isinstance(env_include, list):
+                message = f'Field `tool.hatch.envs.{self.name}.env-include` must be an array'
+                raise TypeError(message)
+
+            for i, pattern in enumerate(env_include, 1):
+                if not isinstance(pattern, str):
+                    message = f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-include` must be a string'
+                    raise TypeError(message)
+
+            if env_include:
+                self._env_include = ['HATCH_BUILD_*', *env_include]
+            else:
+                self._env_include = env_include
+
+        return self._env_include
+
+    @property
+    def env_exclude(self) -> list[str]:
+        """
+        ```toml config-example
+        [tool.hatch.envs.<ENV_NAME>]
+        env-exclude = [...]
+        ```
+        """
+        if self._env_exclude is None:
+            env_exclude = self.config.get('env-exclude', [])
+            if not isinstance(env_exclude, list):
+                message = f'Field `tool.hatch.envs.{self.name}.env-exclude` must be an array'
+                raise TypeError(message)
+
+            for i, pattern in enumerate(env_exclude, 1):
+                if not isinstance(pattern, str):
+                    message = f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-exclude` must be a string'
+                    raise TypeError(message)
+
+            self._env_exclude = env_exclude
+
+        return self._env_exclude
+
+    @property
+    def environment_dependencies_complex(self):
+        if self._environment_dependencies_complex is None:
+            from packaging.requirements import InvalidRequirement, Requirement
+
+            dependencies_complex = []
+            with self.apply_context():
+                for option in ('dependencies', 'extra-dependencies'):
+                    dependencies = self.config.get(option, [])
+                    if not isinstance(dependencies, list):
+                        message = f'Field `tool.hatch.envs.{self.name}.{option}` must be an array'
+                        raise TypeError(message)
+
+                    for i, entry in enumerate(dependencies, 1):
+                        if not isinstance(entry, str):
+                            message = (
+                                f'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` must be a string'
+                            )
+                            raise TypeError(message)
+
+                        try:
+                            dependencies_complex.append(Requirement(self.metadata.context.format(entry)))
+                        except InvalidRequirement as e:
+                            message = f'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` is invalid: {e}'
+                            raise ValueError(message) from None
+
+            self._environment_dependencies_complex = dependencies_complex
+
+        return self._environment_dependencies_complex
+
+    @property
+    def environment_dependencies(self) -> list[str]:
+        """
+        The list of all [environment dependencies](../../config/environment/overview.md#dependencies).
+        """
+        if self._environment_dependencies is None:
+            self._environment_dependencies = [str(dependency) for dependency in self.environment_dependencies_complex]
 
-    @property
-    def environment_dependencies_complex(self):
-        if self._environment_dependencies_complex is None:
-            from packaging.requirements import InvalidRequirement, Requirement
-
-            dependencies_complex = []
-            with self.apply_context():
-                for option in ('dependencies', 'extra-dependencies'):
-                    dependencies = self.config.get(option, [])
-                    if not isinstance(dependencies, list):
-                        message = f'Field `tool.hatch.envs.{self.name}.{option}` must be an array'
-                        raise TypeError(message)
-
-                    for i, entry in enumerate(dependencies, 1):
-                        if not isinstance(entry, str):
-                            message = (
-                                f'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` must be a string'
-                            )
-                            raise TypeError(message)
-
-                        try:
-                            dependencies_complex.append(Requirement(self.metadata.context.format(entry)))
-                        except InvalidRequirement as e:
-                            message = f'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` is invalid: {e}'
-                            raise ValueError(message) from None
+        return self._environment_dependencies
+
+    @property
+    def dependencies_complex(self):
+        if self._dependencies_complex is None:
+            all_dependencies_complex = list(self.environment_dependencies_complex)
+
+            # Ensure these are checked last to speed up initial environment creation since
+            # they will already be installed along with the project
+            if not self.skip_install and self.dev_mode:
+                from hatch.utils.dep import get_project_dependencies_complex
+
+                dependencies_complex, optional_dependencies_complex = get_project_dependencies_complex(self)
+
+                all_dependencies_complex.extend(dependencies_complex.values())
+
+                for feature in self.features:
+                    if feature not in optional_dependencies_complex:
+                        message = (
+                            f'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not '
+                            f'defined in the dynamic field `project.optional-dependencies`'
+                        )
+                        raise ValueError(message)
+
+                    all_dependencies_complex.extend(optional_dependencies_complex[feature].values())
 
-            self._environment_dependencies_complex = dependencies_complex
+            self._dependencies_complex = all_dependencies_complex
 
-        return self._environment_dependencies_complex
+        return self._dependencies_complex
 
     @property
-    def environment_dependencies(self) -> list[str]:
+    def dependencies(self) -> list[str]:
         """
-        The list of all [environment dependencies](../../config/environment/overview.md#dependencies).
-        """
-        if self._environment_dependencies is None:
-            self._environment_dependencies = [str(dependency) for dependency in self.environment_dependencies_complex]
-
-        return self._environment_dependencies
-
-    @property
-    def dependencies_complex(self):
-        if self._dependencies_complex is None:
-            all_dependencies_complex = list(self.environment_dependencies_complex)
-
-            # Ensure these are checked last to speed up initial environment creation since
-            # they will already be installed along with the project
-            if not self.skip_install and self.dev_mode:
-                from hatch.utils.dep import get_project_dependencies_complex
-
-                dependencies_complex, optional_dependencies_complex = get_project_dependencies_complex(self)
-
-                all_dependencies_complex.extend(dependencies_complex.values())
-
-                for feature in self.features:
-                    if feature not in optional_dependencies_complex:
-                        message = (
-                            f'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not '
-                            f'defined in the dynamic field `project.optional-dependencies`'
-                        )
-                        raise ValueError(message)
-
-                    all_dependencies_complex.extend(optional_dependencies_complex[feature].values())
+        The list of all [project dependencies](../../config/metadata.md#dependencies) (if
+        [installed](../../config/environment/overview.md#skip-install) and in
+        [dev mode](../../config/environment/overview.md#dev-mode)) and
+        [environment dependencies](../../config/environment/overview.md#dependencies).
+        """
+        if self._dependencies is None:
+            self._dependencies = [str(dependency) for dependency in self.dependencies_complex]
+
+        return self._dependencies
+
+    @property
+    def platforms(self) -> list[str]:
+        """
+        All names are stored as their lower-cased version.
+
+        ```toml config-example
+        [tool.hatch.envs.<ENV_NAME>]
+        platforms = [...]
+        ```
+        """
+        if self._platforms is None:
+            platforms = self.config.get('platforms', [])
+            if not isinstance(platforms, list):
+                message = f'Field `tool.hatch.envs.{self.name}.platforms` must be an array'
+                raise TypeError(message)
+
+            for i, command in enumerate(platforms, 1):
+                if not isinstance(command, str):
+                    message = f'Platform #{i} of field `tool.hatch.envs.{self.name}.platforms` must be a string'
+                    raise TypeError(message)
 
-            self._dependencies_complex = all_dependencies_complex
+            self._platforms = [platform.lower() for platform in platforms]
 
-        return self._dependencies_complex
+        return self._platforms
 
     @property
-    def dependencies(self) -> list[str]:
+    def skip_install(self) -> bool:
         """
-        The list of all [project dependencies](../../config/metadata.md#dependencies) (if
-        [installed](../../config/environment/overview.md#skip-install) and in
-        [dev mode](../../config/environment/overview.md#dev-mode)) and
-        [environment dependencies](../../config/environment/overview.md#dependencies).
+        ```toml config-example
+        [tool.hatch.envs.<ENV_NAME>]
+        skip-install = ...
+        ```
         """
-        if self._dependencies is None:
-            self._dependencies = [str(dependency) for dependency in self.dependencies_complex]
-
-        return self._dependencies
-
-    @property
-    def platforms(self) -> list[str]:
-        """
-        All names are stored as their lower-cased version.
+        if self._skip_install is None:
+            skip_install = self.config.get('skip-install', not self.metadata.has_project_file())
+            if not isinstance(skip_install, bool):
+                message = f'Field `tool.hatch.envs.{self.name}.skip-install` must be a boolean'
+                raise TypeError(message)
+
+            self._skip_install = skip_install
+
+        return self._skip_install
 
-        === ":octicons-file-code-16: pyproject.toml"
-
-            ```toml
-            [tool.hatch.envs.<ENV_NAME>]
-            platforms = [...]
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [envs.<ENV_NAME>]
-            platforms = [...]
-            ```
-        """
-        if self._platforms is None:
-            platforms = self.config.get('platforms', [])
-            if not isinstance(platforms, list):
-                message = f'Field `tool.hatch.envs.{self.name}.platforms` must be an array'
-                raise TypeError(message)
-
-            for i, command in enumerate(platforms, 1):
-                if not isinstance(command, str):
-                    message = f'Platform #{i} of field `tool.hatch.envs.{self.name}.platforms` must be a string'
-                    raise TypeError(message)
-
-            self._platforms = [platform.lower() for platform in platforms]
-
-        return self._platforms
-
-    @property
-    def skip_install(self) -> bool:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
-
-            ```toml
-            [tool.hatch.envs.<ENV_NAME>]
-            skip-install = ...
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [envs.<ENV_NAME>]
-            skip-install = ...
-            ```
-        """
-        if self._skip_install is None:
-            skip_install = self.config.get('skip-install', not self.metadata.has_project_file())
-            if not isinstance(skip_install, bool):
-                message = f'Field `tool.hatch.envs.{self.name}.skip-install` must be a boolean'
-                raise TypeError(message)
-
-            self._skip_install = skip_install
-
-        return self._skip_install
-
-    @property
-    def dev_mode(self) -> bool:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
-
-            ```toml
-            [tool.hatch.envs.<ENV_NAME>]
-            dev-mode = ...
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [envs.<ENV_NAME>]
-            dev-mode = ...
-            ```
-        """
-        if self._dev_mode is None:
-            dev_mode = self.config.get('dev-mode', True)
-            if not isinstance(dev_mode, bool):
-                message = f'Field `tool.hatch.envs.{self.name}.dev-mode` must be a boolean'
-                raise TypeError(message)
-
-            self._dev_mode = dev_mode
+    @property
+    def dev_mode(self) -> bool:
+        """
+        ```toml config-example
+        [tool.hatch.envs.<ENV_NAME>]
+        dev-mode = ...
+        ```
+        """
+        if self._dev_mode is None:
+            dev_mode = self.config.get('dev-mode', True)
+            if not isinstance(dev_mode, bool):
+                message = f'Field `tool.hatch.envs.{self.name}.dev-mode` must be a boolean'
+                raise TypeError(message)
+
+            self._dev_mode = dev_mode
+
+        return self._dev_mode
+
+    @property
+    def features(self):
+        if self._features is None:
+            from hatchling.metadata.utils import normalize_project_name
+
+            features = self.config.get('features', [])
+            if not isinstance(features, list):
+                message = f'Field `tool.hatch.envs.{self.name}.features` must be an array of strings'
+                raise TypeError(message)
+
+            all_features = set()
+            for i, feature in enumerate(features, 1):
+                if not isinstance(feature, str):
+                    message = f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` must be a string'
+                    raise TypeError(message)
+                elif not feature:
+                    message = f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` cannot be an empty string'
+                    raise ValueError(message)
+
+                if not self.metadata.hatch.metadata.allow_ambiguous_features:
+                    feature = normalize_project_name(feature)
+                if (
+                    not self.metadata.hatch.metadata.hook_config
+                    and feature not in self.metadata.core.optional_dependencies
+                ):
+                    message = (
+                        f'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not '
+                        f'defined in field `project.optional-dependencies`'
+                    )
+                    raise ValueError(message)
+
+                all_features.add(feature)
+
+            self._features = sorted(all_features)
+
+        return self._features
+
+    @property
+    def description(self) -> str:
+        """
+        ```toml config-example
+        [tool.hatch.envs.<ENV_NAME>]
+        description = ...
+        ```
+        """
+        if self._description is None:
+            description = self.config.get('description', '')
+            if not isinstance(description, str):
+                message = f'Field `tool.hatch.envs.{self.name}.description` must be a string'
+                raise TypeError(message)
+
+            self._description = description
+
+        return self._description
+
+    @property
+    def scripts(self):
+        if self._scripts is None:
+            script_config = self.config.get('scripts', {})
+            if not isinstance(script_config, dict):
+                message = f'Field `tool.hatch.envs.{self.name}.scripts` must be a table'
+                raise TypeError(message)
 
-        return self._dev_mode
+            config = {}
 
-    @property
-    def features(self):
-        if self._features is None:
-            from hatchling.metadata.utils import normalize_project_name
-
-            features = self.config.get('features', [])
-            if not isinstance(features, list):
-                message = f'Field `tool.hatch.envs.{self.name}.features` must be an array of strings'
-                raise TypeError(message)
-
-            all_features = set()
-            for i, feature in enumerate(features, 1):
-                if not isinstance(feature, str):
-                    message = f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` must be a string'
-                    raise TypeError(message)
-                elif not feature:
-                    message = f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` cannot be an empty string'
-                    raise ValueError(message)
+            for name, data in script_config.items():
+                if ' ' in name:
+                    message = (
+                        f'Script name `{name}` in field `tool.hatch.envs.{self.name}.scripts` must not contain spaces'
+                    )
+                    raise ValueError(message)
+
+                commands = []
+
+                if isinstance(data, str):
+                    commands.append(data)
+                elif isinstance(data, list):
+                    for i, command in enumerate(data, 1):
+                        if not isinstance(command, str):
+                            message = (
+                                f'Command #{i} in field `tool.hatch.envs.{self.name}.scripts.{name}` must be a string'
+                            )
+                            raise TypeError(message)
 
-                if not self.metadata.hatch.metadata.allow_ambiguous_features:
-                    feature = normalize_project_name(feature)
-                if (
-                    not self.metadata.hatch.metadata.hook_config
-                    and feature not in self.metadata.core.optional_dependencies
-                ):
-                    message = (
-                        f'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not '
-                        f'defined in field `project.optional-dependencies`'
-                    )
-                    raise ValueError(message)
-
-                all_features.add(feature)
+                        commands.append(command)
+                else:
+                    message = (
+                        f'Field `tool.hatch.envs.{self.name}.scripts.{name}` must be a string or an array of strings'
+                    )
+                    raise TypeError(message)
+
+                config[name] = commands
+
+            seen = {}
+            active = []
+            for script_name, commands in config.items():
+                commands[:] = expand_script_commands(self.name, script_name, commands, config, seen, active)
 
-            self._features = sorted(all_features)
+            self._scripts = config
 
-        return self._features
+        return self._scripts
 
     @property
-    def description(self) -> str:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
-
-            ```toml
-            [tool.hatch.envs.<ENV_NAME>]
-            description = ...
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [envs.<ENV_NAME>]
-            description = ...
-            ```
-        """
-        if self._description is None:
-            description = self.config.get('description', '')
-            if not isinstance(description, str):
-                message = f'Field `tool.hatch.envs.{self.name}.description` must be a string'
-                raise TypeError(message)
-
-            self._description = description
-
-        return self._description
+    def pre_install_commands(self):
+        if self._pre_install_commands is None:
+            pre_install_commands = self.config.get('pre-install-commands', [])
+            if not isinstance(pre_install_commands, list):
+                message = f'Field `tool.hatch.envs.{self.name}.pre-install-commands` must be an array'
+                raise TypeError(message)
+
+            for i, command in enumerate(pre_install_commands, 1):
+                if not isinstance(command, str):
+                    message = (
+                        f'Command #{i} of field `tool.hatch.envs.{self.name}.pre-install-commands` must be a string'
+                    )
+                    raise TypeError(message)
+
+            self._pre_install_commands = list(pre_install_commands)
+
+        return self._pre_install_commands
+
+    @property
+    def post_install_commands(self):
+        if self._post_install_commands is None:
+            post_install_commands = self.config.get('post-install-commands', [])
+            if not isinstance(post_install_commands, list):
+                message = f'Field `tool.hatch.envs.{self.name}.post-install-commands` must be an array'
+                raise TypeError(message)
 
-    @property
-    def scripts(self):
-        if self._scripts is None:
-            script_config = self.config.get('scripts', {})
-            if not isinstance(script_config, dict):
-                message = f'Field `tool.hatch.envs.{self.name}.scripts` must be a table'
-                raise TypeError(message)
-
-            config = {}
-
-            for name, data in script_config.items():
-                if ' ' in name:
-                    message = (
-                        f'Script name `{name}` in field `tool.hatch.envs.{self.name}.scripts` must not contain spaces'
-                    )
-                    raise ValueError(message)
-
-                commands = []
-
-                if isinstance(data, str):
-                    commands.append(data)
-                elif isinstance(data, list):
-                    for i, command in enumerate(data, 1):
-                        if not isinstance(command, str):
-                            message = (
-                                f'Command #{i} in field `tool.hatch.envs.{self.name}.scripts.{name}` must be a string'
-                            )
-                            raise TypeError(message)
-
-                        commands.append(command)
-                else:
-                    message = (
-                        f'Field `tool.hatch.envs.{self.name}.scripts.{name}` must be a string or an array of strings'
-                    )
-                    raise TypeError(message)
+            for i, command in enumerate(post_install_commands, 1):
+                if not isinstance(command, str):
+                    message = (
+                        f'Command #{i} of field `tool.hatch.envs.{self.name}.post-install-commands` must be a string'
+                    )
+                    raise TypeError(message)
+
+            self._post_install_commands = list(post_install_commands)
+
+        return self._post_install_commands
+
+    def activate(self):
+        """
+        A convenience method called when using the environment as a context manager:
+
+        ```python
+        with environment:
+            ...
+        ```
+        """
+
+    def deactivate(self):
+        """
+        A convenience method called after using the environment as a context manager:
+
+        ```python
+        with environment:
+            ...
+        ```
+        """
+
+    @abstractmethod
+    def find(self):
+        """
+        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
 
-                config[name] = commands
-
-            seen = {}
-            active = []
-            for script_name, commands in config.items():
-                commands[:] = expand_script_commands(self.name, script_name, commands, config, seen, active)
-
-            self._scripts = config
-
-        return self._scripts
+        This should return information about how to locate the environment.
+        """
+
+    @abstractmethod
+    def create(self):
+        """
+        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+        This should perform the necessary steps to set up the environment.
+        """
 
-    @property
-    def pre_install_commands(self):
-        if self._pre_install_commands is None:
-            pre_install_commands = self.config.get('pre-install-commands', [])
-            if not isinstance(pre_install_commands, list):
-                message = f'Field `tool.hatch.envs.{self.name}.pre-install-commands` must be an array'
-                raise TypeError(message)
-
-            for i, command in enumerate(pre_install_commands, 1):
-                if not isinstance(command, str):
-                    message = (
-                        f'Command #{i} of field `tool.hatch.envs.{self.name}.pre-install-commands` must be a string'
-                    )
-                    raise TypeError(message)
-
-            self._pre_install_commands = list(pre_install_commands)
-
-        return self._pre_install_commands
+    @abstractmethod
+    def remove(self):
+        """
+        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+        This should perform the necessary steps to completely remove the environment from the system and will only
+        be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or
+        [`env prune`](../../cli/reference.md#hatch-env-prune) commands.
+
+        If the
+        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
+        has a caching mechanism, this should remove that as well.
+        """
+
+    @abstractmethod
+    def exists(self) -> bool:
+        """
+        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
 
-    @property
-    def post_install_commands(self):
-        if self._post_install_commands is None:
-            post_install_commands = self.config.get('post-install-commands', [])
-            if not isinstance(post_install_commands, list):
-                message = f'Field `tool.hatch.envs.{self.name}.post-install-commands` must be an array'
-                raise TypeError(message)
+        This should indicate whether or not the environment has already been created.
+        """
+
+    @abstractmethod
+    def install_project(self):
+        """
+        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
 
-            for i, command in enumerate(post_install_commands, 1):
-                if not isinstance(command, str):
-                    message = (
-                        f'Command #{i} of field `tool.hatch.envs.{self.name}.post-install-commands` must be a string'
-                    )
-                    raise TypeError(message)
-
-            self._post_install_commands = list(post_install_commands)
-
-        return self._post_install_commands
-
-    def activate(self):
-        """
-        A convenience method called when using the environment as a context manager:
-
-        ```python
-        with environment:
-            ...
-        ```
+        This should install the project in the environment.
+        """
+
+    @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.
+        """
+
+    @abstractmethod
+    def dependencies_in_sync(self) -> bool:
+        """
+        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+        This should indicate whether or not the environment is compatible with the current
+        [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies).
         """
 
-    def deactivate(self):
-        """
-        A convenience method called after using the environment as a context manager:
-
-        ```python
-        with environment:
-            ...
-        ```
+    @abstractmethod
+    def sync_dependencies(self):
+        """
+        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+        This should install the
+        [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies)
+        in the environment.
         """
 
-    @abstractmethod
-    def find(self):
+    @contextmanager
+    def build_environment(self, dependencies: list[str]):
         """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-        This should return information about how to locate the environment.
-        """
-
-    @abstractmethod
-    def create(self):
-        """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-        This should perform the necessary steps to set up the environment.
-        """
-
-    @abstractmethod
-    def remove(self):
-        """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-        This should perform the necessary steps to completely remove the environment from the system and will only
-        be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or
-        [`env prune`](../../cli/reference.md#hatch-env-prune) commands.
+        This should set up an isolated environment in which to [`build`](../../cli/reference.md#hatch-build) the project
+        given a set of dependencies and must be a context manager:
+
+        ```python
+        with environment.build_environment([...]):
+            ...
+        ```
+
+        The build environment should reflect any
+        [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)
+        the user defined either currently or at the time of
+        [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).
+        """
+        with self.get_env_vars():
+            yield
+
+    def get_build_process(self, build_environment, **kwargs):
+        """
+        This will be called when the
+        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
+        is active:
 
-        If the
-        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
-        has a caching mechanism, this should remove that as well.
-        """
+        ```python
+        with environment.build_environment([...]) as build_environment:
+            build_process = environment.get_build_process(build_environment, ...)
+        ```
 
-    @abstractmethod
-    def exists(self) -> bool:
-        """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+        This should return the standard library's
+        [subprocess.Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
+        with all output captured by `stdout`. The command is constructed by passing all keyword arguments to
+        [construct_build_command](reference.md#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command).
 
-        This should indicate whether or not the environment has already been created.
+        For an example, open the default implementation below:
         """
-
-    @abstractmethod
-    def install_project(self):
+        return self.platform.capture_process(self.construct_build_command(**kwargs))
+
+    def build_environment_exists(self):
         """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-        This should install the project in the environment.
+        If the
+        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
+        has a caching mechanism, this should indicate whether or not it has already been created.
         """
-
-    @abstractmethod
-    def install_project_dev_mode(self):
+        return False
+
+    def enter_shell(self, name: str, path: str, args: Iterable[str]):
         """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+        Spawn a [shell](../../config/hatch.md#shell) within the environment.
 
-        This should install the project in the environment such that the environment
-        always reflects the current state of the project.
-        """
-
-    @abstractmethod
-    def dependencies_in_sync(self) -> bool:
-        """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-        This should indicate whether or not the environment is compatible with the current
-        [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies).
-        """
-
-    @abstractmethod
-    def sync_dependencies(self):
-        """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+        This should either use
+        [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)
+        directly or provide the same guarantee.
+        """
+        with self.command_context():
+            self.platform.exit_with_command([path, *args])
+
+    def run_shell_command(self, command: str, **kwargs):
+        """
+        This should return the standard library's
+        [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess)
+        and will always be called when the
+        [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)
+        is active, with the expectation of providing the same guarantee.
+        """
+        kwargs.setdefault('shell', True)
+        return self.platform.run_command(command, **kwargs)
 
-        This should install the
-        [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies)
-        in the environment.
-        """
-
-    @contextmanager
-    def build_environment(self, dependencies: list[str]):
-        """
-        This should set up an isolated environment in which to [`build`](../../cli/reference.md#hatch-build) the project
-        given a set of dependencies and must be a context manager:
-
-        ```python
-        with environment.build_environment([...]):
-            ...
-        ```
-
-        The build environment should reflect any
-        [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)
-        the user defined either currently or at the time of
-        [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).
-        """
-        with self.get_env_vars():
-            yield
+    @contextmanager
+    def command_context(self):
+        """
+        A context manager that when active should make executed shell commands reflect any
+        [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)
+        the user defined either currently or at the time of
+        [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).
+
+        For an example, open the default implementation below:
+        """
+        with self.get_env_vars():
+            yield
+
+    def resolve_commands(self, commands: list[str]):
+        """
+        This expands each command into one or more commands based on any
+        [scripts](../../config/environment/overview.md#scripts) that the user defined.
+        """
+        for command in commands:
+            yield from self.expand_command(command)
+
+    def expand_command(self, command):
+        possible_script, args, ignore_exit_code = parse_script_command(command)
 
-    def get_build_process(self, build_environment, **kwargs):
-        """
-        This will be called when the
-        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
-        is active:
-
-        ```python
-        with environment.build_environment([...]) as build_environment:
-            build_process = environment.get_build_process(build_environment, ...)
-        ```
+        # Indicate undefined
+        if not args:
+            args = None
+
+        with self.apply_context():
+            if possible_script in self.scripts:
+                for cmd in self.scripts[possible_script]:
+                    yield self.metadata.context.format(cmd, args=args).strip()
+            else:
+                yield self.metadata.context.format(command, args=args).strip()
 
-        This should return the standard library's
-        [subprocess.Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
-        with all output captured by `stdout`. The command is constructed by passing all keyword arguments to
-        [construct_build_command](reference.md#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command).
-
-        For an example, open the default implementation below:
-        """
-        return self.platform.capture_process(self.construct_build_command(**kwargs))
-
-    def build_environment_exists(self):
-        """
-        If the
-        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
-        has a caching mechanism, this should indicate whether or not it has already been created.
+    def construct_build_command(
+        self,
+        *,
+        directory=None,
+        targets=(),
+        hooks_only=False,
+        no_hooks=False,
+        clean=False,
+        clean_hooks_after=False,
+        clean_only=False,
+    ):
+        """
+        This is the canonical way [`build`](../../cli/reference.md#hatch-build) command options are translated to
+        a subprocess command issued to [builders](../builder/reference.md).
         """
-        return False
+        command = ['python', '-u', '-m', 'hatchling', 'build', '--app']
 
-    def enter_shell(self, name: str, path: str, args: Iterable[str]):
-        """
-        Spawn a [shell](../../config/hatch.md#shell) within the environment.
-
-        This should either use
-        [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)
-        directly or provide the same guarantee.
-        """
-        with self.command_context():
-            self.platform.exit_with_command([path, *args])
-
-    def run_shell_command(self, command: str, **kwargs):
-        """
-        This should return the standard library's
-        [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess)
-        and will always be called when the
-        [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)
-        is active, with the expectation of providing the same guarantee.
-        """
-        kwargs.setdefault('shell', True)
-        return self.platform.run_command(command, **kwargs)
+        if directory:
+            command.extend(('--directory', directory))
+
+        if targets:
+            for target in targets:
+                command.extend(('--target', target))
+
+        if hooks_only:
+            command.append('--hooks-only')
+
+        if no_hooks:
+            command.append('--no-hooks')
+
+        if clean:
+            command.append('--clean')
+
+        if clean_hooks_after:
+            command.append('--clean-hooks-after')
+
+        if clean_only:
+            command.append('--clean-only')
 
-    @contextmanager
-    def command_context(self):
-        """
-        A context manager that when active should make executed shell commands reflect any
-        [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)
-        the user defined either currently or at the time of
-        [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).
-
-        For an example, open the default implementation below:
-        """
-        with self.get_env_vars():
-            yield
-
-    def resolve_commands(self, commands: list[str]):
-        """
-        This expands each command into one or more commands based on any
-        [scripts](../../config/environment/overview.md#scripts) that the user defined.
-        """
-        for command in commands:
-            yield from self.expand_command(command)
-
-    def expand_command(self, command):
-        possible_script, args, ignore_exit_code = parse_script_command(command)
-
-        # Indicate undefined
-        if not args:
-            args = None
-
-        with self.apply_context():
-            if possible_script in self.scripts:
-                for cmd in self.scripts[possible_script]:
-                    yield self.metadata.context.format(cmd, args=args).strip()
-            else:
-                yield self.metadata.context.format(command, args=args).strip()
-
-    def construct_build_command(
-        self,
-        *,
-        directory=None,
-        targets=(),
-        hooks_only=False,
-        no_hooks=False,
-        clean=False,
-        clean_hooks_after=False,
-        clean_only=False,
-    ):
-        """
-        This is the canonical way [`build`](../../cli/reference.md#hatch-build) command options are translated to
-        a subprocess command issued to [builders](../builder/reference.md).
-        """
-        command = ['python', '-u', '-m', 'hatchling', 'build', '--app']
-
-        if directory:
-            command.extend(('--directory', directory))
-
-        if targets:
-            for target in targets:
-                command.extend(('--target', target))
+        return command
+
+    def construct_pip_install_command(self, args: list[str]):
+        """
+        A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/)
+        command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.
+        """
+        command = ['python', '-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-python-version-warning']
+
+        # Default to -1 verbosity
+        add_verbosity_flag(command, self.verbosity, adjustment=-1)
+
+        command.extend(args)
+        return command
+
+    def join_command_args(self, args: list[str]):
+        """
+        This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string
+        from the received arguments.
+        """
+        return self.platform.join_command_args(args)
+
+    def apply_features(self, requirement: str):
+        """
+        A convenience method that applies any user defined [features](../../config/environment/overview.md#features)
+        to the given requirement.
+        """
+        if self.features:
+            features = ','.join(self.features)
+            return f'{requirement}[{features}]'
+
+        return requirement
+
+    def check_compatibility(self):
+        """
+        This raises an exception if the environment is not compatible with the user's setup. The default behavior
+        checks for [platform compatibility](../../config/environment/overview.md#supported-platforms)
+        and any method override should keep this check.
+        """
+        if self.platforms and self.platform.name not in self.platforms:
+            message = 'unsupported platform'
+            raise OSError(message)
+
+    def get_env_vars(self) -> EnvVars:
+        """
+        Returns a mapping of environment variables that should be available to the environment. The object can
+        be used as a context manager to temporarily apply the environment variables to the current process.
+
+        !!! note
+            The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment.
+        """
+        return EnvVars(self.env_vars, self.env_include, self.env_exclude)
+
+    def get_env_var_option(self, option: str) -> str:
+        """
+        Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`.
+        """
+        return os.environ.get(f'{AppEnvVars.ENV_OPTION_PREFIX}{self.PLUGIN_NAME}_{option}'.upper(), '')
 
-        if hooks_only:
-            command.append('--hooks-only')
-
-        if no_hooks:
-            command.append('--no-hooks')
-
-        if clean:
-            command.append('--clean')
+    def get_context(self):
+        """
+        Returns a subclass of
+        [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter).
+        """
+        from hatch.env.context import EnvironmentContextFormatter
+
+        return EnvironmentContextFormatter(self)
 
-        if clean_hooks_after:
-            command.append('--clean-hooks-after')
-
-        if clean_only:
-            command.append('--clean-only')
-
-        return command
+    @staticmethod
+    def get_option_types() -> dict:
+        """
+        Returns a mapping of supported options to their respective types so that they can be used by
+        [overrides](../../config/environment/advanced.md#option-overrides).
+        """
+        return {}
 
-    def construct_pip_install_command(self, args: list[str]):
-        """
-        A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/)
-        command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.
-        """
-        command = ['python', '-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-python-version-warning']
-
-        # Default to -1 verbosity
-        add_verbosity_flag(command, self.verbosity, adjustment=-1)
-
-        command.extend(args)
-        return command
-
-    def join_command_args(self, args: list[str]):
-        """
-        This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string
-        from the received arguments.
-        """
-        return self.platform.join_command_args(args)
-
-    def apply_features(self, requirement: str):
-        """
-        A convenience method that applies any user defined [features](../../config/environment/overview.md#features)
-        to the given requirement.
-        """
-        if self.features:
-            features = ','.join(self.features)
-            return f'{requirement}[{features}]'
-
-        return requirement
-
-    def check_compatibility(self):
-        """
-        This raises an exception if the environment is not compatible with the user's setup. The default behavior
-        checks for [platform compatibility](../../config/environment/overview.md#supported-platforms)
-        and any method override should keep this check.
-        """
-        if self.platforms and self.platform.name not in self.platforms:
-            message = 'unsupported platform'
-            raise OSError(message)
-
-    def get_env_vars(self) -> EnvVars:
-        """
-        Returns a mapping of environment variables that should be available to the environment. The object can
-        be used as a context manager to temporarily apply the environment variables to the current process.
-
-        !!! note
-            The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment.
-        """
-        return EnvVars(self.env_vars, self.env_include, self.env_exclude)
-
-    def get_env_var_option(self, option: str) -> str:
-        """
-        Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`.
-        """
-        return os.environ.get(f'{AppEnvVars.ENV_OPTION_PREFIX}{self.PLUGIN_NAME}_{option}'.upper(), '')
-
-    def get_context(self):
-        """
-        Returns a subclass of
-        [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter).
-        """
-        from hatch.env.context import EnvironmentContextFormatter
-
-        return EnvironmentContextFormatter(self)
-
-    @staticmethod
-    def get_option_types() -> dict:
-        """
-        Returns a mapping of supported options to their respective types so that they can be used by
-        [overrides](../../config/environment/advanced.md#option-overrides).
-        """
-        return {}
-
-    @contextmanager
-    def apply_context(self):
-        with self.get_env_vars(), self.metadata.context.apply_context(self.context):
-            yield
-
-    def __enter__(self):
-        self.activate()
-        return self
-
-    def __exit__(self, exc_type, exc_value, traceback):
-        self.deactivate()
+    @contextmanager
+    def apply_context(self):
+        with self.get_env_vars(), self.metadata.context.apply_context(self.context):
+            yield
+
+    def __enter__(self):
+        self.activate()
+        return self
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        self.deactivate()
 

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

app property

An instance of Application.

root property

The root of the project tree as a path-like object.

name: str property

The name of the environment.

data_directory property

The directory this plugin should use for storage as a path-like object. If the user has not configured one then this will be the same as the isolated data directory.

isolated_data_directory property

The default directory reserved exclusively for this plugin as a path-like object.

config: dict property

[tool.hatch.envs.<ENV_NAME>]
 
[envs.<ENV_NAME>]
 

platform property

An instance of Platform.

environment_dependencies: list[str] property

The list of all environment dependencies.

dependencies: list[str] property

env_vars: dict property

[tool.hatch.envs.<ENV_NAME>.env-vars]
@@ -1015,283 +941,283 @@
 description = ...
 

activate()

A convenience method called when using the environment as a context manager:

with environment:
     ...
-
Source code in src/hatch/env/plugin/interface.py
def activate(self):
-    """
-    A convenience method called when using the environment as a context manager:
-
-    ```python
-    with environment:
-        ...
-    ```
-    """
+
Source code in src/hatch/env/plugin/interface.py
def activate(self):
+    """
+    A convenience method called when using the environment as a context manager:
+
+    ```python
+    with environment:
+        ...
+    ```
+    """
 

deactivate()

A convenience method called after using the environment as a context manager:

with environment:
     ...
-
Source code in src/hatch/env/plugin/interface.py
def deactivate(self):
-    """
-    A convenience method called after using the environment as a context manager:
-
-    ```python
-    with environment:
-        ...
-    ```
+
Source code in src/hatch/env/plugin/interface.py
def deactivate(self):
+    """
+    A convenience method called after using the environment as a context manager:
+
+    ```python
+    with environment:
+        ...
+    ```
+    """
+

find() abstractmethod

REQUIRED

This should return information about how to locate the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
+def find(self):
+    """
+    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+    This should return information about how to locate the environment.
+    """
+

create() abstractmethod

REQUIRED

This should perform the necessary steps to set up the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
+def create(self):
+    """
+    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+    This should perform the necessary steps to set up the environment.
+    """
+

remove() abstractmethod

REQUIRED

This should perform the necessary steps to completely remove the environment from the system and will only be triggered manually by users with the env remove or env prune commands.

If the build environment has a caching mechanism, this should remove that as well.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
+def remove(self):
+    """
+    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+    This should perform the necessary steps to completely remove the environment from the system and will only
+    be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or
+    [`env prune`](../../cli/reference.md#hatch-env-prune) commands.
+
+    If the
+    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
+    has a caching mechanism, this should remove that as well.
+    """
+

exists() -> bool abstractmethod

REQUIRED

This should indicate whether or not the environment has already been created.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
+def exists(self) -> bool:
+    """
+    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+    This should indicate whether or not the environment has already been created.
+    """
+

install_project() abstractmethod

REQUIRED

This should install the project in the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
+def install_project(self):
+    """
+    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+    This should install the project in the environment.
+    """
+

install_project_dev_mode() abstractmethod

REQUIRED

This should install the project in the environment such that the environment always reflects the current state of the project.

Source code in src/hatch/env/plugin/interface.py
@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.
+    """
+

dependencies_in_sync() -> bool abstractmethod

REQUIRED

This should indicate whether or not the environment is compatible with the current dependencies.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
+def dependencies_in_sync(self) -> bool:
+    """
+    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+    This should indicate whether or not the environment is compatible with the current
+    [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies).
+    """
+

sync_dependencies() abstractmethod

REQUIRED

This should install the dependencies in the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
+def sync_dependencies(self):
+    """
+    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+    This should install the
+    [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies)
+    in the environment.
     """
-

find() abstractmethod

REQUIRED

This should return information about how to locate the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
-def find(self):
+

build_environment(dependencies: list[str])

This should set up an isolated environment in which to build the project given a set of dependencies and must be a context manager:

with environment.build_environment([...]):
+    ...
+

The build environment should reflect any environment variables the user defined either currently or at the time of creation.

Source code in src/hatch/env/plugin/interface.py
@contextmanager
+def build_environment(self, dependencies: list[str]):
     """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-    This should return information about how to locate the environment.
-    """
-

create() abstractmethod

REQUIRED

This should perform the necessary steps to set up the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
-def create(self):
-    """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-    This should perform the necessary steps to set up the environment.
-    """
-

remove() abstractmethod

REQUIRED

This should perform the necessary steps to completely remove the environment from the system and will only be triggered manually by users with the env remove or env prune commands.

If the build environment has a caching mechanism, this should remove that as well.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
-def remove(self):
-    """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-    This should perform the necessary steps to completely remove the environment from the system and will only
-    be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or
-    [`env prune`](../../cli/reference.md#hatch-env-prune) commands.
+    This should set up an isolated environment in which to [`build`](../../cli/reference.md#hatch-build) the project
+    given a set of dependencies and must be a context manager:
+
+    ```python
+    with environment.build_environment([...]):
+        ...
+    ```
+
+    The build environment should reflect any
+    [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)
+    the user defined either currently or at the time of
+    [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).
+    """
+    with self.get_env_vars():
+        yield
+

build_environment_exists()

If the build environment has a caching mechanism, this should indicate whether or not it has already been created.

Source code in src/hatch/env/plugin/interface.py
def build_environment_exists(self):
+    """
+    If the
+    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
+    has a caching mechanism, this should indicate whether or not it has already been created.
+    """
+    return False
+

get_build_process(build_environment, **kwargs)

This will be called when the build environment is active:

with environment.build_environment([...]) as build_environment:
+    build_process = environment.get_build_process(build_environment, ...)
+

This should return the standard library's subprocess.Popen with all output captured by stdout. The command is constructed by passing all keyword arguments to construct_build_command.

For an example, open the default implementation below:

Source code in src/hatch/env/plugin/interface.py
def get_build_process(self, build_environment, **kwargs):
+    """
+    This will be called when the
+    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
+    is active:
 
-    If the
-    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
-    has a caching mechanism, this should remove that as well.
-    """
-

exists() -> bool abstractmethod

REQUIRED

This should indicate whether or not the environment has already been created.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
-def exists(self) -> bool:
-    """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+    ```python
+    with environment.build_environment([...]) as build_environment:
+        build_process = environment.get_build_process(build_environment, ...)
+    ```
+
+    This should return the standard library's
+    [subprocess.Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
+    with all output captured by `stdout`. The command is constructed by passing all keyword arguments to
+    [construct_build_command](reference.md#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command).
 
-    This should indicate whether or not the environment has already been created.
+    For an example, open the default implementation below:
     """
-

install_project() abstractmethod

REQUIRED

This should install the project in the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
-def install_project(self):
-    """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-    This should install the project in the environment.
-    """
-

install_project_dev_mode() abstractmethod

REQUIRED

This should install the project in the environment such that the environment always reflects the current state of the project.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
-def install_project_dev_mode(self):
+    return self.platform.capture_process(self.construct_build_command(**kwargs))
+

construct_build_command(*, directory = None, targets = (), hooks_only = False, no_hooks = False, clean = False, clean_hooks_after = False, clean_only = False)

This is the canonical way build command options are translated to a subprocess command issued to builders.

Source code in src/hatch/env/plugin/interface.py
def construct_build_command(
+    self,
+    *,
+    directory=None,
+    targets=(),
+    hooks_only=False,
+    no_hooks=False,
+    clean=False,
+    clean_hooks_after=False,
+    clean_only=False,
+):
+    """
+    This is the canonical way [`build`](../../cli/reference.md#hatch-build) command options are translated to
+    a subprocess command issued to [builders](../builder/reference.md).
+    """
+    command = ['python', '-u', '-m', 'hatchling', 'build', '--app']
+
+    if directory:
+        command.extend(('--directory', directory))
+
+    if targets:
+        for target in targets:
+            command.extend(('--target', target))
+
+    if hooks_only:
+        command.append('--hooks-only')
+
+    if no_hooks:
+        command.append('--no-hooks')
+
+    if clean:
+        command.append('--clean')
+
+    if clean_hooks_after:
+        command.append('--clean-hooks-after')
+
+    if clean_only:
+        command.append('--clean-only')
+
+    return command
+

command_context()

A context manager that when active should make executed shell commands reflect any environment variables the user defined either currently or at the time of creation.

For an example, open the default implementation below:

Source code in src/hatch/env/plugin/interface.py
@contextmanager
+def command_context(self):
+    """
+    A context manager that when active should make executed shell commands reflect any
+    [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)
+    the user defined either currently or at the time of
+    [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).
+
+    For an example, open the default implementation below:
+    """
+    with self.get_env_vars():
+        yield
+

enter_shell(name: str, path: str, args: Iterable[str])

Spawn a shell within the environment.

This should either use command_context directly or provide the same guarantee.

Source code in src/hatch/env/plugin/interface.py
def enter_shell(self, name: str, path: str, args: Iterable[str]):
     """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+    Spawn a [shell](../../config/hatch.md#shell) within the environment.
 
-    This should install the project in the environment such that the environment
-    always reflects the current state of the project.
-    """
-

dependencies_in_sync() -> bool abstractmethod

REQUIRED

This should indicate whether or not the environment is compatible with the current dependencies.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
-def dependencies_in_sync(self) -> bool:
-    """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-    This should indicate whether or not the environment is compatible with the current
-    [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies).
-    """
-

sync_dependencies() abstractmethod

REQUIRED

This should install the dependencies in the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod
-def sync_dependencies(self):
-    """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-    This should install the
-    [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies)
-    in the environment.
-    """
-

build_environment(dependencies: list[str])

This should set up an isolated environment in which to build the project given a set of dependencies and must be a context manager:

with environment.build_environment([...]):
-    ...
-

The build environment should reflect any environment variables the user defined either currently or at the time of creation.

Source code in src/hatch/env/plugin/interface.py
@contextmanager
-def build_environment(self, dependencies: list[str]):
-    """
-    This should set up an isolated environment in which to [`build`](../../cli/reference.md#hatch-build) the project
-    given a set of dependencies and must be a context manager:
-
-    ```python
-    with environment.build_environment([...]):
-        ...
-    ```
-
-    The build environment should reflect any
-    [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)
-    the user defined either currently or at the time of
-    [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).
-    """
-    with self.get_env_vars():
-        yield
-

build_environment_exists()

If the build environment has a caching mechanism, this should indicate whether or not it has already been created.

Source code in src/hatch/env/plugin/interface.py
def build_environment_exists(self):
-    """
-    If the
-    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
-    has a caching mechanism, this should indicate whether or not it has already been created.
-    """
-    return False
-

get_build_process(build_environment, **kwargs)

This will be called when the build environment is active:

with environment.build_environment([...]) as build_environment:
-    build_process = environment.get_build_process(build_environment, ...)
-

This should return the standard library's subprocess.Popen with all output captured by stdout. The command is constructed by passing all keyword arguments to construct_build_command.

For an example, open the default implementation below:

Source code in src/hatch/env/plugin/interface.py
def get_build_process(self, build_environment, **kwargs):
-    """
-    This will be called when the
-    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)
-    is active:
-
-    ```python
-    with environment.build_environment([...]) as build_environment:
-        build_process = environment.get_build_process(build_environment, ...)
-    ```
-
-    This should return the standard library's
-    [subprocess.Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
-    with all output captured by `stdout`. The command is constructed by passing all keyword arguments to
-    [construct_build_command](reference.md#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command).
-
-    For an example, open the default implementation below:
-    """
-    return self.platform.capture_process(self.construct_build_command(**kwargs))
-

construct_build_command(*, directory = None, targets = (), hooks_only = False, no_hooks = False, clean = False, clean_hooks_after = False, clean_only = False)

This is the canonical way build command options are translated to a subprocess command issued to builders.

Source code in src/hatch/env/plugin/interface.py
def construct_build_command(
-    self,
-    *,
-    directory=None,
-    targets=(),
-    hooks_only=False,
-    no_hooks=False,
-    clean=False,
-    clean_hooks_after=False,
-    clean_only=False,
-):
-    """
-    This is the canonical way [`build`](../../cli/reference.md#hatch-build) command options are translated to
-    a subprocess command issued to [builders](../builder/reference.md).
-    """
-    command = ['python', '-u', '-m', 'hatchling', 'build', '--app']
-
-    if directory:
-        command.extend(('--directory', directory))
-
-    if targets:
-        for target in targets:
-            command.extend(('--target', target))
-
-    if hooks_only:
-        command.append('--hooks-only')
-
-    if no_hooks:
-        command.append('--no-hooks')
-
-    if clean:
-        command.append('--clean')
-
-    if clean_hooks_after:
-        command.append('--clean-hooks-after')
-
-    if clean_only:
-        command.append('--clean-only')
-
-    return command
-

command_context()

A context manager that when active should make executed shell commands reflect any environment variables the user defined either currently or at the time of creation.

For an example, open the default implementation below:

Source code in src/hatch/env/plugin/interface.py
@contextmanager
-def command_context(self):
-    """
-    A context manager that when active should make executed shell commands reflect any
-    [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)
-    the user defined either currently or at the time of
-    [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).
-
-    For an example, open the default implementation below:
-    """
-    with self.get_env_vars():
-        yield
-

enter_shell(name: str, path: str, args: Iterable[str])

Spawn a shell within the environment.

This should either use command_context directly or provide the same guarantee.

Source code in src/hatch/env/plugin/interface.py
def enter_shell(self, name: str, path: str, args: Iterable[str]):
-    """
-    Spawn a [shell](../../config/hatch.md#shell) within the environment.
-
-    This should either use
-    [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)
-    directly or provide the same guarantee.
-    """
-    with self.command_context():
-        self.platform.exit_with_command([path, *args])
-

run_shell_command(command: str, **kwargs: str)

This should return the standard library's subprocess.CompletedProcess and will always be called when the command_context is active, with the expectation of providing the same guarantee.

Source code in src/hatch/env/plugin/interface.py
def run_shell_command(self, command: str, **kwargs):
-    """
-    This should return the standard library's
-    [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess)
-    and will always be called when the
-    [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)
-    is active, with the expectation of providing the same guarantee.
-    """
-    kwargs.setdefault('shell', True)
-    return self.platform.run_command(command, **kwargs)
-

resolve_commands(commands: list[str])

This expands each command into one or more commands based on any scripts that the user defined.

Source code in src/hatch/env/plugin/interface.py
def resolve_commands(self, commands: list[str]):
-    """
-    This expands each command into one or more commands based on any
-    [scripts](../../config/environment/overview.md#scripts) that the user defined.
-    """
-    for command in commands:
-        yield from self.expand_command(command)
-

get_env_vars() -> EnvVars

Returns a mapping of environment variables that should be available to the environment. The object can be used as a context manager to temporarily apply the environment variables to the current process.

Note

The environment variable HATCH_ENV_ACTIVE will always be set to the name of the environment.

Source code in src/hatch/env/plugin/interface.py
def get_env_vars(self) -> EnvVars:
-    """
-    Returns a mapping of environment variables that should be available to the environment. The object can
-    be used as a context manager to temporarily apply the environment variables to the current process.
-
-    !!! note
-        The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment.
-    """
-    return EnvVars(self.env_vars, self.env_include, self.env_exclude)
-

apply_features(requirement: str)

A convenience method that applies any user defined features to the given requirement.

Source code in src/hatch/env/plugin/interface.py
def apply_features(self, requirement: str):
-    """
-    A convenience method that applies any user defined [features](../../config/environment/overview.md#features)
-    to the given requirement.
-    """
-    if self.features:
-        features = ','.join(self.features)
-        return f'{requirement}[{features}]'
-
-    return requirement
-

construct_pip_install_command(args: list[str])

A convenience method for constructing a pip install command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.

Source code in src/hatch/env/plugin/interface.py
def construct_pip_install_command(self, args: list[str]):
-    """
-    A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/)
-    command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.
-    """
-    command = ['python', '-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-python-version-warning']
-
-    # Default to -1 verbosity
-    add_verbosity_flag(command, self.verbosity, adjustment=-1)
-
-    command.extend(args)
-    return command
-

join_command_args(args: list[str])

This is used by the run command to construct the root command string from the received arguments.

Source code in src/hatch/env/plugin/interface.py
def join_command_args(self, args: list[str]):
-    """
-    This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string
-    from the received arguments.
-    """
-    return self.platform.join_command_args(args)
-

check_compatibility()

This raises an exception if the environment is not compatible with the user's setup. The default behavior checks for platform compatibility and any method override should keep this check.

Source code in src/hatch/env/plugin/interface.py
def check_compatibility(self):
-    """
-    This raises an exception if the environment is not compatible with the user's setup. The default behavior
-    checks for [platform compatibility](../../config/environment/overview.md#supported-platforms)
-    and any method override should keep this check.
-    """
-    if self.platforms and self.platform.name not in self.platforms:
-        message = 'unsupported platform'
-        raise OSError(message)
-

get_option_types() -> dict staticmethod

Returns a mapping of supported options to their respective types so that they can be used by overrides.

Source code in src/hatch/env/plugin/interface.py
@staticmethod
-def get_option_types() -> dict:
-    """
-    Returns a mapping of supported options to their respective types so that they can be used by
-    [overrides](../../config/environment/advanced.md#option-overrides).
-    """
-    return {}
-

get_env_var_option(option: str) -> str

Returns the value of the upper-cased environment variable HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>.

Source code in src/hatch/env/plugin/interface.py
def get_env_var_option(self, option: str) -> str:
-    """
-    Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`.
-    """
-    return os.environ.get(f'{AppEnvVars.ENV_OPTION_PREFIX}{self.PLUGIN_NAME}_{option}'.upper(), '')
-

get_context()

Returns a subclass of EnvironmentContextFormatter.

Source code in src/hatch/env/plugin/interface.py
def get_context(self):
-    """
-    Returns a subclass of
-    [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter).
-    """
-    from hatch.env.context import EnvironmentContextFormatter
-
-    return EnvironmentContextFormatter(self)
-
\ No newline at end of file + This should either use + [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context) + directly or provide the same guarantee. + """ + with self.command_context(): + self.platform.exit_with_command([path, *args]) +

run_shell_command(command: str, **kwargs: str)

This should return the standard library's subprocess.CompletedProcess and will always be called when the command_context is active, with the expectation of providing the same guarantee.

Source code in src/hatch/env/plugin/interface.py
def run_shell_command(self, command: str, **kwargs):
+    """
+    This should return the standard library's
+    [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess)
+    and will always be called when the
+    [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)
+    is active, with the expectation of providing the same guarantee.
+    """
+    kwargs.setdefault('shell', True)
+    return self.platform.run_command(command, **kwargs)
+

resolve_commands(commands: list[str])

This expands each command into one or more commands based on any scripts that the user defined.

Source code in src/hatch/env/plugin/interface.py
def resolve_commands(self, commands: list[str]):
+    """
+    This expands each command into one or more commands based on any
+    [scripts](../../config/environment/overview.md#scripts) that the user defined.
+    """
+    for command in commands:
+        yield from self.expand_command(command)
+

get_env_vars() -> EnvVars

Returns a mapping of environment variables that should be available to the environment. The object can be used as a context manager to temporarily apply the environment variables to the current process.

Note

The environment variable HATCH_ENV_ACTIVE will always be set to the name of the environment.

Source code in src/hatch/env/plugin/interface.py
def get_env_vars(self) -> EnvVars:
+    """
+    Returns a mapping of environment variables that should be available to the environment. The object can
+    be used as a context manager to temporarily apply the environment variables to the current process.
+
+    !!! note
+        The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment.
+    """
+    return EnvVars(self.env_vars, self.env_include, self.env_exclude)
+

apply_features(requirement: str)

A convenience method that applies any user defined features to the given requirement.

Source code in src/hatch/env/plugin/interface.py
def apply_features(self, requirement: str):
+    """
+    A convenience method that applies any user defined [features](../../config/environment/overview.md#features)
+    to the given requirement.
+    """
+    if self.features:
+        features = ','.join(self.features)
+        return f'{requirement}[{features}]'
+
+    return requirement
+

construct_pip_install_command(args: list[str])

A convenience method for constructing a pip install command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.

Source code in src/hatch/env/plugin/interface.py
def construct_pip_install_command(self, args: list[str]):
+    """
+    A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/)
+    command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.
+    """
+    command = ['python', '-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-python-version-warning']
+
+    # Default to -1 verbosity
+    add_verbosity_flag(command, self.verbosity, adjustment=-1)
+
+    command.extend(args)
+    return command
+

join_command_args(args: list[str])

This is used by the run command to construct the root command string from the received arguments.

Source code in src/hatch/env/plugin/interface.py
def join_command_args(self, args: list[str]):
+    """
+    This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string
+    from the received arguments.
+    """
+    return self.platform.join_command_args(args)
+

check_compatibility()

This raises an exception if the environment is not compatible with the user's setup. The default behavior checks for platform compatibility and any method override should keep this check.

Source code in src/hatch/env/plugin/interface.py
def check_compatibility(self):
+    """
+    This raises an exception if the environment is not compatible with the user's setup. The default behavior
+    checks for [platform compatibility](../../config/environment/overview.md#supported-platforms)
+    and any method override should keep this check.
+    """
+    if self.platforms and self.platform.name not in self.platforms:
+        message = 'unsupported platform'
+        raise OSError(message)
+

get_option_types() -> dict staticmethod

Returns a mapping of supported options to their respective types so that they can be used by overrides.

Source code in src/hatch/env/plugin/interface.py
@staticmethod
+def get_option_types() -> dict:
+    """
+    Returns a mapping of supported options to their respective types so that they can be used by
+    [overrides](../../config/environment/advanced.md#option-overrides).
+    """
+    return {}
+

get_env_var_option(option: str) -> str

Returns the value of the upper-cased environment variable HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>.

Source code in src/hatch/env/plugin/interface.py
def get_env_var_option(self, option: str) -> str:
+    """
+    Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`.
+    """
+    return os.environ.get(f'{AppEnvVars.ENV_OPTION_PREFIX}{self.PLUGIN_NAME}_{option}'.upper(), '')
+

get_context()

Returns a subclass of EnvironmentContextFormatter.

Source code in src/hatch/env/plugin/interface.py
def get_context(self):
+    """
+    Returns a subclass of
+    [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter).
+    """
+    from hatch.env.context import EnvironmentContextFormatter
+
+    return EnvironmentContextFormatter(self)
+
\ No newline at end of file diff --git a/dev/plugins/environment/virtual/index.html b/dev/plugins/environment/virtual/index.html index e2ccd29ae..777281ff3 100644 --- a/dev/plugins/environment/virtual/index.html +++ b/dev/plugins/environment/virtual/index.html @@ -13,4 +13,4 @@ type = "virtual"
[envs.<ENV_NAME>]
 type = "virtual"
-

Options

Option Default Description
system-packages false Whether or not to give the virtual environment access to the system site-packages directory
python The version of Python to find on your system and subsequently use to create the environment, defaulting to the HATCH_PYTHON environment variable, followed by the first Python executable found along your PATH, followed by the Python executable Hatch is running on. Setting the HATCH_PYTHON environment variable to self will force the use of the Python executable Hatch is running on. For more information, see the documentation.
path An explicit path to the virtual environment. The path may be absolute or relative to the project root. Any environments that inherit this option will also use this path. The environment variable HATCH_ENV_TYPE_VIRTUAL_PATH may be used, which will take precedence.

Location

The location of environments is determined in the following heuristic order:

  1. The path option
  2. A directory named after the environment within the configured virtual environment directory if the directory resides somewhere within the project root or if it is set to a .virtualenvs directory within the user's home directory
  3. Otherwise, environments are stored within the configured virtual environment directory in a deeply nested structure in order to support multiple projects

Additionally, when the path option is not used, the name of the directory for the default environment will be the normalized project name to provide a more meaningful default shell prompt.

Troubleshooting

macOS SIP

If you need to set linker environment variables like those starting with DYLD_ or LD_, any executable secured by System Integrity Protection that is invoked when running commands will not see those environment variable modifications as macOS strips those.

Hatch interprets such commands as shell commands but deliberately ignores such paths to protected shells. This workaround suffices for the majority of use cases but there are 2 situations in which it may not:

  1. There are no unprotected sh, bash, zsh, nor fish executables found along PATH.
  2. The desired executable is a project's script, and the location of environments contains spaces or is longer than 1241 characters. In this case pip and other installers will create such an entry point with a shebang pointing to /bin/sh (which is protected) to avoid shebang limitations. Rather than changing the location, you could invoke the script as e.g. python -m pytest (if the project supports that method of invocation by shipping a __main__.py).

  1. The shebang length limit is usually 127 but 3 characters surround the executable path: #!<EXE_PATH>\n 

\ No newline at end of file +

Options

Option Default Description
system-packages false Whether or not to give the virtual environment access to the system site-packages directory
python The version of Python to find on your system and subsequently use to create the environment, defaulting to the HATCH_PYTHON environment variable, followed by the first Python executable found along your PATH, followed by the Python executable Hatch is running on. Setting the HATCH_PYTHON environment variable to self will force the use of the Python executable Hatch is running on. For more information, see the documentation.
path An explicit path to the virtual environment. The path may be absolute or relative to the project root. Any environments that inherit this option will also use this path. The environment variable HATCH_ENV_TYPE_VIRTUAL_PATH may be used, which will take precedence.

Location

The location of environments is determined in the following heuristic order:

  1. The path option
  2. A directory named after the environment within the configured virtual environment directory if the directory resides somewhere within the project root or if it is set to a .virtualenvs directory within the user's home directory
  3. Otherwise, environments are stored within the configured virtual environment directory in a deeply nested structure in order to support multiple projects

Additionally, when the path option is not used, the name of the directory for the default environment will be the normalized project name to provide a more meaningful default shell prompt.

Troubleshooting

macOS SIP

If you need to set linker environment variables like those starting with DYLD_ or LD_, any executable secured by System Integrity Protection that is invoked when running commands will not see those environment variable modifications as macOS strips those.

Hatch interprets such commands as shell commands but deliberately ignores such paths to protected shells. This workaround suffices for the majority of use cases but there are 2 situations in which it may not:

  1. There are no unprotected sh, bash, zsh, nor fish executables found along PATH.
  2. The desired executable is a project's script, and the location of environments contains spaces or is longer than 1241 characters. In this case pip and other installers will create such an entry point with a shebang pointing to /bin/sh (which is protected) to avoid shebang limitations. Rather than changing the location, you could invoke the script as e.g. python -m pytest (if the project supports that method of invocation by shipping a __main__.py).

  1. The shebang length limit is usually 127 but 3 characters surround the executable path: #!<EXE_PATH>\n 

\ No newline at end of file diff --git a/dev/plugins/metadata-hook/custom/index.html b/dev/plugins/metadata-hook/custom/index.html index fb6de5541..1b50736f2 100644 --- a/dev/plugins/metadata-hook/custom/index.html +++ b/dev/plugins/metadata-hook/custom/index.html @@ -11,9 +11,9 @@ body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);}
Skip to content

Custom metadata hook


This is a custom class in a given Python file that inherits from the MetadataHookInterface.

Configuration

The metadata hook plugin name is custom.

[tool.hatch.metadata.hooks.custom]
 
[metadata.hooks.custom]
-

Options

Option Default Description
path hatch_build.py The path of the Python file

Example

from hatchling.metadata.plugin.interface import MetadataHookInterface
+

Options

Option Default Description
path hatch_build.py The path of the Python file

Example

    from hatchling.metadata.plugin.interface import MetadataHookInterface
 
 
-class CustomMetadataHook(MetadataHookInterface):
-    ...
-

If multiple subclasses are found, you must define a function named get_metadata_hook that returns the desired build hook.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

\ No newline at end of file + class CustomMetadataHook(MetadataHookInterface): + ... +

If multiple subclasses are found, you must define a function named get_metadata_hook that returns the desired build hook.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

\ No newline at end of file diff --git a/dev/plugins/metadata-hook/reference/index.html b/dev/plugins/metadata-hook/reference/index.html index 7c7caf4df..dbfb09218 100644 --- a/dev/plugins/metadata-hook/reference/index.html +++ b/dev/plugins/metadata-hook/reference/index.html @@ -27,85 +27,73 @@ """ Example usage: - === ":octicons-file-code-16: plugin.py" - - ```python - from hatchling.metadata.plugin.interface import MetadataHookInterface - - - class SpecialMetadataHook(MetadataHookInterface): - PLUGIN_NAME = 'special' - ... - ``` - - === ":octicons-file-code-16: hooks.py" - - ```python - from hatchling.plugin import hookimpl - - from .plugin import SpecialMetadataHook - - - @hookimpl - def hatch_register_metadata_hook(): - return SpecialMetadataHook - ``` - """ - - PLUGIN_NAME = '' - """The name used for selection.""" + ```python tab="plugin.py" + from hatchling.metadata.plugin.interface import MetadataHookInterface + + + class SpecialMetadataHook(MetadataHookInterface): + PLUGIN_NAME = 'special' + ... + ``` + + ```python tab="hooks.py" + from hatchling.plugin import hookimpl + + from .plugin import SpecialMetadataHook + + + @hookimpl + def hatch_register_metadata_hook(): + return SpecialMetadataHook + ``` + """ + + PLUGIN_NAME = '' + """The name used for selection.""" + + def __init__(self, root: str, config: dict) -> None: + self.__root = root + self.__config = config - def __init__(self, root: str, config: dict) -> None: - self.__root = root - self.__config = config - - @property - def root(self) -> str: - """ - The root of the project tree. - """ - return self.__root - - @property - def config(self) -> dict: - """ - The hook configuration. - - === ":octicons-file-code-16: pyproject.toml" + @property + def root(self) -> str: + """ + The root of the project tree. + """ + return self.__root + + @property + def config(self) -> dict: + """ + The hook configuration. + + ```toml config-example + [tool.hatch.metadata.hooks.<PLUGIN_NAME>] + ``` + """ + return self.__config - ```toml - [tool.hatch.metadata.hooks.<PLUGIN_NAME>] - ``` - - === ":octicons-file-code-16: hatch.toml" + @abstractmethod + def update(self, metadata: dict) -> None: + """ + This updates the metadata mapping of the `project` table in-place. + """ - ```toml - [metadata.hooks.<PLUGIN_NAME>] - ``` + def get_known_classifiers(self) -> list[str]: + """ + This returns extra classifiers that should be considered valid in addition to the ones known to PyPI. """ - return self.__config - - @abstractmethod - def update(self, metadata: dict) -> None: - """ - This updates the metadata mapping of the `project` table in-place. - """ - - def get_known_classifiers(self) -> list[str]: - """ - This returns extra classifiers that should be considered valid in addition to the ones known to PyPI. - """ - return [] + return []

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

root: str property

The root of the project tree.

config: dict property

The hook configuration.

[tool.hatch.metadata.hooks.<PLUGIN_NAME>]
 
[metadata.hooks.<PLUGIN_NAME>]
-

update(metadata: dict) -> None abstractmethod

This updates the metadata mapping of the project table in-place.

Source code in backend/src/hatchling/metadata/plugin/interface.py
@abstractmethod
-def update(self, metadata: dict) -> None:
-    """
-    This updates the metadata mapping of the `project` table in-place.
-    """
-

get_known_classifiers() -> list[str]

This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.

Source code in backend/src/hatchling/metadata/plugin/interface.py
def get_known_classifiers(self) -> list[str]:
-    """
-    This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.
-    """
-    return []
+

update(metadata: dict) -> None abstractmethod

This updates the metadata mapping of the project table in-place.

Source code in backend/src/hatchling/metadata/plugin/interface.py
@abstractmethod
+def update(self, metadata: dict) -> None:
+    """
+    This updates the metadata mapping of the `project` table in-place.
+    """
+

get_known_classifiers() -> list[str]

This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.

Source code in backend/src/hatchling/metadata/plugin/interface.py
def get_known_classifiers(self) -> list[str]:
+    """
+    This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.
+    """
+    return []
 
\ No newline at end of file diff --git a/dev/plugins/publisher/package-index/index.html b/dev/plugins/publisher/package-index/index.html index 690a046b4..b220ae6e6 100644 --- a/dev/plugins/publisher/package-index/index.html +++ b/dev/plugins/publisher/package-index/index.html @@ -15,4 +15,4 @@ [publish.index.repos.test] url = "https://test.pypi.org/legacy/" -

The repo and repos options have no effect.

\ No newline at end of file +

The repo and repos options have no effect.

\ No newline at end of file diff --git a/dev/plugins/publisher/reference/index.html b/dev/plugins/publisher/reference/index.html index 3d2da1be4..52c59fced 100644 --- a/dev/plugins/publisher/reference/index.html +++ b/dev/plugins/publisher/reference/index.html @@ -9,153 +9,139 @@ body[data-md-color-scheme="slate"] .gdesc-inner { background: var(--md-default-bg-color);} body[data-md-color-scheme="slate"] .gslide-title { color: var(--md-default-fg-color);} body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);} -
Skip to content

Publisher plugins


PublisherInterface

Example usage:

from hatch.publish.plugin.interface import PublisherInterface
+                  

Publisher plugins


PublisherInterface

Example usage:

    from hatch.publish.plugin.interface import PublisherInterface
 
 
-class SpecialPublisher(PublisherInterface):
-    PLUGIN_NAME = 'special'
-    ...
-
from hatchling.plugin import hookimpl
+    class SpecialPublisher(PublisherInterface):
+        PLUGIN_NAME = 'special'
+        ...
+
    from hatchling.plugin import hookimpl
 
-from .plugin import SpecialPublisher
+    from .plugin import SpecialPublisher
 
 
-@hookimpl
-def hatch_register_publisher():
-    return SpecialPublisher
+    @hookimpl
+    def hatch_register_publisher():
+        return SpecialPublisher
 
Source code in src/hatch/publish/plugin/interface.py
class PublisherInterface(ABC):
     """
     Example usage:
 
-    === ":octicons-file-code-16: plugin.py"
-
-        ```python
-        from hatch.publish.plugin.interface import PublisherInterface
-
-
-        class SpecialPublisher(PublisherInterface):
-            PLUGIN_NAME = 'special'
-            ...
-        ```
-
-    === ":octicons-file-code-16: hooks.py"
-
-        ```python
-        from hatchling.plugin import hookimpl
-
-        from .plugin import SpecialPublisher
-
-
-        @hookimpl
-        def hatch_register_publisher():
-            return SpecialPublisher
-        ```
-    """
-
-    PLUGIN_NAME = ''
-    """The name used for selection."""
-
-    def __init__(self, app, root, cache_dir, project_config, plugin_config):
-        self.__app = app
-        self.__root = root
-        self.__cache_dir = cache_dir
-        self.__project_config = project_config
-        self.__plugin_config = plugin_config
-
-        self.__disable = None
-
-    @property
-    def app(self):
-        """
-        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).
-        """
-        return self.__app
-
-    @property
-    def root(self):
-        """
-        The root of the project tree as a path-like object.
-        """
-        return self.__root
-
-    @property
-    def cache_dir(self):
-        """
-        The directory reserved exclusively for this plugin as a path-like object.
-        """
-        return self.__cache_dir
-
-    @property
-    def project_config(self) -> dict:
-        """
-        === ":octicons-file-code-16: pyproject.toml"
+    ```python tab="plugin.py"
+        from hatch.publish.plugin.interface import PublisherInterface
+
+
+        class SpecialPublisher(PublisherInterface):
+            PLUGIN_NAME = 'special'
+            ...
+    ```
+
+    ```python tab="hooks.py"
+        from hatchling.plugin import hookimpl
+
+        from .plugin import SpecialPublisher
+
+
+        @hookimpl
+        def hatch_register_publisher():
+            return SpecialPublisher
+    ```
+    """
+
+    PLUGIN_NAME = ''
+    """The name used for selection."""
+
+    def __init__(self, app, root, cache_dir, project_config, plugin_config):
+        self.__app = app
+        self.__root = root
+        self.__cache_dir = cache_dir
+        self.__project_config = project_config
+        self.__plugin_config = plugin_config
+
+        self.__disable = None
+
+    @property
+    def app(self):
+        """
+        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).
+        """
+        return self.__app
+
+    @property
+    def root(self):
+        """
+        The root of the project tree as a path-like object.
+        """
+        return self.__root
+
+    @property
+    def cache_dir(self):
+        """
+        The directory reserved exclusively for this plugin as a path-like object.
+        """
+        return self.__cache_dir
+
+    @property
+    def project_config(self) -> dict:
+        """
+        ```toml config-example
+        [tool.hatch.publish.<PLUGIN_NAME>]
+        ```
+        """
+        return self.__project_config
 
-            ```toml
-            [tool.hatch.publish.<PLUGIN_NAME>]
-            ```
-
-        === ":octicons-file-code-16: hatch.toml"
-
-            ```toml
-            [publish.<PLUGIN_NAME>]
-            ```
-        """
-        return self.__project_config
-
-    @property
-    def plugin_config(self) -> dict:
-        """
-        This is defined in Hatch's [config file](../../config/hatch.md).
-
-        === ":octicons-file-code-16: config.toml"
-
-            ```toml
-            [publish.<PLUGIN_NAME>]
-            ```
-        """
-        return self.__plugin_config
-
-    @property
-    def disable(self):
-        """
-        Whether this plugin is disabled, thus requiring confirmation when publishing. Local
-        [project configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.project_config)
-        takes precedence over global
-        [plugin configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.plugin_config).
-        """
-        if self.__disable is None:
-            if 'disable' in self.project_config:
-                disable = self.project_config['disable']
-                if not isinstance(disable, bool):
-                    message = f'Field `tool.hatch.publish.{self.PLUGIN_NAME}.disable` must be a boolean'
-                    raise TypeError(message)
-            else:
-                disable = self.plugin_config.get('disable', False)
-                if not isinstance(disable, bool):
-                    message = f'Global plugin configuration `publish.{self.PLUGIN_NAME}.disable` must be a boolean'
-                    raise TypeError(message)
-
-            self.__disable = disable
-
-        return self.__disable
-
-    @abstractmethod
-    def publish(self, artifacts: list[str], options: dict):
-        """
-        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-        This is called directly by the [`publish`](../../cli/reference.md#hatch-publish) command
-        with the arguments and options it receives.
-        """
+    @property
+    def plugin_config(self) -> dict:
+        """
+        This is defined in Hatch's [config file](../../config/hatch.md).
+
+        ```toml tab="config.toml"
+        [publish.<PLUGIN_NAME>]
+        ```
+        """
+        return self.__plugin_config
+
+    @property
+    def disable(self):
+        """
+        Whether this plugin is disabled, thus requiring confirmation when publishing. Local
+        [project configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.project_config)
+        takes precedence over global
+        [plugin configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.plugin_config).
+        """
+        if self.__disable is None:
+            if 'disable' in self.project_config:
+                disable = self.project_config['disable']
+                if not isinstance(disable, bool):
+                    message = f'Field `tool.hatch.publish.{self.PLUGIN_NAME}.disable` must be a boolean'
+                    raise TypeError(message)
+            else:
+                disable = self.plugin_config.get('disable', False)
+                if not isinstance(disable, bool):
+                    message = f'Global plugin configuration `publish.{self.PLUGIN_NAME}.disable` must be a boolean'
+                    raise TypeError(message)
+
+            self.__disable = disable
+
+        return self.__disable
+
+    @abstractmethod
+    def publish(self, artifacts: list[str], options: dict):
+        """
+        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+        This is called directly by the [`publish`](../../cli/reference.md#hatch-publish) command
+        with the arguments and options it receives.
+        """
 

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

app property

An instance of Application.

root property

The root of the project tree as a path-like object.

cache_dir property

The directory reserved exclusively for this plugin as a path-like object.

project_config: dict property

[tool.hatch.publish.<PLUGIN_NAME>]
 
[publish.<PLUGIN_NAME>]
 

plugin_config: dict property

This is defined in Hatch's config file.

[publish.<PLUGIN_NAME>]
-

disable property

Whether this plugin is disabled, thus requiring confirmation when publishing. Local project configuration takes precedence over global plugin configuration.

publish(artifacts: list[str], options: dict) abstractmethod

REQUIRED

This is called directly by the publish command with the arguments and options it receives.

Source code in src/hatch/publish/plugin/interface.py
@abstractmethod
-def publish(self, artifacts: list[str], options: dict):
-    """
-    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
-
-    This is called directly by the [`publish`](../../cli/reference.md#hatch-publish) command
-    with the arguments and options it receives.
-    """
+

disable property

Whether this plugin is disabled, thus requiring confirmation when publishing. Local project configuration takes precedence over global plugin configuration.

publish(artifacts: list[str], options: dict) abstractmethod

REQUIRED

This is called directly by the publish command with the arguments and options it receives.

Source code in src/hatch/publish/plugin/interface.py
@abstractmethod
+def publish(self, artifacts: list[str], options: dict):
+    """
+    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:
+
+    This is called directly by the [`publish`](../../cli/reference.md#hatch-publish) command
+    with the arguments and options it receives.
+    """
 
\ No newline at end of file diff --git a/dev/plugins/version-scheme/reference/index.html b/dev/plugins/version-scheme/reference/index.html index 45c739958..b5a5f83c3 100644 --- a/dev/plugins/version-scheme/reference/index.html +++ b/dev/plugins/version-scheme/reference/index.html @@ -27,74 +27,62 @@ """ Example usage: - === ":octicons-file-code-16: plugin.py" - - ```python - from hatchling.version.scheme.plugin.interface import VersionSchemeInterface - - - class SpecialVersionScheme(VersionSchemeInterface): - PLUGIN_NAME = 'special' - ... - ``` - - === ":octicons-file-code-16: hooks.py" - - ```python - from hatchling.plugin import hookimpl - - from .plugin import SpecialVersionScheme - - - @hookimpl - def hatch_register_version_scheme(): - return SpecialVersionScheme - ``` - """ - - PLUGIN_NAME = '' - """The name used for selection.""" + ```python tab="plugin.py" + from hatchling.version.scheme.plugin.interface import VersionSchemeInterface + + + class SpecialVersionScheme(VersionSchemeInterface): + PLUGIN_NAME = 'special' + ... + ``` + + ```python tab="hooks.py" + from hatchling.plugin import hookimpl + + from .plugin import SpecialVersionScheme + + + @hookimpl + def hatch_register_version_scheme(): + return SpecialVersionScheme + ``` + """ + + PLUGIN_NAME = '' + """The name used for selection.""" + + def __init__(self, root: str, config: dict) -> None: + self.__root = root + self.__config = config - def __init__(self, root: str, config: dict) -> None: - self.__root = root - self.__config = config - - @property - def root(self) -> str: - """ - The root of the project tree as a string. - """ - return self.__root - - @property - def config(self) -> dict: - """ - === ":octicons-file-code-16: pyproject.toml" + @property + def root(self) -> str: + """ + The root of the project tree as a string. + """ + return self.__root + + @property + def config(self) -> dict: + """ + ```toml config-example + [tool.hatch.version] + ``` + """ + return self.__config - ```toml - [tool.hatch.version] - ``` - - === ":octicons-file-code-16: hatch.toml" - - ```toml - [version] - ``` - """ - return self.__config - - @abstractmethod - def update(self, desired_version: str, original_version: str, version_data: dict) -> str: - """ - This should return a normalized form of the desired version and verify that it - is higher than the original version. - """ + @abstractmethod + def update(self, desired_version: str, original_version: str, version_data: dict) -> str: + """ + This should return a normalized form of the desired version and verify that it + is higher than the original version. + """

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

root: str property

The root of the project tree as a string.

config: dict property

[tool.hatch.version]
 
[version]
-

update(desired_version: str, original_version: str, version_data: dict) -> str abstractmethod

This should return a normalized form of the desired version and verify that it is higher than the original version.

Source code in backend/src/hatchling/version/scheme/plugin/interface.py
@abstractmethod
-def update(self, desired_version: str, original_version: str, version_data: dict) -> str:
-    """
-    This should return a normalized form of the desired version and verify that it
-    is higher than the original version.
-    """
+

update(desired_version: str, original_version: str, version_data: dict) -> str abstractmethod

This should return a normalized form of the desired version and verify that it is higher than the original version.

Source code in backend/src/hatchling/version/scheme/plugin/interface.py
@abstractmethod
+def update(self, desired_version: str, original_version: str, version_data: dict) -> str:
+    """
+    This should return a normalized form of the desired version and verify that it
+    is higher than the original version.
+    """
 
\ No newline at end of file diff --git a/dev/plugins/version-scheme/standard/index.html b/dev/plugins/version-scheme/standard/index.html index 908bacf66..79f7343de 100644 --- a/dev/plugins/version-scheme/standard/index.html +++ b/dev/plugins/version-scheme/standard/index.html @@ -13,4 +13,4 @@ scheme = "standard"
[version]
 scheme = "standard"
-

Options

Option Description
validate-bump When setting a specific version, this determines whether to check that the new version is higher than the original. The default is true.
\ No newline at end of file +

Options

Option Description
validate-bump When setting a specific version, this determines whether to check that the new version is higher than the original. The default is true.
\ No newline at end of file diff --git a/dev/plugins/version-source/code/index.html b/dev/plugins/version-source/code/index.html index e635bc4dd..9f667ec90 100644 --- a/dev/plugins/version-source/code/index.html +++ b/dev/plugins/version-source/code/index.html @@ -13,12 +13,12 @@ source = "code"
[version]
 source = "code"
-

Options

Option Description
path (required) A relative path to a Python file or extension module that will be loaded
expression A Python expression that when evaluated in the context of the loaded file returns the version. The default expression is simply __version__.
search-paths A list of relative paths to directories that will be prepended to Python's search path

Missing imports

If the chosen path imports another module in your project, then you'll need to use absolute imports coupled with the search-paths option. For example, say you need to load the following file:

from ._version import get_version
+

Options

Option Description
path (required) A relative path to a Python file or extension module that will be loaded
expression A Python expression that when evaluated in the context of the loaded file returns the version. The default expression is simply __version__.
search-paths A list of relative paths to directories that will be prepended to Python's search path

Missing imports

If the chosen path imports another module in your project, then you'll need to use absolute imports coupled with the search-paths option. For example, say you need to load the following file:

    from ._version import get_version
 
-__version__ = get_version()
-

You should change it to:

from pkg._version import get_version
+    __version__ = get_version()
+

You should change it to:

    from pkg._version import get_version
 
-__version__ = get_version()
+    __version__ = get_version()
 

and the configuration would become:

[tool.hatch.version]
 source = "code"
 path = "src/pkg/__init__.py"
@@ -27,4 +27,4 @@
 source = "code"
 path = "src/pkg/__init__.py"
 search-paths = ["src"]
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/plugins/version-source/env/index.html b/dev/plugins/version-source/env/index.html index d4f3fe72d..47d259491 100644 --- a/dev/plugins/version-source/env/index.html +++ b/dev/plugins/version-source/env/index.html @@ -13,4 +13,4 @@ source = "env"
[version]
 source = "env"
-

Options

Option Description
variable (required) The name of the environment variable
\ No newline at end of file +

Options

Option Description
variable (required) The name of the environment variable
\ No newline at end of file diff --git a/dev/plugins/version-source/reference/index.html b/dev/plugins/version-source/reference/index.html index 5ffeb1d87..95e434afa 100644 --- a/dev/plugins/version-source/reference/index.html +++ b/dev/plugins/version-source/reference/index.html @@ -27,93 +27,81 @@ """ Example usage: - === ":octicons-file-code-16: plugin.py" - - ```python - from hatchling.version.source.plugin.interface import VersionSourceInterface - - - class SpecialVersionSource(VersionSourceInterface): - PLUGIN_NAME = 'special' - ... - ``` - - === ":octicons-file-code-16: hooks.py" - - ```python - from hatchling.plugin import hookimpl - - from .plugin import SpecialVersionSource - - - @hookimpl - def hatch_register_version_source(): - return SpecialVersionSource - ``` - """ - - PLUGIN_NAME = '' - """The name used for selection.""" + ```python tab="plugin.py" + from hatchling.version.source.plugin.interface import VersionSourceInterface + + + class SpecialVersionSource(VersionSourceInterface): + PLUGIN_NAME = 'special' + ... + ``` + + ```python tab="hooks.py" + from hatchling.plugin import hookimpl + + from .plugin import SpecialVersionSource + + + @hookimpl + def hatch_register_version_source(): + return SpecialVersionSource + ``` + """ + + PLUGIN_NAME = '' + """The name used for selection.""" + + def __init__(self, root: str, config: dict) -> None: + self.__root = root + self.__config = config - def __init__(self, root: str, config: dict) -> None: - self.__root = root - self.__config = config - - @property - def root(self) -> str: - """ - The root of the project tree as a string. - """ - return self.__root - - @property - def config(self) -> dict: - """ - === ":octicons-file-code-16: pyproject.toml" + @property + def root(self) -> str: + """ + The root of the project tree as a string. + """ + return self.__root + + @property + def config(self) -> dict: + """ + ```toml config-example + [tool.hatch.version] + ``` + """ + return self.__config - ```toml - [tool.hatch.version] - ``` - - === ":octicons-file-code-16: hatch.toml" + @abstractmethod + def get_version_data(self) -> dict: + """ + This should return a mapping with a `version` key representing the current version of the project and will be + displayed when invoking the [`version`](../../cli/reference.md#hatch-version) command without any arguments. - ```toml - [version] - ``` + The mapping can contain anything else and will be passed to + [set_version](reference.md#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version) + when updating the version. """ - return self.__config - - @abstractmethod - def get_version_data(self) -> dict: - """ - This should return a mapping with a `version` key representing the current version of the project and will be - displayed when invoking the [`version`](../../cli/reference.md#hatch-version) command without any arguments. - - The mapping can contain anything else and will be passed to - [set_version](reference.md#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version) - when updating the version. - """ - - def set_version(self, version: str, version_data: dict) -> None: - """ - This should update the version to the first argument with the data provided during retrieval. - """ - raise NotImplementedError + + def set_version(self, version: str, version_data: dict) -> None: + """ + This should update the version to the first argument with the data provided during retrieval. + """ + raise NotImplementedError

PLUGIN_NAME = '' class-attribute instance-attribute

The name used for selection.

root: str property

The root of the project tree as a string.

config: dict property

[tool.hatch.version]
 
[version]
-

get_version_data() -> dict abstractmethod

This should return a mapping with a version key representing the current version of the project and will be displayed when invoking the version command without any arguments.

The mapping can contain anything else and will be passed to set_version when updating the version.

Source code in backend/src/hatchling/version/source/plugin/interface.py
@abstractmethod
-def get_version_data(self) -> dict:
-    """
-    This should return a mapping with a `version` key representing the current version of the project and will be
-    displayed when invoking the [`version`](../../cli/reference.md#hatch-version) command without any arguments.
-
-    The mapping can contain anything else and will be passed to
-    [set_version](reference.md#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version)
-    when updating the version.
-    """
-

set_version(version: str, version_data: dict) -> None

This should update the version to the first argument with the data provided during retrieval.

Source code in backend/src/hatchling/version/source/plugin/interface.py
def set_version(self, version: str, version_data: dict) -> None:
-    """
-    This should update the version to the first argument with the data provided during retrieval.
-    """
-    raise NotImplementedError
+

get_version_data() -> dict abstractmethod

This should return a mapping with a version key representing the current version of the project and will be displayed when invoking the version command without any arguments.

The mapping can contain anything else and will be passed to set_version when updating the version.

Source code in backend/src/hatchling/version/source/plugin/interface.py
@abstractmethod
+def get_version_data(self) -> dict:
+    """
+    This should return a mapping with a `version` key representing the current version of the project and will be
+    displayed when invoking the [`version`](../../cli/reference.md#hatch-version) command without any arguments.
+
+    The mapping can contain anything else and will be passed to
+    [set_version](reference.md#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version)
+    when updating the version.
+    """
+

set_version(version: str, version_data: dict) -> None

This should update the version to the first argument with the data provided during retrieval.

Source code in backend/src/hatchling/version/source/plugin/interface.py
def set_version(self, version: str, version_data: dict) -> None:
+    """
+    This should update the version to the first argument with the data provided during retrieval.
+    """
+    raise NotImplementedError
 
\ No newline at end of file diff --git a/dev/plugins/version-source/regex/index.html b/dev/plugins/version-source/regex/index.html index fbe04a1f8..5c427c286 100644 --- a/dev/plugins/version-source/regex/index.html +++ b/dev/plugins/version-source/regex/index.html @@ -13,4 +13,4 @@ source = "regex"
[version]
 source = "regex"
-

Options

Option Description
path (required) A relative path to a file containing the project's version
pattern A regular expression that has a named group called version that represents the version. The default pattern looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v.
\ No newline at end of file +

Options

Option Description
path (required) A relative path to a file containing the project's version
pattern A regular expression that has a named group called version that represents the version. The default pattern looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v.
\ No newline at end of file diff --git a/dev/publish/index.html b/dev/publish/index.html index cdf92be84..42ec9c925 100644 --- a/dev/publish/index.html +++ b/dev/publish/index.html @@ -25,4 +25,4 @@ disable = true
[publish.index]
 disable = true
-
\ No newline at end of file +
\ No newline at end of file diff --git a/dev/search/search_index.json b/dev/search/search_index.json index 645c30dec..f4f2a79da 100644 --- a/dev/search/search_index.json +++ b/dev/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"Hatch","text":"CI/CD Docs Package Meta

Hatch is a modern, extensible Python project manager.

"},{"location":"#features","title":"Features","text":""},{"location":"#license","title":"License","text":"

Hatch is distributed under the terms of the MIT license.

"},{"location":"#navigation","title":"Navigation","text":"

Documentation for specific MAJOR.MINOR versions can be chosen by using the dropdown on the top of every page. The dev version reflects changes that have not yet been released.

Also, desktop readers can use special keyboard shortcuts:

Keys Action Navigate to the \"previous\" page Navigate to the \"next\" page Display the search modal"},{"location":"build/","title":"Builds","text":""},{"location":"build/#configuration","title":"Configuration","text":"

Builds are configured using the tool.hatch.build table. Every target is defined by a section within tool.hatch.build.targets, for example:

pyproject.toml hatch.toml
[tool.hatch.build.targets.sdist]\nexclude = [\n\"/.github\",\n\"/docs\",\n]\n\n[tool.hatch.build.targets.wheel]\npackages = [\"src/foo\"]\n
[build.targets.sdist]\nexclude = [\n\"/.github\",\n\"/docs\",\n]\n\n[build.targets.wheel]\npackages = [\"src/foo\"]\n
"},{"location":"build/#building","title":"Building","text":"

Invoking the build command without any arguments will build the sdist and wheel targets:

$ hatch build\n[sdist]\ndist/hatch_demo-1rc0.tar.gz\n\n[wheel]\ndist/hatch_demo-1rc0-py3-none-any.whl\n

To only build specific targets, use the -t/--target option:

$ hatch build -t wheel\n[wheel]\ndist/hatch_demo-1rc0-py3-none-any.whl\n

If the target supports multiple versions, you can specify the exact versions to build by appending a colon followed by the desired versions separated by commas:

$ hatch -v build -t wheel:standard\n[wheel]\nBuilding `wheel` version `standard`\ndist/hatch_demo-1rc0-py3-none-any.whl\n
"},{"location":"build/#packaging-ecosystem","title":"Packaging ecosystem","text":"

Hatch complies with modern Python packaging specs and therefore your projects can be used by other tools with Hatch serving as just the build backend.

So you could use tox as an alternative to Hatch's environment management, or cibuildwheel to distribute packages for every platform, and they both will transparently use Hatch without any extra modification.

"},{"location":"environment/","title":"Environments","text":"

Environments are designed to allow for isolated workspaces for testing, building documentation, or anything else projects need.

Unless an environment is chosen explicitly, Hatch will use the default environment.

"},{"location":"environment/#creation","title":"Creation","text":"

You can create environments by using the env create command. Let's enter the directory of the project we created in the setup phase:

$ hatch env create\nCreating environment: default\nInstalling project in development mode\nSyncing dependencies\n

Tip

You never need to manually create environments as spawning a shell or running commands within one will automatically trigger creation.

"},{"location":"environment/#entering-environments","title":"Entering environments","text":"

You can spawn a shell within an environment by using the shell command.

$ hatch shell\n(hatch-demo) $\n

Now confirm the project has been installed:

(hatch-demo) $ pip show hatch-demo\nName: hatch-demo\nVersion: 0.0.1\n...\n

Finally, see where your environment's Python is located:

(hatch-demo) $ python -c \"import sys;print(sys.executable)\"\n...\n

You can type exit to leave the environment.

"},{"location":"environment/#command-execution","title":"Command execution","text":"

The run command allows you to execute commands in an environment as if you had already entered it. For example, running the following command will output the same path as before:

hatch run python -c \"import sys;print(sys.executable)\"\n
"},{"location":"environment/#scripts","title":"Scripts","text":"

You can also run any scripts that have been defined.

You'll notice that in the pyproject.toml file there are already scripts defined in the default environment. Try running the test command, which invokes pytest with some default arguments:

hatch run test\n

All additional arguments are passed through to that script, so for example if you wanted to see the version of pytest and which plugins are installed you could do:

hatch run test -VV\n
"},{"location":"environment/#dependencies","title":"Dependencies","text":"

Hatch ensures that environments are always compatible with the currently defined project dependencies (if installed and in dev mode) and environment dependencies.

For example, add cowsay as a dependency then try to run it:

$ hatch run cowsay \"Hello, world!\"\nSyncing dependencies\n  _____________\n| Hello, world! |\n  =============\n             \\\n              \\\n                ^__^\n                (oo)\\_______\n                (__)\\       )\\/\\\n                    ||----w |\n                    ||     ||\n
"},{"location":"environment/#selection","title":"Selection","text":"

You can select which environment to enter or run commands in by using the -e/--env root option or by setting the HATCH_ENV environment variable.

The run command allows for more explicit selection by prepending <ENV_NAME>: to commands. For example, if you had the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.docs]\ndependencies = [\n\"mkdocs\"\n]\n[tool.hatch.envs.docs.scripts]\nbuild = \"mkdocs build --clean --strict\"\nserve = \"mkdocs serve --dev-addr localhost:8000\"\n
[envs.docs]\ndependencies = [\n\"mkdocs\"\n]\n[envs.docs.scripts]\nbuild = \"mkdocs build --clean --strict\"\nserve = \"mkdocs serve --dev-addr localhost:8000\"\n

you could then serve your documentation by running:

hatch run docs:serve\n

Tip

If you've already entered an environment, commands will target it by default.

"},{"location":"environment/#matrix","title":"Matrix","text":"

Every environment can define its own set of matrices:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"pytest\"\n]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeatures = [\"foo\", \"bar\"]\n
[envs.test]\ndependencies = [\n\"pytest\"\n]\n\n[[envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[envs.test.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeatures = [\"foo\", \"bar\"]\n

Using the env show command would then display:

$ hatch env show --ascii\n     Standalone\n+---------+---------+\n| Name    | Type    |\n+=========+=========+\n| default | virtual |\n+---------+---------+\n                       Matrices\n+------+---------+---------------------+--------------+\n| Name | Type    | Envs                | Dependencies |\n+======+=========+=====================+==============+\n| test | virtual | test.py2.7-42       | pytest       |\n|      |         | test.py2.7-3.14     |              |\n|      |         | test.py3.8-42       |              |\n|      |         | test.py3.8-3.14     |              |\n|      |         | test.py3.8-9000-foo |              |\n|      |         | test.py3.8-9000-bar |              |\n|      |         | test.py3.9-9000-foo |              |\n|      |         | test.py3.9-9000-bar |              |\n+------+---------+---------------------+--------------+\n
"},{"location":"environment/#removal","title":"Removal","text":"

You can remove a single environment or environment matrix by using the env remove command or all of a project's environments by using the env prune command.

"},{"location":"install/","title":"Installation","text":""},{"location":"install/#github-releases","title":"GitHub releases","text":"

Each release provides the following:

"},{"location":"install/#pip","title":"pip","text":"

Hatch is available on PyPI and can be installed with pip.

pip install hatch\n

Warning

This method modifies the Python environment in which you choose to install. Consider instead using pipx to avoid dependency conflicts.

"},{"location":"install/#pipx","title":"pipx","text":"

pipx allows for the global installation of Python applications in isolated environments.

pipx install hatch\n
"},{"location":"install/#homebrew","title":"Homebrew","text":"

See the formula for more details.

brew install hatch\n
"},{"location":"install/#conda","title":"Conda","text":"

See the feedstock for more details.

conda install -c conda-forge hatch\n

or with mamba:

mamba install hatch\n

Warning

This method modifies the Conda environment in which you choose to install. Consider instead using pipx or condax to avoid dependency conflicts.

"},{"location":"install/#macports","title":"MacPorts","text":"

See the port for more details.

sudo port install hatch\n
"},{"location":"install/#fedora","title":"Fedora","text":"

The minimum supported version is 37, currently in development as Rawhide.

sudo dnf install hatch\n
"},{"location":"install/#void-linux","title":"Void Linux","text":"
xbps-install hatch\n
"},{"location":"install/#build-system-availability","title":"Build system availability","text":"

Hatchling is Hatch's build backend which you will never need to install manually. See its changelog for version information.

"},{"location":"intro/","title":"Introduction","text":""},{"location":"intro/#setup","title":"Setup","text":"

Projects can be setup for use by Hatch using the new command.

"},{"location":"intro/#new-project","title":"New project","text":"

Let's say you want to create a project named Hatch Demo. You would run:

hatch new \"Hatch Demo\"\n

This would create the following structure in your current working directory:

hatch-demo\n\u251c\u2500\u2500 src\n\u2502   \u2514\u2500\u2500 hatch_demo\n\u2502       \u251c\u2500\u2500 __about__.py\n\u2502       \u2514\u2500\u2500 __init__.py\n\u251c\u2500\u2500 tests\n\u2502   \u2514\u2500\u2500 __init__.py\n\u251c\u2500\u2500 LICENSE.txt\n\u251c\u2500\u2500 README.md\n\u2514\u2500\u2500 pyproject.toml\n

Tip

There are many ways to customize project generation.

"},{"location":"intro/#existing-project","title":"Existing project","text":"

To initialize an existing project, enter the directory containing the project and run the following:

hatch new --init\n

If your project has a setup.py file the command will automatically migrate setuptools configuration for you. Otherwise, this will interactively guide you through the setup process.

"},{"location":"intro/#project-metadata","title":"Project metadata","text":"

Next you'll want to define more of your project's metadata located in the pyproject.toml file. You can specify things like its license, the supported versions of Python, and URLs referring to various parts of your project, like documentation.

"},{"location":"intro/#dependencies","title":"Dependencies","text":"

The last step of the setup process is to define any dependencies that you'd like your project to begin with.

"},{"location":"intro/#configuration","title":"Configuration","text":"

All project-specific configuration recognized by Hatch can be defined in either the pyproject.toml file, or a file named hatch.toml where options are not contained within the tool.hatch table:

pyproject.toml hatch.toml
[tool.hatch]\noption = \"...\"\n\n[tool.hatch.table1]\noption = \"...\"\n\n[tool.hatch.table2]\noption = \"...\"\n
option = \"...\"\n\n[table1]\noption = \"...\"\n\n[table2]\noption = \"...\"\n

Top level keys in the latter file take precedence when defined in both.

Tip

If you want to make your file more compact, you can use dotted keys, turning the above example into:

pyproject.toml hatch.toml
[tool.hatch]\noption = \"...\"\ntable1.option = \"...\"\ntable2.option = \"...\"\n
option = \"...\"\ntable1.option = \"...\"\ntable2.option = \"...\"\n
"},{"location":"next-steps/","title":"Next steps","text":""},{"location":"next-steps/#learn-more","title":"Learn more","text":"

At this point you should have a basic understanding of how to use Hatch.

Now you may want to check out advanced configuration for environments or builds, set up your preferred shell, or read more about Hatch's CLI.

After that, check out the Hatch Showcase project to see examples of what is possible.

Finally, if you see a need, feel free to write a plugin for extended functionality.

"},{"location":"next-steps/#community","title":"Community","text":"

For any projects using Hatch, you may add its official badge somewhere prominent like the README.

MarkdownreStructuredText
[![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch)\n
.. image:: https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg\n   :alt: Hatch project\n   :target: https://github.com/pypa/hatch\n
"},{"location":"publish/","title":"Publishing","text":"

After your project is built, you can distribute it using the publish command.

The -p/--publisher option controls which publisher to use, with the default being index.

"},{"location":"publish/#artifact-selection","title":"Artifact selection","text":"

By default, the dist directory located at the root of your project will be used:

$ hatch publish\ndist/hatch_demo-1rc0-py3-none-any.whl ... success\ndist/hatch_demo-1rc0.tar.gz ... success\n\n[hatch-demo]\nhttps://pypi.org/project/hatch-demo/1rc0/\n

You can instead pass specific paths as arguments:

hatch publish /path/to/artifacts foo-1.tar.gz\n

Only files ending with .whl or .tar.gz will be published.

"},{"location":"publish/#repository","title":"Repository","text":"

You can select the repository with which to upload using the -r/--repo option or by setting the HATCH_INDEX_REPO environment variable.

Rather than specifying the full URL of a repository, you can use a named repository from a publish.index.repos table defined in Hatch's config file:

config.toml
[publish.index.repos.private]\nurl = \"...\"\n...\n

The following repository names are reserved by Hatch and cannot be overridden:

Name Repository main https://upload.pypi.org/legacy/ test https://test.pypi.org/legacy/

The main repository is used by default.

"},{"location":"publish/#authentication","title":"Authentication","text":"

The first time you publish to a repository you need to authenticate using the -u/--user (environment variable HATCH_INDEX_USER) and -a/--auth (environment variable HATCH_INDEX_AUTH) options. You will be prompted if either option is not provided.

The user that most recently published to the chosen repository is cached, with their credentials saved to the system keyring, so that they will no longer need to provide authentication information.

For automated releasing to PyPI, it is recommended that you use per-project API tokens.

"},{"location":"publish/#confirmation","title":"Confirmation","text":"

You can require a confirmation prompt or use of the -y/--yes flag by setting publishers' disable option to true in either Hatch's config file or project-specific configuration (which takes precedence):

config.toml pyproject.toml hatch.toml
[publish.index]\ndisable = true\n
[tool.hatch.publish.index]\ndisable = true\n
[publish.index]\ndisable = true\n
"},{"location":"version/","title":"Versioning","text":""},{"location":"version/#configuration","title":"Configuration","text":"

When the version is not statically set, configuration is defined in the tool.hatch.version table. The source option determines the source to use for retrieving and updating the version. The regex source is used by default.

The regex source requires an option path that represents a relative path to a file containing the project's version:

pyproject.toml hatch.toml
[tool.hatch.version]\npath = \"src/hatch_demo/__about__.py\"\n
[version]\npath = \"src/hatch_demo/__about__.py\"\n

The default pattern looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v.

If this doesn't reflect how you store the version, you can define a different regular expression using the pattern option:

pyproject.toml hatch.toml
[tool.hatch.version]\npath = \"pkg/__init__.py\"\npattern = \"BUILD = 'b(?P<version>[^']+)'\"\n
[version]\npath = \"pkg/__init__.py\"\npattern = \"BUILD = 'b(?P<version>[^']+)'\"\n

The pattern must have a named group called version that represents the version.

"},{"location":"version/#display","title":"Display","text":"

Invoking the version command without any arguments will display the current version of the project:

$ hatch version\n0.0.1\n
"},{"location":"version/#updating","title":"Updating","text":"

You can update the version like so:

$ hatch version \"0.1.0\"\nOld: 0.0.1\nNew: 0.1.0\n

The scheme option determines the scheme to use for parsing both the existing and new versions. The standard scheme is used by default, which is based on PEP 440.

Rather than setting the version explicitly, you can select the name of a segment used to increment the version:

$ hatch version minor\nOld: 0.1.0\nNew: 0.2.0\n

You can chain multiple segment updates with a comma. For example, if you wanted to release a preview of your project's first major version, you could do:

$ hatch version major,rc\nOld: 0.2.0\nNew: 1.0.0rc0\n

When you want to release the final version, you would do:

$ hatch version release\nOld: 1.0.0rc0\nNew: 1.0.0\n
"},{"location":"version/#supported-segments","title":"Supported segments","text":"

Here are the supported segments and how they would influence an existing version of 1.0.0:

Segments New version release 1.0.0 major 2.0.0 minor 1.1.0 micropatchfix 1.0.1 aalpha 1.0.0a0 bbeta 1.0.0b0 crcprepreview 1.0.0rc0 rrevpost 1.0.0.post0 dev 1.0.0.dev0"},{"location":"blog/","title":"Blog","text":""},{"location":"blog/2022/10/08/hatch-v160/","title":"Hatch v1.6.0","text":"

Hatch v1.6.0 brings improvements to build environments, better handling of dynamic metadata, and support for tools like Visual Studio Code.

"},{"location":"blog/2022/10/08/hatch-v160/#build-environments","title":"Build environments","text":"

Originally, the environment interface method for providing builder sub-environments was intended to be used in conjunction with some cleanup logic in order to provide a fresh setup every time. However, this is unnecessary in practice because build dependencies rarely change.

Without caching, repeat build environment use is slow which affects the following scenarios:

Now a new environment interface method build_environment_exists is used by Hatch to determine whether or not it has already been created, for implementations that have a caching mechanism.

The virtual environment type now uses this method to cache build environments.

"},{"location":"blog/2022/10/08/hatch-v160/#project-metadata","title":"Project metadata","text":"

Dynamically defined metadata is now supported everywhere, thanks to the new caching of virtual build environments.

A project metadata command is introduced that displays the fully resolved metadata. The output format is JSON unless a field is specified as an argument.

For example, if you checkout a project that is built by Hatch, like FastAPI, and run:

hatch project metadata readme\n

only the readme text will be displayed. If the content is in Markdown, then Rich will render it directly in your terminal:

"},{"location":"blog/2022/10/08/hatch-v160/#virtual-environment-location","title":"Virtual environment location","text":"

The virtual environment type now uses a flat layout for storage in the configured virtual environment directory if the directory resides somewhere within the project root or if it is set to a .virtualenvs directory within the user's home directory.

For example, if you define the following Hatch configuration:

config.toml
[dirs.env]\nvirtual = \".hatch\"\n

and the following matrix:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\npython = [\"3.7\", \"3.8\", \"3.9\", \"3.10\", \"3.11\"]\n
[[envs.test.matrix]]\npython = [\"3.7\", \"3.8\", \"3.9\", \"3.10\", \"3.11\"]\n

then locating environments with the following command:

hatch env find test\n

will show that the general directory structure is:

.hatch\n\u251c\u2500\u2500 test.py3.7\n\u251c\u2500\u2500 test.py3.8\n\u251c\u2500\u2500 test.py3.9\n\u251c\u2500\u2500 test.py3.10\n\u2514\u2500\u2500 test.py3.11\n

This flat structure is required for detection of virtual environments by tools like Visual Studio Code and PyCharm.

Additionally, the virtual environment type now supports a path option to specify an explicit path that all inherited environments will share, such as the common .venv.

"},{"location":"blog/2022/10/08/hatch-v160/#migration-script-improvements","title":"Migration script improvements","text":"

The script used to migrate existing projects from setuptools has been improved to handle more edge cases that were encountered in the wild and now no longer modifies the formatting of existing pyproject.toml configuration.

"},{"location":"blog/2022/10/08/hatch-v160/#hatchling","title":"Hatchling","text":"

Hatch now depends on Hatchling v1.11.0, which was also just released.

"},{"location":"blog/2022/10/08/hatch-v160/#environment-version-source","title":"Environment version source","text":"

A new env version source is available that allows for the project version to be defined by an environment variable.

"},{"location":"blog/2022/10/08/hatch-v160/#relaxed-version-bumping","title":"Relaxed version bumping","text":"

The standard version scheme now supports a validate-bump option that when set to false will forego the check when updating the version that the desired version is higher than the current version.

This use case comes from Project Jupyter:

A common pattern we use in Jupyter is to bump to a .dev0 minor version bump after making a release. If we have a bug fix that needs to go out in the interim, we'd rather not be forced to create a branch every time.

"},{"location":"cli/about/","title":"About","text":""},{"location":"cli/about/#verbosity","title":"Verbosity","text":"

The amount of displayed output is controlled solely by the -v/--verbose (environment variable HATCH_VERBOSE) and -q/--quiet (environment variable HATCH_QUIET) root options.

The levels are documented here.

"},{"location":"cli/about/#project-awareness","title":"Project awareness","text":"

No matter the mode, Hatch will always change to the project's root directory for entering or running commands in environments.

"},{"location":"cli/about/#tab-completion","title":"Tab completion","text":"

Completion is achieved by saving a script and then executing it as a part of your shell's startup sequence.

Afterward, you'll need to start a new shell in order for the changes to take effect.

BashZ shellfish

Save the script somewhere:

_HATCH_COMPLETE=bash_source hatch > ~/.hatch-complete.bash\n

Source the file in ~/.bashrc (or ~/.bash_profile if on macOS):

. ~/.hatch-complete.bash\n

Save the script somewhere:

_HATCH_COMPLETE=zsh_source hatch > ~/.hatch-complete.zsh\n

Source the file in ~/.zshrc:

. ~/.hatch-complete.zsh\n

Save the script in ~/.config/fish/completions:

_HATCH_COMPLETE=fish_source hatch > ~/.config/fish/completions/hatch.fish\n
"},{"location":"cli/reference/","title":"hatch","text":"

Usage:

hatch [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --env, -e text The name of the environment to use [env var: HATCH_ENV] default --project, -p text The name of the project to work on [env var: HATCH_PROJECT] None --verbose, -v integer range (0 and above) Increase verbosity (can be used additively) [env var: HATCH_VERBOSE] 0 --quiet, -q integer range (0 and above) Decrease verbosity (can be used additively) [env var: HATCH_QUIET] 0 --color / --no-color boolean Whether or not to display colored output (default is auto-detection) [env vars: FORCE_COLOR/NO_COLOR] None --interactive / --no-interactive boolean Whether or not to allow features like prompts and progress bars (default is auto-detection) [env var: HATCH_INTERACTIVE] None --data-dir text The path to a custom directory used to persist data [env var: HATCH_DATA_DIR] None --cache-dir text The path to a custom directory used to cache data [env var: HATCH_CACHE_DIR] None --config text The path to a custom config file to use [env var: HATCH_CONFIG] None --version boolean Show the version and exit. False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-build","title":"hatch build","text":"

Build a project.

Usage:

hatch build [OPTIONS] [LOCATION]\n

Options:

Name Type Description Default --target, -t text The target to build, overriding project defaults. This may be selected multiple times e.g. -t sdist -t wheel None --hooks-only boolean Whether or not to only execute build hooks [env var: HATCH_BUILD_HOOKS_ONLY] False --no-hooks boolean Whether or not to disable build hooks [env var: HATCH_BUILD_NO_HOOKS] False --ext boolean Whether or not to only execute build hooks for distributing binary Python packages, such as compiling extensions. Equivalent to --hooks-only -t wheel False --clean, -c boolean Whether or not existing artifacts should first be removed [env var: HATCH_BUILD_CLEAN] False --clean-hooks-after boolean Whether or not build hook artifacts should be removed after each build [env var: HATCH_BUILD_CLEAN_HOOKS_AFTER] False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-clean","title":"hatch clean","text":"

Remove build artifacts.

Usage:

hatch clean [OPTIONS] [LOCATION]\n

Options:

Name Type Description Default --target, -t text The target with which to remove artifacts, overriding project defaults. This may be selected multiple times e.g. -t sdist -t wheel None --hooks-only boolean Whether or not to only remove artifacts from build hooks [env var: HATCH_BUILD_HOOKS_ONLY] False --no-hooks boolean Whether or not to ignore artifacts from build hooks [env var: HATCH_BUILD_NO_HOOKS] False --ext boolean Whether or not to only remove artifacts from build hooks for distributing binary Python packages, such as compiled extensions. Equivalent to --hooks-only -t wheel False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config","title":"hatch config","text":"

Manage the config file

Usage:

hatch config [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-explore","title":"hatch config explore","text":"

Open the config location in your file manager.

Usage:

hatch config explore [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-find","title":"hatch config find","text":"

Show the location of the config file.

Usage:

hatch config find [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-restore","title":"hatch config restore","text":"

Restore the config file to default settings.

Usage:

hatch config restore [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-set","title":"hatch config set","text":"

Assign values to config file entries. If the value is omitted, you will be prompted, with the input hidden if it is sensitive.

Usage:

hatch config set [OPTIONS] KEY [VALUE]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-show","title":"hatch config show","text":"

Show the contents of the config file.

Usage:

hatch config show [OPTIONS]\n

Options:

Name Type Description Default --all, -a boolean Do not scrub secret fields False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-update","title":"hatch config update","text":"

Update the config file with any new fields.

Usage:

hatch config update [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep","title":"hatch dep","text":"

Manage environment dependencies

Usage:

hatch dep [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep-hash","title":"hatch dep hash","text":"

Output a hash of the currently defined dependencies.

Usage:

hatch dep hash [OPTIONS]\n

Options:

Name Type Description Default --project-only, -p boolean Whether or not to exclude environment dependencies False --env-only, -e boolean Whether or not to exclude project dependencies False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep-show","title":"hatch dep show","text":"

Display dependencies in various formats

Usage:

hatch dep show [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep-show-requirements","title":"hatch dep show requirements","text":"

Enumerate dependencies as a list of requirements.

Usage:

hatch dep show requirements [OPTIONS]\n

Options:

Name Type Description Default --project-only, -p boolean Whether or not to exclude environment dependencies False --env-only, -e boolean Whether or not to exclude project dependencies False --feature, -f text Whether or not to only show the dependencies of the specified features None --all boolean Whether or not to include the dependencies of all features False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep-show-table","title":"hatch dep show table","text":"

Enumerate dependencies in a tabular format.

Usage:

hatch dep show table [OPTIONS]\n

Options:

Name Type Description Default --project-only, -p boolean Whether or not to exclude environment dependencies False --env-only, -e boolean Whether or not to exclude project dependencies False --lines, -l boolean Whether or not to show lines between table rows False --ascii boolean Whether or not to only use ASCII characters False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env","title":"hatch env","text":"

Manage project environments

Usage:

hatch env [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-create","title":"hatch env create","text":"

Create environments.

Usage:

hatch env create [OPTIONS] [ENV_NAME]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-find","title":"hatch env find","text":"

Locate environments.

Usage:

hatch env find [OPTIONS] [ENV_NAME]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-prune","title":"hatch env prune","text":"

Remove all environments.

Usage:

hatch env prune [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-remove","title":"hatch env remove","text":"

Remove environments.

Usage:

hatch env remove [OPTIONS] [ENV_NAME]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-run","title":"hatch env run","text":"

Run commands within project environments.

The -e/--env option overrides the equivalent root option and the HATCH_ENV environment variable.

If environments provide matrices, then you may use the -i/--include and -x/--exclude options to select or exclude certain variables, optionally followed by specific comma-separated values. For example, if you have the following configuration:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\npython = [\"3.9\", \"3.10\"]\nversion = [\"42\", \"3.14\", \"9000\"]\n
[[envs.test.matrix]]\npython = [\"3.9\", \"3.10\"]\nversion = [\"42\", \"3.14\", \"9000\"]\n

then running:

hatch env run -i py=3.10 -x version=9000 test:pytest\n

would execute pytest in the environments test.py3.10-42 and test.py3.10-3.14. Note that py may be used as an alias for python.

Usage:

hatch env run [OPTIONS] ARGS...\n

Options:

Name Type Description Default --env, -e text The environments to target None --include, -i text The matrix variables to include None --exclude, -x text The matrix variables to exclude None --filter, -f text The JSON data used to select environments None --force-continue boolean Run every command and if there were any errors exit with the first code False --ignore-compat boolean Ignore incompatibility when selecting specific environments False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-show","title":"hatch env show","text":"

Show the available environments.

Usage:

hatch env show [OPTIONS] [ENVS]...\n

Options:

Name Type Description Default --ascii boolean Whether or not to only use ASCII characters False --json boolean Whether or not to output in JSON format False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-new","title":"hatch new","text":"

Create or initialize a project.

Usage:

hatch new [OPTIONS] [NAME] [LOCATION]\n

Options:

Name Type Description Default --interactive, -i boolean Interactively choose details about the project False --cli boolean Give the project a command line interface False --init boolean Initialize an existing project False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-project","title":"hatch project","text":"

View project information

Usage:

hatch project [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-project-metadata","title":"hatch project metadata","text":"

Display project metadata.

If you want to view the raw readme file without rendering, you can use a JSON parser like jq:

hatch project metadata | jq -r .readme\n

Usage:

hatch project metadata [OPTIONS] [FIELD]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-publish","title":"hatch publish","text":"

Publish build artifacts.

Usage:

hatch publish [OPTIONS] [ARTIFACTS]...\n

Options:

Name Type Description Default --repo, -r text The repository with which to publish artifacts [env var: HATCH_INDEX_REPO] None --user, -u text The user with which to authenticate [env var: HATCH_INDEX_USER] None --auth, -a text The credentials to use for authentication [env var: HATCH_INDEX_AUTH] None --ca-cert text The path to a CA bundle [env var: HATCH_INDEX_CA_CERT] None --client-cert text The path to a client certificate, optionally containing the private key [env var: HATCH_INDEX_CLIENT_CERT] None --client-key text The path to the client certificate's private key [env var: HATCH_INDEX_CLIENT_KEY] None --no-prompt, -n boolean Disable prompts, such as for missing required fields False --initialize-auth boolean Save first-time authentication information even if nothing was published False --publisher, -p text The publisher plugin to use (default is index) [env var: HATCH_PUBLISHER] index --option, -o text Options to pass to the publisher plugin. This may be selected multiple times e.g. -o foo=bar -o baz=23 [env var: HATCH_PUBLISHER_OPTIONS] None --yes, -y boolean Confirm without prompting when the plugin is disabled False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python","title":"hatch python","text":"

Manage Python installations

Usage:

hatch python [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python-install","title":"hatch python install","text":"

Install Python distributions.

You may select all to install all compatible distributions:

hatch python install all\n

Usage:

hatch python install [OPTIONS] NAMES...\n

Options:

Name Type Description Default --private boolean Do not add distributions to the user PATH False --update, -u boolean Update existing installations False --dir, -d text The directory in which to install distributions, overriding configuration None --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python-remove","title":"hatch python remove","text":"

Remove Python distributions.

You may select all to remove all installed distributions:

hatch python remove all\n

Usage:

hatch python remove [OPTIONS] NAMES...\n

Options:

Name Type Description Default --dir, -d text The directory in which distributions reside None --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python-show","title":"hatch python show","text":"

Show the available Python distributions.

Usage:

hatch python show [OPTIONS]\n

Options:

Name Type Description Default --ascii boolean Whether or not to only use ASCII characters False --dir, -d text The directory in which distributions reside None --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python-update","title":"hatch python update","text":"

Update Python distributions.

You may select all to update all installed distributions:

hatch python update all\n

Usage:

hatch python update [OPTIONS] NAMES...\n

Options:

Name Type Description Default --dir, -d text The directory in which distributions reside None --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-run","title":"hatch run","text":"

Run commands within project environments. This is a convenience wrapper around the env run command.

If the first argument contains a colon, then the preceding component will be interpreted as the name of the environment to target, overriding the -e/--env root option and the HATCH_ENV environment variable.

If the environment provides matrices, then you may also provide leading arguments starting with a + or - to select or exclude certain variables, optionally followed by specific comma-separated values. For example, if you have the following configuration:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\npython = [\"3.9\", \"3.10\"]\nversion = [\"42\", \"3.14\", \"9000\"]\n
[[envs.test.matrix]]\npython = [\"3.9\", \"3.10\"]\nversion = [\"42\", \"3.14\", \"9000\"]\n

then running:

hatch run +py=3.10 -version=9000 test:pytest\n

would execute pytest in the environments test.py3.10-42 and test.py3.10-3.14. Note that py may be used as an alias for python.

Usage:

hatch run [OPTIONS] [ENV:]ARGS...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-shell","title":"hatch shell","text":"

Enter a shell within a project's environment.

Usage:

hatch shell [OPTIONS] [SHELL_NAME] [SHELL_PATH] [SHELL_ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-status","title":"hatch status","text":"

Show information about the current environment.

Usage:

hatch status [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-version","title":"hatch version","text":"

View or set a project's version.

Usage:

hatch version [OPTIONS] [DESIRED_VERSION]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"community/highlights/","title":"Highlights","text":""},{"location":"community/users/","title":"Users","text":"

The following is not intended to be a complete enumeration. Be sure to view the development version of this page for an up-to-date listing.

"},{"location":"community/users/#projects","title":"Projects","text":"

argon2-cffi | Black | Colorama | Django Debug Toolbar | Django Wiki | FastAPI | Gradio | HTTPX | iCalendar for Humans | LinkChecker | Material for MkDocs | MkDocs | Nox | pipx | platformdirs | Pydantic | PyHamcrest | PyMdown Extensions | Python JSON Schema | SALib | Spack | Starlette | structlog | tox | Twisted | urllib3 | Uvicorn | Voil\u00e0

"},{"location":"community/users/#industry","title":"Industry","text":""},{"location":"community/users/#organizations","title":"Organizations","text":""},{"location":"community/users/#government","title":"Government","text":""},{"location":"community/users/#academia","title":"Academia","text":""},{"location":"community/users/#research","title":"Research","text":""},{"location":"community/users/#security","title":"Security","text":""},{"location":"community/users/#crypto","title":"Crypto","text":""},{"location":"config/build/","title":"Build configuration","text":"

All build configuration is defined in the tool.hatch.build table.

Build targets are defined as sections within tool.hatch.build.targets:

pyproject.toml hatch.toml
[tool.hatch.build.targets.<TARGET_NAME>]\n
[build.targets.<TARGET_NAME>]\n

For each build target you may override any of the defaults set in the top-level tool.hatch.build table.

"},{"location":"config/build/#build-system","title":"Build system","text":"

To be compatible with the broader Python packaging ecosystem, you must define the build system as follows:

pyproject.toml
[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n

The version of hatchling defined here will be used to build all targets.

Hatchling is a PEP 517/PEP 660 compatible build backend and is a dependency of Hatch itself.

"},{"location":"config/build/#file-selection","title":"File selection","text":""},{"location":"config/build/#vcs","title":"VCS","text":"

By default, Hatch will respect the first .gitignore or .hgignore file found in your project's root directory or parent directories. Set ignore-vcs to true to disable this behavior:

pyproject.toml hatch.toml
[tool.hatch.build]\nignore-vcs = true\n
[build]\nignore-vcs = true\n

Note

For .hgignore files only glob syntax is supported.

"},{"location":"config/build/#patterns","title":"Patterns","text":"

You can set the include and exclude options to select exactly which files will be shipped in each build, with exclude taking precedence. Every entry represents a Git-style glob pattern.

For example, the following configuration:

pyproject.toml hatch.toml
[tool.hatch.build]\ninclude = [\n\"pkg/*.py\",\n\"/tests\",\n]\nexclude = [\n\"*.json\",\n\"pkg/_compat.py\",\n]\n
[build]\ninclude = [\n\"pkg/*.py\",\n\"/tests\",\n]\nexclude = [\n\"*.json\",\n\"pkg/_compat.py\",\n]\n

will exclude every file with a .json extension, and will include everything under a tests directory located at the root and every file with a .py extension that is directly under a pkg directory located at the root except for _compat.py.

"},{"location":"config/build/#artifacts","title":"Artifacts","text":"

If you want to include files that are ignored by your VCS, such as those that might be created by build hooks, you can use the artifacts option. This option is semantically equivalent to include.

Note that artifacts are not affected by the exclude option. Artifacts can be excluded by using more explicit paths or by using the ! negation operator. When using the ! operator, the negated pattern(s) must come after the more generic ones.

pyproject.toml hatch.toml
[tool.hatch.build]\nartifacts = [\n\"*.so\",\n\"*.dll\",\n\"!/foo/*.so\",\n]\n
[build]\nartifacts = [\n\"*.so\",\n\"*.dll\",\n\"!/foo/*.so\",\n]\n
"},{"location":"config/build/#explicit-selection","title":"Explicit selection","text":""},{"location":"config/build/#generic","title":"Generic","text":"

You can use the only-include option to prevent directory traversal starting at the project root and only select specific relative paths to directories or files. Using this option ignores any defined include patterns.

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel]\nonly-include = [\"pkg\", \"tests/unit\"]\n
[build.targets.wheel]\nonly-include = [\"pkg\", \"tests/unit\"]\n
"},{"location":"config/build/#packages","title":"Packages","text":"

The packages option is semantically equivalent to only-include (which takes precedence) except that the shipped path will be collapsed to only include the final component.

So for example, if you want to ship a package foo that is stored in a directory src you would do:

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel]\npackages = [\"src/foo\"]\n
[build.targets.wheel]\npackages = [\"src/foo\"]\n
"},{"location":"config/build/#forced-inclusion","title":"Forced inclusion","text":"

The force-include option allows you to select specific files or directories from anywhere on the file system that should be included and map them to the desired relative distribution path.

For example, if there was a directory alongside the project root named artifacts containing a file named lib.so and a file named lib.h in your home directory, you could ship both files in a pkg directory with the following configuration:

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel.force-include]\n\"../artifacts\" = \"pkg\"\n\"~/lib.h\" = \"pkg/lib.h\"\n
[build.targets.wheel.force-include]\n\"../artifacts\" = \"pkg\"\n\"~/lib.h\" = \"pkg/lib.h\"\n

Note

Warning

Files included using this option will overwrite any file path that was already included by other file selection options.

"},{"location":"config/build/#default-file-selection","title":"Default file selection","text":"

If no file selection options are provided, then what gets included is determined by each build target.

"},{"location":"config/build/#excluding-files-outside-packages","title":"Excluding files outside packages","text":"

If you want to exclude non-artifact files that do not reside within a Python package, set only-packages to true:

pyproject.toml hatch.toml
[tool.hatch.build]\nonly-packages = true\n
[build]\nonly-packages = true\n
"},{"location":"config/build/#rewriting-paths","title":"Rewriting paths","text":"

You can rewrite relative paths to directories with the sources option. For example, the following configuration:

pyproject.toml hatch.toml
[tool.hatch.build.sources]\n\"src/foo\" = \"bar\"\n
[build.sources]\n\"src/foo\" = \"bar\"\n

would distribute the file src/foo/file.ext as bar/file.ext.

If you want to remove path prefixes entirely, rather than setting each to an empty string, you can define sources as an array:

pyproject.toml hatch.toml
[tool.hatch.build]\nsources = [\"src\"]\n
[build]\nsources = [\"src\"]\n

The packages option itself relies on sources. Defining packages = [\"src/foo\"] for the wheel target is equivalent to the following:

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel]\nonly-include = [\"src/foo\"]\nsources = [\"src\"]\n
[build.targets.wheel]\nonly-include = [\"src/foo\"]\nsources = [\"src\"]\n
"},{"location":"config/build/#performance","title":"Performance","text":"

All encountered directories are traversed by default. To skip non-artifact directories that are excluded, set skip-excluded-dirs to true:

pyproject.toml hatch.toml
[tool.hatch.build]\nskip-excluded-dirs = true\n
[build]\nskip-excluded-dirs = true\n

Warning

This may result in not shipping desired files. For example, if you want to include the file a/b/c.txt but your VCS ignores a/b, the file c.txt will not be seen because its parent directory will not be entered. In such cases you can use the force-include option.

"},{"location":"config/build/#reproducible-builds","title":"Reproducible builds","text":"

By default, build targets will build in a reproducible manner provided that they support that behavior. To disable this, set reproducible to false:

pyproject.toml hatch.toml
[tool.hatch.build]\nreproducible = false\n
[build]\nreproducible = false\n

When enabled, the SOURCE_DATE_EPOCH environment variable will be used for all build timestamps. If not set, then Hatch will use an unchanging default value.

"},{"location":"config/build/#output-directory","title":"Output directory","text":"

When the output directory is not provided to the build command, the dist directory will be used by default. You can change the default to a different directory using a relative or absolute path like so:

pyproject.toml hatch.toml
[tool.hatch.build]\ndirectory = \"<PATH>\"\n
[build]\ndirectory = \"<PATH>\"\n
"},{"location":"config/build/#dev-mode","title":"Dev mode","text":"

By default for dev mode environment installations or editable installs, the wheel target will determine which directories should be added to Python's search path based on the selected files.

If you want to override this detection or perhaps instruct other build targets as well, you can use the dev-mode-dirs option:

pyproject.toml hatch.toml
[tool.hatch.build]\ndev-mode-dirs = [\".\"]\n
[build]\ndev-mode-dirs = [\".\"]\n

If you don't want to add entire directories to Python's search path, you can enable a more targeted mechanism with the mutually exclusive dev-mode-exact option:

pyproject.toml hatch.toml
[tool.hatch.build]\ndev-mode-exact = true\n
[build]\ndev-mode-exact = true\n

Warning

The dev-mode-exact mechanism is not supported by static analysis tools & IDEs, therefore functionality such as autocompletion is unlikely to work.

"},{"location":"config/build/#build-targets","title":"Build targets","text":"

A build target can be provided by any builder plugin. There are three built-in build targets: wheel, sdist, and custom.

"},{"location":"config/build/#dependencies","title":"Dependencies","text":"

You can specify additional dependencies that will be installed in each build environment, such as for third party builders:

pyproject.toml hatch.toml
[tool.hatch.build.targets.your-target-name]\ndependencies = [\n\"your-builder-plugin\"\n]\n
[build.targets.your-target-name]\ndependencies = [\n\"your-builder-plugin\"\n]\n

You can also declare dependence on the project's runtime dependencies with the require-runtime-dependencies option:

pyproject.toml hatch.toml
[tool.hatch.build.targets.your-target-name]\nrequire-runtime-dependencies = true\n
[build.targets.your-target-name]\nrequire-runtime-dependencies = true\n

Additionally, you may declare dependence on specific runtime features of the project with the require-runtime-features option:

pyproject.toml hatch.toml
[tool.hatch.build.targets.your-target-name]\nrequire-runtime-features = [\n\"feature1\",\n\"feature2\",\n]\n
[build.targets.your-target-name]\nrequire-runtime-features = [\n\"feature1\",\n\"feature2\",\n]\n
"},{"location":"config/build/#versions","title":"Versions","text":"

If a build target supports multiple build strategies or if there are major changes over time, you can specify exactly which versions you want to build using the versions option:

pyproject.toml hatch.toml
[tool.hatch.build.targets.<TARGET_NAME>]\nversions = [\n\"v1\",\n\"beta-feature\",\n]\n
[build.targets.<TARGET_NAME>]\nversions = [\n\"v1\",\n\"beta-feature\",\n]\n

See the wheel target for a real world example.

"},{"location":"config/build/#build-hooks","title":"Build hooks","text":"

A build hook defines code that will be executed at various stages of the build process and can be provided by any build hook plugin. There is one built-in build hook: custom.

Build hooks can be applied either globally:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.<HOOK_NAME>]\n
[build.hooks.<HOOK_NAME>]\n

or to specific build targets:

pyproject.toml hatch.toml
[tool.hatch.build.targets.<TARGET_NAME>.hooks.<HOOK_NAME>]\n
[build.targets.<TARGET_NAME>.hooks.<HOOK_NAME>]\n
"},{"location":"config/build/#dependencies_1","title":"Dependencies","text":"

You can specify additional dependencies that will be installed in each build environment, such as for third party build hooks:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.your-hook-name]\ndependencies = [\n\"your-build-hook-plugin\"\n]\n
[build.hooks.your-hook-name]\ndependencies = [\n\"your-build-hook-plugin\"\n]\n

You can also declare dependence on the project's runtime dependencies with the require-runtime-dependencies option:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.your-hook-name]\nrequire-runtime-dependencies = true\n
[build.hooks.your-hook-name]\nrequire-runtime-dependencies = true\n

Additionally, you may declare dependence on specific runtime features of the project with the require-runtime-features option:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.your-hook-name]\nrequire-runtime-features = [\n\"feature1\",\n\"feature2\",\n]\n
[build.hooks.your-hook-name]\nrequire-runtime-features = [\n\"feature1\",\n\"feature2\",\n]\n
"},{"location":"config/build/#order-of-execution","title":"Order of execution","text":"

For each build target, build hooks execute in the order in which they are defined, starting with global hooks.

As an example, for the following configuration:

pyproject.toml hatch.toml
[tool.hatch.build.targets.foo.hooks.hook2]\n\n[tool.hatch.build.hooks.hook3]\n[tool.hatch.build.hooks.hook1]\n
[build.targets.foo.hooks.hook2]\n\n[build.hooks.hook3]\n[build.hooks.hook1]\n

When target foo is built, build hook hook3 will be executed first, followed by hook1, and then finally hook2.

"},{"location":"config/build/#conditional-execution","title":"Conditional execution","text":"

If you want to disable a build hook by default and control its use by environment variables, you can do so by setting the enable-by-default option to false:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.<HOOK_NAME>]\nenable-by-default = false\n
[build.hooks.<HOOK_NAME>]\nenable-by-default = false\n
"},{"location":"config/build/#environment-variables","title":"Environment variables","text":"Variable Default Description HATCH_BUILD_CLEAN false Whether or not existing artifacts should first be removed HATCH_BUILD_CLEAN_HOOKS_AFTER false Whether or not build hook artifacts should be removed after each build HATCH_BUILD_HOOKS_ONLY false Whether or not to only execute build hooks HATCH_BUILD_NO_HOOKS false Whether or not to disable all build hooks; this takes precedence over other options HATCH_BUILD_HOOKS_ENABLE false Whether or not to enable all build hooks HATCH_BUILD_HOOK_ENABLE_<HOOK_NAME> false Whether or not to enable the build hook named <HOOK_NAME> HATCH_BUILD_LOCATION dist The location with which to build the targets; only used by the build command"},{"location":"config/context/","title":"Context formatting","text":"

You can populate configuration with the values of certain supported fields using the syntax of Python's format strings. Each field interprets the modifier part after the colon differently, if at all.

"},{"location":"config/context/#global-fields","title":"Global fields","text":"

Any configuration that declares support for context formatting will always support these fields.

"},{"location":"config/context/#paths","title":"Paths","text":"Field Description root The root project directory home The user's home directory

All paths support the following modifiers:

Modifier Description uri The normalized absolute URI path prefixed by file: real The path with all symbolic links resolved"},{"location":"config/context/#system-separators","title":"System separators","text":"Field Description / \\ on Windows, / otherwise ; ; on Windows, : otherwise"},{"location":"config/context/#environment-variables","title":"Environment variables","text":"

The env field and its modifier allow you to select the value of an environment variable. If the environment variable is not set, you must specify a default value as an additional modifier e.g. {env:PATH:DEFAULT}.

"},{"location":"config/context/#field-nesting","title":"Field nesting","text":"

You can insert fields within others. For example, if you wanted a script that displays the value of the environment variable FOO, with a fallback to the environment variable BAR, with its own fallback to the user's home directory, you could do the following:

pyproject.toml hatch.toml
[tool.hatch.envs.test.scripts]\ndisplay = \"echo {env:FOO:{env:BAR:{home}}}\"\n
[envs.test.scripts]\ndisplay = \"echo {env:FOO:{env:BAR:{home}}}\"\n
"},{"location":"config/dependency/","title":"Dependency configuration","text":"

Project dependencies are defined with PEP 508 strings using optional PEP 440 version specifiers.

"},{"location":"config/dependency/#version-specifiers","title":"Version specifiers","text":"

A version specifier consists of a series of version clauses, separated by commas. For example:

pyproject.toml
[project]\n...\ndependencies = [\n\"cryptography\",\n\"click>=7, <9, != 8.0.0\",\n\"python-dateutil==2.8.*\",\n\"numpy~=1.21.4\",\n]\n

The comma is equivalent to a logical AND operator: a candidate version must match all given version clauses in order to match the specifier as a whole.

"},{"location":"config/dependency/#operators","title":"Operators","text":"Operators Function ~= Compatible release == Version matching != Version exclusion <=, >= Inclusive ordered comparison <, > Exclusive ordered comparison === Arbitrary equality"},{"location":"config/dependency/#version-matching","title":"Version matching","text":"

A version matching clause includes the version matching operator == and a version identifier.

By default, the version matching operator is based on a strict equality comparison: the specified version must be exactly the same as the requested version.

Clause Allowed versions ==1 1.0.0 ==1.2 1.2.0

Prefix matching may be requested instead of strict comparison, by appending a trailing .* to the version identifier in the version matching clause. This means that additional trailing segments will be ignored when determining whether or not a version identifier matches the clause.

Clause Allowed versions ==1.* >=1.0.0, <2.0.0 ==1.2.* >=1.2.0, <1.3.0"},{"location":"config/dependency/#compatible-release","title":"Compatible release","text":"

A compatible release clause consists of the compatible release operator ~= and a version identifier. It matches any candidate version that is expected to be compatible with the specified version.

For a given release identifier V.N, the compatible release clause is approximately equivalent to the following pair of comparison clauses:

>= V.N, == V.*\n

This operator cannot be used with a single segment version number such as ~=1.

Clause Allowed versions ~=1.2 >=1.2.0, <2.0.0 ~=1.2.3 >=1.2.3, <1.3.0"},{"location":"config/dependency/#version-exclusion","title":"Version exclusion","text":"

A version exclusion clause includes the version exclusion operator != and a version identifier.

The allowed version identifiers and comparison semantics are the same as those of the Version matching operator, except that the sense of any match is inverted.

"},{"location":"config/dependency/#ordered-comparison","title":"Ordered comparison","text":"

Inclusive comparisons allow for the version identifier part of clauses whereas exclusive comparisons do not. For example, >=1.2 allows for version 1.2.0 while >1.2 does not.

Unlike the inclusive ordered comparisons <= and >=, the exclusive ordered comparisons < and > specifically exclude pre-releases, post-releases, and local versions of the specified version.

"},{"location":"config/dependency/#arbitrary-equality","title":"Arbitrary equality","text":"

Though heavily discouraged, arbitrary equality comparisons allow for simple string matching without any version semantics, for example ===foobar.

"},{"location":"config/dependency/#environment-markers","title":"Environment markers","text":"

Environment markers allow for dependencies to only be installed when certain conditions are met.

For example, if you need to install the latest version of cryptography that is available for a given Python major version you could define the following:

cryptography==3.3.2; python_version < \"3\"\ncryptography>=35.0; python_version > \"3\"\n

Alternatively, if you only need it on Python 3 when running on Windows you could do:

cryptography; python_version ~= \"3.0\" and platform_system == \"Windows\"\n

The available environment markers are as follows.

Marker Python equivalent Examples os_name import osos.name sys_platform import syssys.platform platform_machine import platformplatform.machine() platform_python_implementation import platformplatform.python_implementation() platform_release import platformplatform.release() platform_system import platformplatform.system() platform_version import platformplatform.version() python_version import platform'.'.join(platform.python_version_tuple()[:2]) python_full_version import platformplatform.python_version() implementation_name import syssys.implementation.name implementation_version See here "},{"location":"config/dependency/#features","title":"Features","text":"

You can select groups of optional dependencies to install using the extras syntax. For example, if a dependency named foo defined the following:

pyproject.toml
[project.optional-dependencies]\ncrypto = [\n\"PyJWT\",\n\"cryptography\",\n]\nfastjson = [\n\"orjson\",\n]\ncli = [\n\"prompt-toolkit\",\n\"colorama; platform_system == 'Windows'\",\n]\n

You can select the cli and crypto features like so:

foo[cli,crypto]==1.*\n

Note that the features come immediately after the package name, before any version specifiers.

"},{"location":"config/dependency/#self-referential","title":"Self-referential","text":"

Feature groups can self-referentially extend others. For example, for a project called awesome-project, the dev feature group in the following pyproject.toml file would select everything in the crypto feature group, plus black:

pyproject.toml
[project]\nname = \"awesome-project\"\n\n[project.optional-dependencies]\ncrypto = [\n\"PyJWT\",\n\"cryptography\",\n]\ndev = [\n\"awesome-project[crypto]\",\n\"black\",\n]\n
"},{"location":"config/dependency/#direct-references","title":"Direct references","text":"

Instead of using normal version specifiers and fetching packages from an index like PyPI, you can define exact sources using direct references with an explicit URI.

Direct references are usually not meant to be used for dependencies of a published project but rather are used for defining dependencies for an environment.

All direct reference types are prefixed by the package name like:

<NAME> @ <REFERENCE>\n
"},{"location":"config/dependency/#version-control-systems","title":"Version control systems","text":"

Various version control systems (VCS) are supported as long as the associated executable is available along your PATH.

VCS direct references are defined using one of the following formats:

<NAME> @ <SCHEME>://<PATH>\n<NAME> @ <SCHEME>://<PATH>@<REVISION>\n

You may also append a #subdirectory=<PATH> component for specifying the relative path to the Python package when it is not located at the root e.g. #subdirectory=lib/foo.

For more information, refer to this.

"},{"location":"config/dependency/#supported-vcs","title":"Supported VCS","text":"GitMercurialSubversionBazaar Executable Schemes Revisions Example git proj @ git+https://github.com/org/proj.git@v1 Executable Schemes Revisions Example hg proj @ hg+file:///path/to/proj@v1 Executable Schemes Revisions Example svn proj @ svn+file:///path/to/proj Executable Schemes Revisions Example bzr proj @ bzr+lp:proj@v1"},{"location":"config/dependency/#local","title":"Local","text":"

You can install local packages with the file scheme in the following format:

<NAME> @ file://<HOST>/<PATH>\n

The <HOST> is only used on Windows systems, where it can refer to a network share. If omitted it is assumed to be localhost and the third slash must still be present.

The <PATH> can refer to a source archive, a wheel, or a directory containing a Python package.

Type Unix Windows Source archive proj @ file:///path/to/pkg.tar.gz proj @ file:///c:/path/to/pkg.tar.gz Wheel proj @ file:///path/to/pkg.whl proj @ file:///c:/path/to/pkg.whl Directory proj @ file:///path/to/pkg proj @ file:///c:/path/to/pkg

Tip

You may also specify paths relative to your project's root directory on all platforms by using context formatting:

<NAME> @ {root:uri}/pkg_inside_project\n<NAME> @ {root:uri}/../pkg_alongside_project\n
"},{"location":"config/dependency/#remote","title":"Remote","text":"

You can install source archives and wheels by simply referring to a URL:

black @ https://github.com/psf/black/archive/refs/tags/21.10b0.zip\npytorch @ https://download.pytorch.org/whl/cu102/torch-1.10.0%2Bcu102-cp39-cp39-linux_x86_64.whl\n

An expected hash value may be specified by appending a #<HASH_ALGORITHM>=<EXPECTED_HASH> component:

requests @ https://github.com/psf/requests/archive/refs/tags/v2.26.0.zip#sha256=eb729a757f01c10546ebd179ae2aec852dd0d7f8ada2328ccf4558909d859985\n

If the hash differs from the expected hash, the installation will fail.

It is recommended that only hashes which are unconditionally provided by the latest version of the standard library's hashlib module be used for hashes. As of Python 3.10, that list consists of:

"},{"location":"config/dependency/#complex-syntax","title":"Complex syntax","text":"

The following is an example that uses features and environment markers:

pkg[feature1,feature2] @ <REFERENCE> ; python_version < \"3.7\"\n

Note that the space before the semicolon is required.

"},{"location":"config/hatch/","title":"Hatch configuration","text":"

Configuration for Hatch itself is stored in a config.toml file located by default in one of the following platform-specific directories.

Platform Path macOS ~/Library/Application Support/hatch Windows %USERPROFILE%\\AppData\\Local\\hatch Unix $XDG_CONFIG_HOME/hatch (the XDG_CONFIG_HOME environment variable default is ~/.config)

You can select a custom path to the file using the --config root option or by setting the HATCH_CONFIG environment variable.

The file can be managed by the config command group.

"},{"location":"config/hatch/#mode","title":"Mode","text":"

The mode key controls how Hatch selects the project to work on.

"},{"location":"config/hatch/#local","title":"Local","text":"config.toml
mode = \"local\"\n

By default, Hatch will look for a pyproject.toml file in the current working directory and any parent directories. The directory storing the first found file will be considered the project root.

"},{"location":"config/hatch/#project","title":"Project","text":"config.toml
mode = \"project\"\nproject = \"proj1\"\n\n[projects]\nproj1 = \"/path/to/project1\"\nproj2 = {\"location\": \"/path/to/project2\"}\n\n[dirs]\nproject = [\"/path/to/monorepo1\", \"/path/to/monorepo2\"]\n

In this mode, Hatch will only work on the selected project. The project is located using multiple heuristics:

  1. If the project is defined in the projects table then it must be a string, or an inline table with a location key, that is the full path to the project.
  2. If the project matches a subdirectory in any of the directories listed in dirs.project, then that will be used as the project root.

An error will occur if the project cannot be found.

You can use the config set command to change the project you are working on:

$ hatch config set project proj2\nNew setting:\nproject = \"proj2\"\n

The project can be selected on a per-command basis with the -p/--project (environment variable HATCH_PROJECT) root option.

"},{"location":"config/hatch/#aware","title":"Aware","text":"config.toml
mode = \"aware\"\n

This is essentially the local mode with a fallback to the project mode.

"},{"location":"config/hatch/#shell","title":"Shell","text":"

You can control the shell used to enter environments with the shell key.

If defined as a string, it must be the name of one of the supported shells and be available along your PATH.

config.toml
shell = \"fish\"\n

If the executable name of your shell differs from the supported name, you can define the shell as a table with name and path keys.

config.toml
[shell]\nname = \"bash\"\npath = \"/bin/ash\"\n

You can change the default arguments used to spawn most shells with the args key. The default for such supported shells is usually [\"-i\"].

config.toml
[shell]\nname = \"bash\"\nargs = [\"--login\"]\n
"},{"location":"config/hatch/#supported","title":"Supported","text":"Shell Name Arguments macOS Windows Unix Almquist shell ash [\"-i\"] Bash bash [\"-i\"] Command Prompt cmd C shell csh [\"-i\"] fish fish [\"-i\"] Nushell nu [] PowerShell pwsh, powershell tcsh tcsh [\"-i\"] xonsh xonsh [\"-i\"] Z shell zsh [\"-i\"]"},{"location":"config/hatch/#default","title":"Default","text":"

Hatch will attempt to use the current shell based on parent processes. If the shell cannot be determined, then on Windows systems Hatch will use the SHELL environment variable, if present, followed by the COMSPEC environment variable, defaulting to cmd. On all other platforms only the SHELL environment variable will be used, defaulting to bash.

"},{"location":"config/hatch/#directories","title":"Directories","text":""},{"location":"config/hatch/#data","title":"Data","text":"config.toml
[dirs]\ndata = \"...\"\n

This is the directory that is used to persist data. By default it is set to one of the following platform-specific directories.

Platform Path macOS ~/Library/Application Support/hatch Windows %USERPROFILE%\\AppData\\Local\\hatch Unix $XDG_DATA_HOME/hatch (the XDG_DATA_HOME environment variable default is ~/.local/share)

You can select a custom path to the directory using the --data-dir root option or by setting the HATCH_DATA_DIR environment variable.

"},{"location":"config/hatch/#cache","title":"Cache","text":"config.toml
[dirs]\ncache = \"...\"\n

This is the directory that is used to cache data. By default it is set to one of the following platform-specific directories.

Platform Path macOS ~/Library/Caches/hatch Windows %USERPROFILE%\\AppData\\Local\\hatch\\Cache Unix $XDG_CACHE_HOME/hatch (the XDG_CACHE_HOME environment variable default is ~/.cache)

You can select a custom path to the directory using the --cache-dir root option or by setting the HATCH_CACHE_DIR environment variable.

"},{"location":"config/hatch/#environments","title":"Environments","text":"config.toml
[dirs.env]\n<ENV_TYPE> = \"...\"\n

This determines where to store environments, with every key being the type of environment and the value being the desired storage location.

For example, if you wanted to store virtual environments in a .virtualenvs directory within your home directory, you could specify the following:

config.toml
[dirs.env]\nvirtual = \"~/.virtualenvs\"\n

Any environment variables are also expanded.

If the path is not absolute, then it will be relative to the project root. So if you wanted to use a directory named .hatch in each project directory, you could do:

config.toml
[dirs.env]\nvirtual = \".hatch\"\n

Any type of environment that is not explicitly defined will default to <DATA_DIR>/env/<ENV_TYPE>.

"},{"location":"config/hatch/#python-installations","title":"Python installations","text":"config.toml
[dirs]\npython = \"...\"\n

This determines where to install specific versions of Python.

The following values have special meanings:

Value Path shared (default) ~/.pythons isolated <DATA_DIR>/pythons"},{"location":"config/hatch/#terminal","title":"Terminal","text":"

You can configure how all output is displayed using the terminal.styles table. These settings are also applied to all plugins.

config.toml
[terminal.styles]\nerror = \"...\"\n...\n

Cross-platform terminal capabilities are provided by Rich.

"},{"location":"config/hatch/#output-levels","title":"Output levels","text":"

The levels of output are as follows. Note that the verbosity indicates the minimum level at which the output is displayed.

Level Default Verbosity Description debug bold 1 - 3 Messages that are not useful for most user experiences error bold red -2 Messages indicating some unrecoverable error info bold 0 Messages conveying basic information success bold cyan 0 Messages indicating some positive outcome waiting bold magenta 0 Messages shown before potentially time consuming operations warning bold yellow -1 Messages conveying important information

See the documentation and color reference for guidance on valid values.

"},{"location":"config/hatch/#spinner","title":"Spinner","text":"

You can select the sequence used for waiting animations with the spinner option.

config.toml
[terminal.styles]\nspinner = \"...\"\n
"},{"location":"config/metadata/","title":"Project metadata","text":"

Project metadata is stored in a pyproject.toml file located at the root of a project's tree and is based entirely on PEP 621.

"},{"location":"config/metadata/#name","title":"Name (required)","text":"

The name of the project.

pyproject.toml
[project]\nname = \"your-app\"\n
"},{"location":"config/metadata/#version","title":"Version (required)","text":"pyproject.toml DynamicStatic

See the dedicated versioning section.

[project]\n...\ndynamic = [\"version\"]\n\n[tool.hatch.version]\npath = \"...\"\n
[project]\n...\nversion = \"0.0.1\"\n
"},{"location":"config/metadata/#description","title":"Description","text":"

A brief summary of the project.

pyproject.toml
[project]\n...\ndescription = '...'\n
"},{"location":"config/metadata/#readme","title":"Readme","text":"

The full description of the project.

pyproject.toml SimpleComplex

The file extension must be .md, .rst, or .txt.

[project]\n...\nreadme = \"README.md\"\n

The content-type field must be set to text/markdown, text/x-rst, or text/plain.

FileText

A charset field may also be set to instruct which encoding to use for reading the file, defaulting to utf-8.

[project]\n...\nreadme = {\"file\" = \"README.md\", \"content-type\" = \"text/markdown\"}\n

The content-type field must be set to text/markdown or text/x-rst.

[project]\n...\nreadme = {\"text\" = \"...\", \"content-type\" = \"text/markdown\"}\n

Note

If this is defined as a file, then it will always be included in source distributions for consistent builds.

"},{"location":"config/metadata/#python-support","title":"Python support","text":"

The Python version requirements of the project.

pyproject.toml
[project]\n...\nrequires-python = \">=3.8\"\n
"},{"location":"config/metadata/#license","title":"License","text":"

For more information, see PEP 639.

pyproject.toml SPDX expressionFiles
[project]\n...\nlicense = \"Apache-2.0 OR MIT\"\n
PathsGlobs
[project]\n...\nlicense-files = { paths = [\"LICENSE.txt\"] }\n
[project]\n...\nlicense-files = { globs = [\"LICENSES/*\"] }\n
"},{"location":"config/metadata/#ownership","title":"Ownership","text":"

The people or organizations considered to be the authors or maintainers of the project. The exact meaning is open to interpretation; it may list the original or primary authors, current maintainers, or owners of the package. If the values are the same, prefer only the use of the authors field.

pyproject.toml
[project]\n...\nauthors = [\n{ name = \"...\", email = \"...\" },\n]\nmaintainers = [\n{ name = \"...\", email = \"...\" },\n]\n
"},{"location":"config/metadata/#keywords","title":"Keywords","text":"

The keywords used to assist in the discovery of the project.

pyproject.toml
[project]\n...\nkeywords = [\n\"...\",\n]\n
"},{"location":"config/metadata/#classifiers","title":"Classifiers","text":"

The trove classifiers that apply to the project.

pyproject.toml
[project]\n...\nclassifiers = [\n\"...\",\n]\n
"},{"location":"config/metadata/#urls","title":"URLs","text":"

A table of URLs where the key is the URL label and the value is the URL itself.

pyproject.toml
[project.urls]\nDocumentation = \"...\"\n\"Source code\" = \"...\"\n
"},{"location":"config/metadata/#dependencies","title":"Dependencies","text":"

The format is based on PEP 631. See the dependency specification section for more information.

Entries support context formatting and disallow direct references by default.

"},{"location":"config/metadata/#required","title":"Required","text":"pyproject.toml
[project]\n...\ndependencies = [\n\"...\",\n]\n
"},{"location":"config/metadata/#optional","title":"Optional","text":"pyproject.toml
[project.optional-dependencies]\noption1 = [\n\"...\",\n]\noption2 = [\n\"...\",\n]\n
"},{"location":"config/metadata/#entry-points","title":"Entry points","text":"

Entry points are a mechanism for the project to advertise components it provides to be discovered and used by other code.

"},{"location":"config/metadata/#cli","title":"CLI","text":"

After installing projects that define CLI scripts, each key will be available along your PATH as a command that will call its associated object.

pyproject.toml
[project.scripts]\ncli-name = \"pkg.subpkg:func\"\n

Using the above example, running cli-name would essentially execute the following Python script:

import sys\n\nfrom pkg.subpkg import func\n\nsys.exit(func())\n
"},{"location":"config/metadata/#gui","title":"GUI","text":"

GUI scripts are exactly the same as CLI scripts except on Windows, where they are handled specially so that they can be started without a console.

pyproject.toml
[project.gui-scripts]\ngui-name = \"pkg.subpkg:func\"\n
"},{"location":"config/metadata/#plugins","title":"Plugins","text":"pyproject.toml
[project.entry-points.plugin-namespace]\nplugin-name1 = \"pkg.subpkg1\"\nplugin-name2 = \"pkg.subpkg2:func\"\n
"},{"location":"config/metadata/#dynamic","title":"Dynamic","text":"

If any metadata fields are set dynamically, like the version may be, then they must be listed here.

pyproject.toml
[project]\n...\ndynamic = [\n\"...\",\n]\n
"},{"location":"config/metadata/#metadata-options","title":"Metadata options","text":""},{"location":"config/metadata/#allowing-direct-references","title":"Allowing direct references","text":"

By default, dependencies are not allowed to define direct references. To disable this check, set allow-direct-references to true:

pyproject.toml hatch.toml
[tool.hatch.metadata]\nallow-direct-references = true\n
[metadata]\nallow-direct-references = true\n
"},{"location":"config/metadata/#allowing-ambiguous-features","title":"Allowing ambiguous features","text":"

By default, names of optional dependencies are normalized to prevent ambiguity. To disable this normalization, set allow-ambiguous-features to true:

pyproject.toml hatch.toml
[tool.hatch.metadata]\nallow-ambiguous-features = true\n
[metadata]\nallow-ambiguous-features = true\n

Deprecated

This option temporarily exists to provide better interoperability with tools that do not yet support PEP 685 and will be removed in the first minor release after Jan 1, 2024.

"},{"location":"config/project-templates/","title":"Project templates","text":"

You can control how new projects are created by the new command using Hatch's config file.

"},{"location":"config/project-templates/#author","title":"Author","text":"config.toml
[template]\nname = \"...\"\nemail = \"...\"\n
"},{"location":"config/project-templates/#licenses","title":"Licenses","text":"config.toml
[template.licenses]\nheaders = true\ndefault = [\n\"MIT\",\n]\n

The list of licenses should be composed of SPDX identifiers. If multiple licenses are specified, then they will be placed in a LICENSES directory.

"},{"location":"config/project-templates/#options","title":"Options","text":""},{"location":"config/project-templates/#tests","title":"Tests","text":"

This adds a tests directory with environments for testing and linting.

config.toml
[template.plugins.default]\ntests = true\n
"},{"location":"config/project-templates/#ci","title":"CI","text":"

This adds a GitHub Actions workflow that runs tests on all platforms using modern versions of Python.

config.toml
[template.plugins.default]\nci = false\n
"},{"location":"config/project-templates/#src-layout","title":"src layout","text":"

See this blog post.

config.toml
[template.plugins.default]\nsrc-layout = true\n
"},{"location":"config/project-templates/#feature-flags","title":"Feature flags","text":""},{"location":"config/project-templates/#command-line-interface","title":"Command line interface","text":"

The --cli flag adds a CLI backed by Click that can also be invoked with python -m <PKG_NAME>.

"},{"location":"config/environment/advanced/","title":"Advanced environment configuration","text":""},{"location":"config/environment/advanced/#context-formatting","title":"Context formatting","text":"

All environments support the following extra context formatting fields:

Field Description env_name The name of the environment env_type The type of environment matrix Its modifier selects the value of that matrix variable. If the environment is not part of a matrix or was not generated with the variable, you must specify a default value as an additional modifier e.g. {matrix:version:v1.0.0}. verbosity The integer verbosity value of Hatch. A flag modifier is supported that will render the value as a CLI flag e.g. -2 becomes -qq, 1 becomes -v, and 0 becomes an empty string. An additional flag integer modifier may be used to adjust the verbosity level. For example, if you wanted to make a command quiet by default, you could use {verbosity:flag:-1} within the command. args For executed commands only, any extra command line arguments with an optional default modifier if none were provided"},{"location":"config/environment/advanced/#matrix","title":"Matrix","text":"

Environments can define a series of matrices with the matrix option:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"pytest\"\n]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeature = [\"foo\", \"bar\"]\n
[envs.test]\ndependencies = [\n\"pytest\"\n]\n\n[[envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[envs.test.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeature = [\"foo\", \"bar\"]\n

Doing so will result in the product of each variable combination being its own environment.

"},{"location":"config/environment/advanced/#naming","title":"Naming","text":"

The name of the generated environments will be the variable values of each combination separated by hyphens, altogether prefixed by <ENV_NAME>.. For example, the following configuration:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\nversion = [\"42\"]\nfeature = [\"foo\", \"bar\"]\n
[[envs.test.matrix]]\nversion = [\"42\"]\nfeature = [\"foo\", \"bar\"]\n

would indicate the following unique environments:

test.42-foo\ntest.42-bar\n

The exceptions to this format are described below.

"},{"location":"config/environment/advanced/#python-variables","title":"Python variables","text":"

If the variables py or python are specified, then they will rank first in the product result and will be prefixed by py if the value is not. For example, the following configuration:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\nversion = [\"42\"]\npython = [\"3.9\", \"pypy3\"]\n
[[envs.test.matrix]]\nversion = [\"42\"]\npython = [\"3.9\", \"pypy3\"]\n

would generate the following environments:

test.py3.9-42\ntest.pypy3-42\n

Note

The value of this variable sets the Python version.

"},{"location":"config/environment/advanced/#name-formatting","title":"Name formatting","text":"

You can set the matrix-name-format option to modify how each variable part is formatted which recognizes the placeholders {variable} and {value}. For example, the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\nmatrix-name-format = \"{variable}_{value}\"\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"42\"]\nfeature = [\"foo\", \"bar\"]\n
[envs.test]\nmatrix-name-format = \"{variable}_{value}\"\n\n[[envs.test.matrix]]\nversion = [\"42\"]\nfeature = [\"foo\", \"bar\"]\n

would produce the following environments:

test.version_42-feature_foo\ntest.version_42-feature_bar\n

By default this option is set to {value}.

"},{"location":"config/environment/advanced/#default-environment","title":"Default environment","text":"

If the default environment defines matrices, then the generated names will not be prefixed by the environment name. This can be useful for projects that only need a single series of matrices without any standalone environments.

"},{"location":"config/environment/advanced/#selection","title":"Selection","text":"

Rather than selecting a single generated environment, you can select the root environment to target all of them. For example, if you have the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n]\n\n[tool.hatch.envs.test.scripts]\ncov = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n
[envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n]\n\n[envs.test.scripts]\ncov = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'\n\n[[envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n

you could then run your tests consecutively in all 4 environments with:

hatch run test:cov\n
"},{"location":"config/environment/advanced/#option-overrides","title":"Option overrides","text":"

You can modify options based on the conditions of different sources like matrix variables with the overrides table, using dotted key syntax for each declaration:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>.overrides]\n<SOURCE>.<CONDITION>.<OPTION> = <VALUE>\n
[envs.<ENV_NAME>.overrides]\n<SOURCE>.<CONDITION>.<OPTION> = <VALUE>\n

The type of the selected option determines the types of values.

"},{"location":"config/environment/advanced/#platform-overrides","title":"Platform overrides","text":"

Options can be modified based on the current platform using the platform source.

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nplatform.windows.scripts = [\n'run=pytest -m \"not io_uring\"',\n]\n
[envs.test.overrides]\nplatform.windows.scripts = [\n'run=pytest -m \"not io_uring\"',\n]\n

The following platforms are supported:

"},{"location":"config/environment/advanced/#environment-variable-overrides","title":"Environment variable overrides","text":"

Environment variables can modify options using the env source.

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nenv.GITHUB_ACTIONS.dev-mode = { value = false, if = [\"true\"] }\n
[envs.test.overrides]\nenv.GITHUB_ACTIONS.dev-mode = { value = false, if = [\"true\"] }\n
"},{"location":"config/environment/advanced/#matrix-variable-overrides","title":"Matrix variable overrides","text":"

The matrix variables used to generate each environment can be used to modify options within using the matrix source.

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nmatrix.version.env-vars = \"PRODUCT_VERSION\"\nmatrix.auth.features = [\n{ value = \"oauth\", if = [\"oauth2\"] },\n{ value = \"kerberos\", if = [\"krb5\"] },\n]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"legacy\", \"latest\"]\nauth = [\"oauth2\", \"krb5\", \"noauth\"]\n
[envs.test.overrides]\nmatrix.version.env-vars = \"PRODUCT_VERSION\"\nmatrix.auth.features = [\n{ value = \"oauth\", if = [\"oauth2\"] },\n{ value = \"kerberos\", if = [\"kerberos\"] },\n]\n\n[[envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"legacy\", \"latest\"]\nauth = [\"oauth2\", \"kerberos\", \"noauth\"]\n
"},{"location":"config/environment/advanced/#name-overrides","title":"Name overrides","text":"

When a matrix is defined, the name source can be used for regular expression matching on the generated name, minus the prefix for non-default environments.

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nname.\"^0\".env-vars = \"TESTING_UNSTABLE=true\"\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"0.1.0\", \"0.2.0\", \"1.0.0\"]\n
[envs.test.overrides]\nname.\"^0\".env-vars = \"TESTING_UNSTABLE=true\"\n\n[[envs.test.matrix]]\nversion = [\"0.1.0\", \"0.2.0\", \"1.0.0\"]\n
"},{"location":"config/environment/advanced/#types","title":"Types","text":""},{"location":"config/environment/advanced/#overwriting","title":"Overwriting","text":"

Rather than supplementing the values within mapping types or array types, you can overwrite the option as a whole by prefixing the name with set-:

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nmatrix.foo.set-platforms = [\"macos\", \"linux\"]\n
[envs.test.overrides]\nmatrix.foo.set-platforms = [\"macos\", \"linux\"]\n

When overwriting entire options or keys within mappings, override sources are applied in the following order:

  1. platform
  2. environment variables
  3. matrix variables
  4. names
"},{"location":"config/environment/advanced/#conditions","title":"Conditions","text":"

You may specify certain extra keys for any inline table that will determine whether or not to apply that entry. These modifiers may be combined with others and any negative evaluation will immediately cause the entry to be skipped.

"},{"location":"config/environment/advanced/#allowed-values","title":"Allowed values","text":"

The if key represents the allowed values for that condition. If the value of the condition is not listed, then that entry will not be applied:

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nmatrix.version.python = { value = \"pypy\", if = [\"3.14\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
[envs.test.overrides]\nmatrix.version.python = { value = \"pypy\", if = [\"3.14\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
"},{"location":"config/environment/advanced/#specific-platforms","title":"Specific platforms","text":"

The platform key represents the desired platforms. If the current platform is not listed, then that entry will not be applied:

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nenv.EXPERIMENTAL.python = { value = \"pypy\", if = [\"1\"], platform = [\"macos\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"], platform = [\"linux\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
[envs.test.overrides]\nenv.EXPERIMENTAL.python = { value = \"pypy\", if = [\"1\"], platform = [\"macos\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"], platform = [\"linux\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
"},{"location":"config/environment/advanced/#required-environment-variables","title":"Required environment variables","text":"

The env key represents the required environment variables. If any of the listed environment variables are not set or the defined value does not match, then that entry will not be applied:

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nplatform.windows.python = { value = \"pypy\", env = [\"EXPERIMENTAL\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"], env = [\"FOO\", \"BAR=BAZ\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
[envs.test.overrides]\nplatform.windows.python = { value = \"pypy\", env = [\"EXPERIMENTAL\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"], env = [\"FOO\", \"BAR=BAZ\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
"},{"location":"config/environment/overview/","title":"Environment configuration","text":"

All environments are defined as sections within the tool.hatch.envs table.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\n
[envs.<ENV_NAME>]\n

The storage location for environments is completely configurable.

Unless an environment is explicitly selected on the command line, the default environment will be used. The type of this environment defaults to virtual.

"},{"location":"config/environment/overview/#inheritance","title":"Inheritance","text":"

All environments inherit from the environment defined by its template option, which defaults to default.

So for the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.foo]\ntype = \"baz\"\nskip-install = true\n\n[tool.hatch.envs.bar]\ntemplate = \"foo\"\nskip-install = false\n
[envs.foo]\ntype = \"baz\"\nskip-install = true\n\n[envs.bar]\ntemplate = \"foo\"\nskip-install = false\n

the environment bar will be of type baz with skip-install set to false.

Note

Environments do not inherit matrices.

"},{"location":"config/environment/overview/#self-referential-environments","title":"Self-referential environments","text":"

You can disable inheritance by setting template to the environment's own name:

pyproject.toml hatch.toml
[tool.hatch.envs.foo]\ntemplate = \"foo\"\n
[envs.foo]\ntemplate = \"foo\"\n
"},{"location":"config/environment/overview/#detached-environments","title":"Detached environments","text":"

A common use case is standalone environments that do not require inheritance nor the installation of the project, such as for linting or sometimes building documentation. Enabling the detached option will make the environment self-referential and will skip project installation:

pyproject.toml hatch.toml
[tool.hatch.envs.lint]\ndetached = true\n
[envs.lint]\ndetached = true\n
"},{"location":"config/environment/overview/#dependencies","title":"Dependencies","text":"

You can install dependencies in addition to the ones defined by your project's metadata. Entries support context formatting.

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n\"pytest-mock\",\n]\n
[envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n\"pytest-mock\",\n]\n

If you define environments with dependencies that only slightly differ from their inherited environments, you can use the extra-dependencies option to avoid redeclaring the dependencies option:

pyproject.toml hatch.toml
[tool.hatch.envs.default]\ndependencies = [\n\"foo\",\n\"bar\",\n]\n\n[tool.hatch.envs.experimental]\nextra-dependencies = [\n\"baz\",\n]\n
[envs.default]\ndependencies = [\n\"foo\",\n\"bar\",\n]\n\n[envs.experimental]\nextra-dependencies = [\n\"baz\",\n]\n

Tip

Hatch uses pip to install dependencies so any configuration it supports Hatch does as well. For example, if you wanted to only use a private repository you could set the PIP_INDEX_URL environment variable.

"},{"location":"config/environment/overview/#installation","title":"Installation","text":""},{"location":"config/environment/overview/#features","title":"Features (extras)","text":"

If your project defines optional dependencies, you can select which groups to install using the features option:

pyproject.toml hatch.toml
[tool.hatch.envs.nightly]\nfeatures = [\n\"server\",\n\"grpc\",\n]\n
[envs.nightly]\nfeatures = [\n\"server\",\n\"grpc\",\n]\n

Note

Features/optional dependencies are also known as extras in other tools.

"},{"location":"config/environment/overview/#dev-mode","title":"Dev mode","text":"

By default, environments will always reflect the current state of your project on disk. Set dev-mode to false to disable this behavior:

pyproject.toml hatch.toml
[tool.hatch.envs.static]\ndev-mode = false\n
[envs.static]\ndev-mode = false\n
"},{"location":"config/environment/overview/#skip-install","title":"Skip install","text":"

By default, environments will install your project during creation. To ignore this step, set skip-install to true:

pyproject.toml hatch.toml
[tool.hatch.envs.lint]\nskip-install = true\n
[envs.lint]\nskip-install = true\n
"},{"location":"config/environment/overview/#environment-variables","title":"Environment variables","text":""},{"location":"config/environment/overview/#defined","title":"Defined","text":"

You can define environment variables with the env-vars option:

pyproject.toml hatch.toml
[tool.hatch.envs.docs]\ndependencies = [\n\"mkdocs\"\n]\n[tool.hatch.envs.docs.env-vars]\nSOURCE_DATE_EPOCH = \"1580601600\"\n
[envs.docs]\ndependencies = [\n\"mkdocs\"\n]\n[envs.docs.env-vars]\nSOURCE_DATE_EPOCH = \"1580601600\"\n

Values support context formatting.

"},{"location":"config/environment/overview/#filters","title":"Filters","text":"

By default, environments will have access to all environment variables. You can filter with wildcard patterns using the env-include/env-exclude options:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nenv-include = [\n\"FOO*\",\n]\nenv-exclude = [\n\"BAR\",\n]\n
[envs.<ENV_NAME>]\nenv-include = [\n\"FOO*\",\n]\nenv-exclude = [\n\"BAR\",\n]\n

Exclusion patterns take precedence but will never affect defined environment variables.

"},{"location":"config/environment/overview/#scripts","title":"Scripts","text":"

You can define named scripts that may be executed or referenced at the beginning of other scripts. Context formatting is supported.

For example, in the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n\"pytest-mock\",\n]\n[tool.hatch.envs.test.scripts]\nrun-coverage = \"pytest --cov-config=pyproject.toml --cov=pkg --cov=tests\"\nrun = \"run-coverage --no-cov\"\n
[envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n\"pytest-mock\",\n]\n[envs.test.scripts]\nrun-coverage = \"pytest --cov-config=pyproject.toml --cov=pkg --cov=tests\"\nrun = \"run-coverage --no-cov\"\n

the run script would be expanded to:

pytest --cov-config=pyproject.toml --cov=pkg --cov=tests --no-cov\n

Scripts can also be defined as an array of strings.

pyproject.toml hatch.toml
[tool.hatch.envs.style]\ndetached = true\ndependencies = [\n\"flake8\",\n\"black\",\n\"isort\",\n]\n[tool.hatch.envs.style.scripts]\ncheck = [\n\"flake8 .\",\n\"black --check --diff .\",\n\"isort --check-only --diff .\",\n]\nfmt = [\n\"isort .\",\n\"black .\",\n\"check\",\n]\n
[envs.style]\ndetached = true\ndependencies = [\n\"flake8\",\n\"black\",\n\"isort\",\n]\n[envs.style.scripts]\ncheck = [\n\"flake8 .\",\n\"black --check --diff .\",\n\"isort --check-only --diff .\",\n]\nfmt = [\n\"isort .\",\n\"black .\",\n\"check\",\n]\n

Similar to make, you can ignore the exit code of commands that start with - (a hyphen). For example, the script error defined by the following configuration would halt after the second command with 3 as the exit code:

pyproject.toml hatch.toml
[tool.hatch.envs.test.scripts]\nerror = [\n\"- exit 1\",\n\"exit 3\",\n\"exit 0\",\n]\n
[envs.test.scripts]\nerror = [\n\"- exit 1\",\n\"exit 3\",\n\"exit 0\",\n]\n

Tip

Individual scripts inherit from parent environments just like options.

"},{"location":"config/environment/overview/#commands","title":"Commands","text":"

All commands are able to use any defined scripts. Also like scripts, context formatting is supported and the exit code of commands that start with a hyphen will be ignored.

"},{"location":"config/environment/overview/#pre-install","title":"Pre-install","text":"

You can run commands immediately before environments install your project.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\npre-install-commands = [\n\"...\",\n]\n
[envs.<ENV_NAME>]\npre-install-commands = [\n\"...\",\n]\n
"},{"location":"config/environment/overview/#post-install","title":"Post-install","text":"

You can run commands immediately after environments install your project.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\npost-install-commands = [\n\"...\",\n]\n
[envs.<ENV_NAME>]\npost-install-commands = [\n\"...\",\n]\n
"},{"location":"config/environment/overview/#python-version","title":"Python version","text":"

The python option specifies which version of Python to use, or an absolute path to a Python interpreter:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\npython = \"3.10\"\n
[envs.<ENV_NAME>]\npython = \"3.10\"\n

All environment types should respect this option.

"},{"location":"config/environment/overview/#supported-platforms","title":"Supported platforms","text":"

The platforms option indicates the operating systems with which the environment is compatible:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nplatforms = [\"linux\", \"windows\", \"macos\"]\n
[envs.<ENV_NAME>]\nplatforms = [\"linux\", \"windows\", \"macos\"]\n

The following platforms are supported:

If unspecified, the environment is assumed to be compatible with all platforms.

"},{"location":"config/environment/overview/#description","title":"Description","text":"

The description option is purely informational and is displayed in the output of the env show command:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\ndescription = \"\"\"\nLorem ipsum ...\n\"\"\"\n
[envs.<ENV_NAME>]\ndescription = \"\"\"\nLorem ipsum ...\n\"\"\"\n
"},{"location":"config/environment/overview/#type","title":"Type","text":"

An environment's type determines which environment plugin will be used for management. The only built-in environment type is virtual, which uses virtual Python environments.

"},{"location":"history/hatch/","title":"Hatch history","text":"

All notable changes to Hatch will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

"},{"location":"history/hatch/#unreleased","title":"Unreleased","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.7.0","title":"1.7.0 - 2023-04-03","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.6.3","title":"1.6.3 - 2022-10-24","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.6.2","title":"1.6.2 - 2022-10-20","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.6.1","title":"1.6.1 - 2022-10-16","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.6.0","title":"1.6.0 - 2022-10-08","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.5.0","title":"1.5.0 - 2022-08-28","text":"

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.4.2","title":"1.4.2 - 2022-08-16","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.4.1","title":"1.4.1 - 2022-08-13","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.4.0","title":"1.4.0 - 2022-08-06","text":"

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.3.1","title":"1.3.1 - 2022-07-11","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.3.0","title":"1.3.0 - 2022-07-10","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.2.1","title":"1.2.1 - 2022-05-30","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.2.0","title":"1.2.0 - 2022-05-22","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.1.2","title":"1.1.2 - 2022-05-20","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.1.1","title":"1.1.1 - 2022-05-12","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.1.0","title":"1.1.0 - 2022-05-12","text":"

Changed:

Added:

"},{"location":"history/hatch/#hatch-v1.0.0","title":"1.0.0 - 2022-04-28","text":"

This is the first stable release of Hatch v1, a complete rewrite. Enjoy!

"},{"location":"history/hatchling/","title":"Hatchling history","text":"

All notable changes to Hatchling will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

"},{"location":"history/hatchling/#unreleased","title":"Unreleased","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.18.0","title":"1.18.0 - 2023-06-12","text":"

Changed:

Added:

"},{"location":"history/hatchling/#hatchling-v1.17.1","title":"1.17.1 - 2023-06-03","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.17.0","title":"1.17.0 - 2023-05-12","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.16.1","title":"1.16.1 - 2023-05-11","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.16.0","title":"1.16.0 - 2023-05-11","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.15.0","title":"1.15.0 - 2023-05-09","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.14.1","title":"1.14.1 - 2023-04-23","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.14.0","title":"1.14.0 - 2023-04-02","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.13.0","title":"1.13.0 - 2023-02-09","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.12.2","title":"1.12.2 - 2023-01-05","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.12.1","title":"1.12.1 - 2022-12-31","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.12.0","title":"1.12.0 - 2022-12-30","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.11.1","title":"1.11.1 - 2022-10-19","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.11.0","title":"1.11.0 - 2022-10-08","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.10.0","title":"1.10.0 - 2022-09-18","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.9.0","title":"1.9.0 - 2022-09-09","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.8.1","title":"1.8.1 - 2022-08-25","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.8.0","title":"1.8.0 - 2022-08-16","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.7.1","title":"1.7.1 - 2022-08-13","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.7.0","title":"1.7.0 - 2022-08-12","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.6.0","title":"1.6.0 - 2022-07-23","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.5.0","title":"1.5.0 - 2022-07-11","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.4.1","title":"1.4.1 - 2022-07-04","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.4.0","title":"1.4.0 - 2022-07-03","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.3.1","title":"1.3.1 - 2022-05-30","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.3.0","title":"1.3.0 - 2022-05-22","text":"

Removed:

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.2.0","title":"1.2.0 - 2022-05-20","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.1.0","title":"1.1.0 - 2022-05-19","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.0.0","title":"1.0.0 - 2022-05-17","text":"

Changed:

Added:

"},{"location":"history/hatchling/#hatchling-v0.25.1","title":"0.25.1 - 2022-06-14","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v0.25.0","title":"0.25.0 - 2022-05-15","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v0.24.0","title":"0.24.0 - 2022-04-28","text":"

This is the initial public release of the Hatchling build system. Support for Python 2 will be dropped in version 1.

"},{"location":"how-to/environment/package-indices/","title":"Package indices","text":"

Most Hatch environment types, like the default virtual, simply use pip to install dependencies. Therefore, you can use the standard environment variables that influence pip's behavior to choose where to search for packages.

Here's an example of setting up the default environment to look at 2 private indices (using context formatting for authentication) before finally falling back to PyPI:

pyproject.toml hatch.toml
[tool.hatch.envs.default.env-vars]\nPIP_INDEX_URL = \"https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group1_path>/-/packages/pypi/simple/\"\nPIP_EXTRA_INDEX_URL = \"https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group2_path>/-/packages/pypi/simple/ https://pypi.org/simple/\"\n
[envs.default.env-vars]\nPIP_INDEX_URL = \"https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group1_path>/-/packages/pypi/simple/\"\nPIP_EXTRA_INDEX_URL = \"https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group2_path>/-/packages/pypi/simple/ https://pypi.org/simple/\"\n
"},{"location":"how-to/plugins/testing-builds/","title":"Testing builds","text":"

For testing Hatchling plugins, you'll usually want to generate a project to execute builds as a real user would. For example, as a minimal pytest fixture:

from pathlib import Path\n\nimport pytest\n\n\n@pytest.fixture\ndef new_project(tmp_path):\n    project_dir = tmp_path / 'my-app'\n    project_dir.mkdir()\n\n    project_file = project_dir / 'pyproject.toml'\n    project_file.write_text(\n        f\"\"\"\\\n[build-system]\nrequires = [\"hatchling\", \"hatch-plugin-name @ {Path.cwd().as_uri()}\"]\nbuild-backend = \"hatchling.build\"\n\n[project]\nname = \"my-app\"\nversion = \"0.1.0\"\n\"\"\",\n        encoding='utf-8',\n    )\n    ...\n

The issue with this is that after the first test session, the project will be forever cached by pip based on the file path. Therefore, subsequent tests runs will never use updated code.

To invalidate the cache, copy your code to a new path for every test session:

import shutil\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nimport pytest\n\n\n@pytest.fixture(scope='session')\ndef plugin_dir():\n    with TemporaryDirectory() as d:\n        directory = Path(d, 'plugin')\n        shutil.copytree(\n            Path.cwd(), directory, ignore=shutil.ignore_patterns('.git')\n        )\n\n        yield directory.resolve()\n\n\n@pytest.fixture\ndef new_project(tmp_path, plugin_dir):\n    project_dir = tmp_path / 'my-app'\n    project_dir.mkdir()\n\n    project_file = project_dir / 'pyproject.toml'\n    project_file.write_text(\n        f\"\"\"\\\n[build-system]\nrequires = [\"hatchling\", \"hatch-plugin-name @ {plugin_dir.as_uri()}\"]\nbuild-backend = \"hatchling.build\"\n\n[project]\nname = \"my-app\"\nversion = \"0.1.0\"\n\"\"\",\n        encoding='utf-8',\n    )\n    ...\n

Note

This example chooses to ignore copying .git for performance reasons. You may want to ignore more patterns, or copy only specific paths like this plugin does.

"},{"location":"meta/authors/","title":"Authors","text":""},{"location":"meta/authors/#maintainers","title":"Maintainers","text":""},{"location":"meta/authors/#contributors","title":"Contributors","text":""},{"location":"meta/faq/","title":"FAQ","text":""},{"location":"meta/faq/#interoperability","title":"Interoperability","text":"

Q: What is the risk of lock-in?

A: Not much! Other than the plugin system, everything uses Python's established standards by default. Project metadata is based entirely on PEP 621/PEP 631, the build system is compatible with PEP 517/PEP 660, versioning uses the scheme specified by PEP 440, dependencies are defined with PEP 508 strings, and environments use virtualenv.

Q: Must one use all features?

A: No, all features are optional! You can use just the build system, publish wheels and source distributions that were built by other tools, only use the environment management, etc.

"},{"location":"meta/faq/#libraries-vs-applications","title":"Libraries vs applications","text":"

Q: Are workflows for both libraries and applications supported?

A: Yes, mostly! Applications can utilize environment management just like libraries, and plugins can be used to build projects in arbitrary formats or publish artifacts to arbitrary destinations.

The only caveat is that currently there is no support for re-creating an environment given a set of dependencies in a reproducible manner. Although a standard lock file format may be far off since PEP 665 was rejected, resolving capabilities are coming to pip. When that is stabilized, Hatch will add locking functionality and dedicated documentation for managing applications.

"},{"location":"meta/faq/#tool-migration","title":"Tool migration","text":"

Q: How to migrate to Hatch?

"},{"location":"meta/faq/#build-system","title":"Build system","text":"SetuptoolsHatch setup.py MANIFEST.in
import os\nfrom io import open\n\nfrom setuptools import find_packages, setup\n\nabout = {}\nwith open(os.path.join('src', 'foo', '__about__.py'), 'r', 'utf-8') as f:\n    exec(f.read(), about)\n\nwith open('README.md', 'r', 'utf-8') as f:\n    readme = f.read()\n\nsetup(\n    # Metadata\n    name='foo',\n    version=about['__version__'],\n    description='...',\n    long_description=readme,\n    long_description_content_type='text/markdown',\n    author='...',\n    author_email='...',\n    project_urls={\n        'Documentation': '...',\n        'Source': '...',\n    },\n    classifiers=[\n        '...',\n    ],\n    keywords=[\n        '...',\n    ],\n    python_requires='>=3.8',\n    install_requires=[\n        '...',\n    ],\n    extras_require={\n        'feature': ['...'],\n    },\n\n    # Packaging\n    packages=find_packages(where='src'),\n    package_dir={'': 'src'},\n    package_data={\n        'foo': ['py.typed'],\n    },\n    zip_safe=False,\n    entry_points={\n        'console_scripts': [\n            'foo = foo.cli:main',\n        ],\n    },\n)\n
graft tests\n\nglobal-exclude *.py[cod] __pycache__\n
pyproject.toml
[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n\n[project]\nname = \"foo\"\ndescription = \"...\"\nreadme = \"README.md\"\nauthors = [\n{ name = \"...\", email = \"...\" },\n]\nclassifiers = [\n\"...\",\n]\nkeywords = [\n\"...\",\n]\nrequires-python = \">=3.8\"\ndependencies = [\n\"...\",\n]\ndynamic = [\"version\"]\n\n[project.urls]\nDocumentation = \"...\"\nSource = \"...\"\n\n[project.optional-dependencies]\nfeature = [\"...\"]\n\n[project.scripts]\nfoo = \"foo.cli:main\"\n\n[tool.hatch.version]\npath = \"src/foo/__about__.py\"\n\n[tool.hatch.build.targets.sdist]\ninclude = [\n\"/src\",\n\"/tests\",\n]\n
"},{"location":"meta/faq/#environments","title":"Environments","text":"ToxHatch

Invocation:

tox\n
tox.ini
[tox]\nenvlist =\npy{27,38}-{42,3.14}\npy{38,39}-{9000}-{foo,bar}\n\n[testenv]\nusedevelop = true\ndeps =\ncoverage[toml]\npytest\npytest-cov\nfoo: cryptography\ncommands =\npytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests {posargs}\nsetenv =\n3.14: PRODUCT_VERSION=3.14\n42: PRODUCT_VERSION=42\n9000: PRODUCT_VERSION=9000\n{foo,bar}: EXPERIMENTAL=true\n

Invocation:

hatch run test\n
hatch.toml pyproject.toml
[envs.default]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n]\n\n[envs.default.scripts]\ntest = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'\n\n[envs.default.overrides]\nmatrix.version.env-vars = \"PRODUCT_VERSION\"\nmatrix.features.env-vars = \"EXPERIMENTAL=true\"\nmatrix.features.dependencies = [\n{ value = \"cryptography\", if = [\"foo\"] },\n]\n\n[[envs.default.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[envs.default.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeatures = [\"foo\", \"bar\"]\n
[tool.hatch.envs.default]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n]\n\n[tool.hatch.envs.default.scripts]\ntest = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'\n\n[tool.hatch.envs.default.overrides]\nmatrix.version.env-vars = \"PRODUCT_VERSION\"\nmatrix.features.env-vars = \"EXPERIMENTAL=true\"\nmatrix.features.dependencies = [\n{ value = \"cryptography\", if = [\"foo\"] },\n]\n\n[[tool.hatch.envs.default.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[tool.hatch.envs.default.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeatures = [\"foo\", \"bar\"]\n
"},{"location":"plugins/about/","title":"Plugins","text":"

Hatch utilizes pluggy for its plugin functionality.

"},{"location":"plugins/about/#overview","title":"Overview","text":"

All plugins provide registration hooks that return one or more classes that inherit from a particular type interface.

Each registration hook must be decorated by Hatch's hook marker. For example, if you wanted to create a new kind of environment you could do:

hooks.py
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialEnvironment\n\n\n@hookimpl\ndef hatch_register_environment():\n    return SpecialEnvironment\n

The hooks can return a single class or a list of classes.

Every class must define an attribute called PLUGIN_NAME that users will select when they wish to use the plugin. So in the example above, the class might be defined like:

plugin.py
...\nclass SpecialEnvironment(...):\n    PLUGIN_NAME = 'special'\n    ...\n
"},{"location":"plugins/about/#project-configuration","title":"Project configuration","text":""},{"location":"plugins/about/#naming","title":"Naming","text":"

It is recommended that plugin project names are prefixed with hatch-. For example, if you wanted to make a plugin that provides some functionality for a product named foo you might do:

pyproject.toml
[project]\nname = \"hatch-foo\"\n
"},{"location":"plugins/about/#discovery","title":"Discovery","text":"

You'll need to define your project as a Python plugin for Hatch:

pyproject.toml
[project.entry-points.hatch]\nfoo = \"pkg.hooks\"\n

The name of the plugin should be the project name (excluding any hatch- prefix) and the path should represent the module that contains the registration hooks.

"},{"location":"plugins/about/#classifier","title":"Classifier","text":"

Add Framework :: Hatch to your project's classifiers to make it easy to search for Hatch plugins:

pyproject.toml
[project]\nclassifiers = [\n...\n\"Framework :: Hatch\",\n...\n]\n
"},{"location":"plugins/about/#types","title":"Types","text":""},{"location":"plugins/about/#hatchling","title":"Hatchling","text":"

These are all involved in building projects and therefore any defined dependencies are automatically installed in each build environment.

"},{"location":"plugins/about/#hatch","title":"Hatch","text":"

These must be installed in the same environment as Hatch itself.

"},{"location":"plugins/utilities/","title":"Plugin utilities","text":""},{"location":"plugins/utilities/#hatchling.builders.utils.get_reproducible_timestamp","title":"hatchling.builders.utils.get_reproducible_timestamp() -> int","text":"

Returns an int derived from the SOURCE_DATE_EPOCH environment variable; see https://reproducible-builds.org/specs/source-date-epoch/.

The default value will always be: 1580601600

Source code in backend/src/hatchling/builders/utils.py
def get_reproducible_timestamp() -> int:\n\"\"\"\n    Returns an `int` derived from the `SOURCE_DATE_EPOCH` environment variable; see\n    https://reproducible-builds.org/specs/source-date-epoch/.\n    The default value will always be: `1580601600`\n    \"\"\"\nreturn int(os.environ.get('SOURCE_DATE_EPOCH', '1580601600'))\n
"},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig","title":"BuilderConfig","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.directory","title":"directory: str property","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.ignore_vcs","title":"ignore_vcs: bool property","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.reproducible","title":"reproducible: bool property","text":"

Whether or not the target should be built in a reproducible manner, defaulting to true.

"},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.dev_mode_dirs","title":"dev_mode_dirs: list[str] property","text":"

Directories which must be added to Python's search path in dev mode.

"},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.versions","title":"versions: list[str] property","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.dependencies","title":"dependencies: list[str] property","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.default_include","title":"default_include() -> list","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.default_exclude","title":"default_exclude() -> list","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.default_packages","title":"default_packages() -> list","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.default_only_include","title":"default_only_include() -> list","text":""},{"location":"plugins/utilities/#hatchling.bridge.app.Application","title":"Application","text":"

The way output is displayed can be configured by users.

Important

Never import this directly; Hatch judiciously decides if a type of plugin requires the capabilities herein and will grant access via an attribute.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.verbosity","title":"verbosity: int property","text":"

The verbosity level of the application, with 0 as the default.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.abort","title":"abort(message: str = '', code: int = 1, **kwargs: Any) -> None","text":"

Terminate the program with the given return code.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_debug","title":"display_debug(message: str = '', level: int = 1, **kwargs: Any) -> None","text":"

Meant to be used for messages that are not useful for most user experiences. The level option must be between 1 and 3 (inclusive).

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_error","title":"display_error(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages indicating some unrecoverable error.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_info","title":"display_info(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages conveying basic information.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_success","title":"display_success(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages indicating some positive outcome.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_waiting","title":"display_waiting(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages shown before potentially time consuming operations.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_warning","title":"display_warning(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages conveying important information.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform","title":"Platform","text":""},{"location":"plugins/utilities/#hatch.utils.platform.Platform.default_shell","title":"default_shell: str property","text":"

Returns the default shell of the system.

On Windows systems first try the SHELL environment variable, if present, followed by the COMSPEC environment variable, defaulting to cmd. On all other platforms only the SHELL environment variable will be used, defaulting to bash.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.modules","title":"modules: LazilyLoadedModules property","text":"

Accessor for lazily loading modules that either take multiple milliseconds to import (like shutil and subprocess) or are not used on all platforms (like shlex).

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.home","title":"home: Path property","text":"

The user's home directory as a path-like object.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.name","title":"name: str property","text":"

One of the following:

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.windows","title":"windows: bool property","text":"

Indicates whether Hatch is running on Windows.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.macos","title":"macos: bool property","text":"

Indicates whether Hatch is running on macOS.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.linux","title":"linux: bool property","text":"

Indicates whether Hatch is running on neither Windows nor macOS.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.format_for_subprocess","title":"format_for_subprocess(command: str | list[str], *, shell: bool) -> str | list[str]","text":"

Format the given command in a cross-platform manner for immediate consumption by subprocess utilities.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.run_command","title":"run_command(command: str | list[str], *, shell: bool = False, **kwargs: Any) -> CompletedProcess","text":"

Equivalent to the standard library's subprocess.run, with the command first being properly formatted.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.check_command","title":"check_command(command: str | list[str], *, shell: bool = False, **kwargs: Any) -> CompletedProcess","text":"

Equivalent to run_command, but non-zero exit codes will gracefully end program execution.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.check_command_output","title":"check_command_output(command: str | list[str], *, shell: bool = False, **kwargs: Any) -> str","text":"

Equivalent to the output from the process returned by capture_process, but non-zero exit codes will gracefully end program execution.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.capture_process","title":"capture_process(command: str | list[str], *, shell: bool = False, **kwargs: Any) -> Popen","text":"

Equivalent to the standard library's subprocess.Popen, with all output captured by stdout and the command first being properly formatted.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.exit_with_command","title":"exit_with_command(command: list[str]) -> None","text":"

Run the given command and exit with its exit code. On non-Windows systems, this uses the standard library's os.execvp.

"},{"location":"plugins/utilities/#hatch.env.context.EnvironmentContextFormatter","title":"EnvironmentContextFormatter","text":""},{"location":"plugins/utilities/#hatch.env.context.EnvironmentContextFormatter.formatters","title":"formatters()","text":"

This returns a mapping of supported field names to their respective formatting functions. Each function accepts 2 arguments:

"},{"location":"plugins/build-hook/custom/","title":"Custom build hook","text":"

This is a custom class in a given Python file that inherits from the BuildHookInterface.

"},{"location":"plugins/build-hook/custom/#configuration","title":"Configuration","text":"

The build hook plugin name is custom.

pyproject.toml hatch.toml
[tool.hatch.build.hooks.custom]\n[tool.hatch.build.targets.<TARGET_NAME>.hooks.custom]\n
[build.hooks.custom]\n[build.targets.<TARGET_NAME>.hooks.custom]\n
"},{"location":"plugins/build-hook/custom/#options","title":"Options","text":"Option Default Description path hatch_build.py The path of the Python file"},{"location":"plugins/build-hook/custom/#example","title":"Example","text":"hatch_build.py
from hatchling.builders.hooks.plugin.interface import BuildHookInterface\n\n\nclass CustomBuildHook(BuildHookInterface):\n    ...\n

If multiple subclasses are found, you must define a function named get_build_hook that returns the desired build hook.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

"},{"location":"plugins/build-hook/reference/","title":"Build hook plugins","text":"

A build hook provides code that will be executed at various stages of the build process. See the documentation for build hook configuration.

"},{"location":"plugins/build-hook/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/build-hook/reference/#overview","title":"Overview","text":"

Build hooks run for every selected version of build targets.

The initialization stage occurs immediately before each build and the finalization stage occurs immediately after. Each stage has the opportunity to view or modify build data.

"},{"location":"plugins/build-hook/reference/#build-data","title":"Build data","text":"

Build data is a simple mapping whose contents can influence the behavior of builds. Which fields exist and are recognized depends on each build target.

The following fields are always present and recognized by the build system itself:

Field Type Description artifacts list[str] This is a list of extra artifact patterns and should generally only be appended to force_include dict[str, str] This is a mapping of extra forced inclusion paths, with this mapping taking precedence in case of conflicts build_hooks tuple[str, ...] This is an immutable sequence of the names of the configured build hooks and matches the order in which they run

Attention

While user-facing TOML options are hyphenated, build data fields should be named with underscores to allow plugins to use them as valid Python identifiers.

"},{"location":"plugins/build-hook/reference/#notes","title":"Notes","text":"

In some cases it may be necessary to use force_include rather than artifacts. For example, say that you want to install a lib.so directly at the root of site-packages and a project defines a package src/foo. If you create src/lib.so, there will never be a match because the directory traversal starts at src/foo rather than src. In that case you must do either:

build_data['force_include']['src/lib.so'] = 'src/lib.so'\n

or

build_data['force_include']['/absolute/path/to/src/lib.so'] = 'src/lib.so'\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface","title":"BuildHookInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.builders.hooks.plugin.interface import BuildHookInterface\n\n\nclass SpecialBuildHook(BuildHookInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialBuildHook\n\n\n@hookimpl\ndef hatch_register_build_hook():\n    return SpecialBuildHook\n
Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
class BuildHookInterface(Generic[BuilderConfigBound]):  # no cov\n\"\"\"\n    Example usage:\n    === \":octicons-file-code-16: plugin.py\"\n        ```python\n        from hatchling.builders.hooks.plugin.interface import BuildHookInterface\n        class SpecialBuildHook(BuildHookInterface):\n            PLUGIN_NAME = 'special'\n            ...\n        ```\n    === \":octicons-file-code-16: hooks.py\"\n        ```python\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialBuildHook\n        @hookimpl\n        def hatch_register_build_hook():\n            return SpecialBuildHook\n        ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(\nself,\nroot: str,\nconfig: dict[str, Any],\nbuild_config: BuilderConfigBound,\nmetadata: ProjectMetadata,\ndirectory: str,\ntarget_name: str,\napp: Application | None = None,\n) -> None:\nself.__root = root\nself.__config = config\nself.__build_config = build_config\nself.__metadata = metadata\nself.__directory = directory\nself.__target_name = target_name\nself.__app = app\n@property\ndef app(self) -> Application:\n\"\"\"\n        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).\n        \"\"\"\nif self.__app is None:\nfrom hatchling.bridge.app import Application\nself.__app = cast(Application, Application().get_safe_application())\nreturn self.__app\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict[str, Any]:\n\"\"\"\n        The cumulative hook configuration.\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.build.hooks.<PLUGIN_NAME>]\n            [tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [build.hooks.<PLUGIN_NAME>]\n            [build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]\n            ```\n        \"\"\"\nreturn self.__config\n@property\ndef metadata(self) -> ProjectMetadata:\n# Undocumented for now\nreturn self.__metadata\n@property\ndef build_config(self) -> BuilderConfigBound:\n\"\"\"\n        An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).\n        \"\"\"\nreturn self.__build_config\n@property\ndef directory(self) -> str:\n\"\"\"\n        The build directory.\n        \"\"\"\nreturn self.__directory\n@property\ndef target_name(self) -> str:\n\"\"\"\n        The plugin name of the build target.\n        \"\"\"\nreturn self.__target_name\ndef clean(self, versions: list[str]) -> None:\n\"\"\"\n        This occurs before the build process if the `-c`/`--clean` flag was passed to\n        the [`build`](../../cli/reference.md#hatch-build) command, or when invoking\n        the [`clean`](../../cli/reference.md#hatch-clean) command.\n        \"\"\"\ndef initialize(self, version: str, build_data: dict[str, Any]) -> None:\n\"\"\"\n        This occurs immediately before each build.\n        Any modifications to the build data will be seen by the build target.\n        \"\"\"\ndef finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:\n\"\"\"\n        This occurs immediately after each build and will not run if the `--hooks-only` flag\n        was passed to the [`build`](../../cli/reference.md#hatch-build) command.\n        The build data will reflect any modifications done by the target during the build.\n        \"\"\"\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.app","title":"app: Application property","text":"

An instance of Application.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.root","title":"root: str property","text":"

The root of the project tree.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.config","title":"config: dict[str, Any] property","text":"

The cumulative hook configuration.

pyproject.toml hatch.toml
[tool.hatch.build.hooks.<PLUGIN_NAME>]\n[tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]\n
[build.hooks.<PLUGIN_NAME>]\n[build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.build_config","title":"build_config: BuilderConfigBound property","text":"

An instance of BuilderConfig.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.target_name","title":"target_name: str property","text":"

The plugin name of the build target.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.directory","title":"directory: str property","text":"

The build directory.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.clean","title":"clean(versions: list[str]) -> None","text":"

This occurs before the build process if the -c/--clean flag was passed to the build command, or when invoking the clean command.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def clean(self, versions: list[str]) -> None:\n\"\"\"\n    This occurs before the build process if the `-c`/`--clean` flag was passed to\n    the [`build`](../../cli/reference.md#hatch-build) command, or when invoking\n    the [`clean`](../../cli/reference.md#hatch-clean) command.\n    \"\"\"\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.initialize","title":"initialize(version: str, build_data: dict[str, Any]) -> None","text":"

This occurs immediately before each build.

Any modifications to the build data will be seen by the build target.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def initialize(self, version: str, build_data: dict[str, Any]) -> None:\n\"\"\"\n    This occurs immediately before each build.\n    Any modifications to the build data will be seen by the build target.\n    \"\"\"\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.finalize","title":"finalize(version: str, build_data: dict[str, Any], artifact_path: str) -> None","text":"

This occurs immediately after each build and will not run if the --hooks-only flag was passed to the build command.

The build data will reflect any modifications done by the target during the build.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:\n\"\"\"\n    This occurs immediately after each build and will not run if the `--hooks-only` flag\n    was passed to the [`build`](../../cli/reference.md#hatch-build) command.\n    The build data will reflect any modifications done by the target during the build.\n    \"\"\"\n
"},{"location":"plugins/build-hook/version/","title":"Version build hook","text":"

This writes the project's version to a file.

"},{"location":"plugins/build-hook/version/#configuration","title":"Configuration","text":"

The build hook plugin name is version.

pyproject.toml hatch.toml
[tool.hatch.build.hooks.version]\n[tool.hatch.build.targets.<TARGET_NAME>.hooks.version]\n
[build.hooks.version]\n[build.targets.<TARGET_NAME>.hooks.version]\n
"},{"location":"plugins/build-hook/version/#options","title":"Options","text":"Option Description path (required) A relative path to the desired file template A string representing the entire contents of path that will be formatted with a version variable pattern Rather than updating the entire file, a regular expression may be used that has a named group called version that represents the version. If set to true, a pattern will be used that looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v."},{"location":"plugins/builder/app/","title":"Application builder","text":"

This uses PyApp to build an application that is able to bootstrap itself at runtime.

Note

This requires an installation of Rust.

"},{"location":"plugins/builder/app/#configuration","title":"Configuration","text":"

The builder plugin name is app.

pyproject.toml hatch.toml
[tool.hatch.build.targets.app]\n
[build.targets.app]\n
"},{"location":"plugins/builder/app/#options","title":"Options","text":"Option Default Description scripts all defined An array of defined script names to limit what gets built python-version latest compatible Python minor version The Python version ID to use pyapp-version The version of PyApp to use"},{"location":"plugins/builder/app/#build-behavior","title":"Build behavior","text":"

If any scripts are defined then each one will be built (limited by the scripts option). Otherwise, a single executable will be built based on the project name assuming there is an equivalently named module with a __main__.py file.

Every executable will be built inside an app directory in the output directory.

If the CARGO environment variable is set then that path will be used as the executable for performing builds.

If the CARGO_BUILD_TARGET environment variable is set then its value will be appended to the file name stems.

If the PYAPP_REPO environment variable is set then a local build will be performed inside that directory rather than installing from crates.io. Note that this is required if the CARGO environment variable refers to cross.

"},{"location":"plugins/builder/custom/","title":"Custom builder","text":"

This is a custom class in a given Python file that inherits from the BuilderInterface.

"},{"location":"plugins/builder/custom/#configuration","title":"Configuration","text":"

The builder plugin name is custom.

pyproject.toml hatch.toml
[tool.hatch.build.targets.custom]\n
[build.targets.custom]\n
"},{"location":"plugins/builder/custom/#options","title":"Options","text":"Option Default Description path hatch_build.py The path of the Python file"},{"location":"plugins/builder/custom/#example","title":"Example","text":"hatch_build.py
from hatchling.builders.plugin.interface import BuilderInterface\n\n\nclass CustomBuilder(BuilderInterface):\n    ...\n

If multiple subclasses are found, you must define a function named get_builder that returns the desired builder.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

"},{"location":"plugins/builder/reference/","title":"Builder plugins","text":"

See the documentation for build configuration.

"},{"location":"plugins/builder/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface","title":"BuilderInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.builders.plugin.interface import BuilderInterface\n\n\nclass SpecialBuilder(BuilderInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialBuilder\n\n\n@hookimpl\ndef hatch_register_builder():\n    return SpecialBuilder\n
Source code in backend/src/hatchling/builders/plugin/interface.py
class BuilderInterface(ABC, Generic[BuilderConfigBound, PluginManagerBound]):\n\"\"\"\n    Example usage:\n    === \":octicons-file-code-16: plugin.py\"\n        ```python\n        from hatchling.builders.plugin.interface import BuilderInterface\n        class SpecialBuilder(BuilderInterface):\n            PLUGIN_NAME = 'special'\n            ...\n        ```\n    === \":octicons-file-code-16: hooks.py\"\n        ```python\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialBuilder\n        @hookimpl\n        def hatch_register_builder():\n            return SpecialBuilder\n        ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(\nself,\nroot: str,\nplugin_manager: PluginManagerBound | None = None,\nconfig: dict[str, Any] | None = None,\nmetadata: ProjectMetadata | None = None,\napp: Application | None = None,\n) -> None:\nself.__root = root\nself.__plugin_manager = cast(PluginManagerBound, plugin_manager)\nself.__raw_config = config\nself.__metadata = metadata\nself.__app = app\nself.__config = cast(BuilderConfigBound, None)\nself.__project_config: dict[str, Any] | None = None\nself.__hatch_config: dict[str, Any] | None = None\nself.__build_config: dict[str, Any] | None = None\nself.__build_targets: list[str] | None = None\nself.__target_config: dict[str, Any] | None = None\n# Metadata\nself.__project_id: str | None = None\ndef build(\nself,\ndirectory: str | None = None,\nversions: list[str] | None = None,\nhooks_only: bool | None = None,\nclean: bool | None = None,\nclean_hooks_after: bool | None = None,\nclean_only: bool | None = False,  # noqa: FBT002\n) -> Generator[str, None, None]:\n# Fail early for invalid project metadata\nself.metadata.validate_fields()\nif directory is None:\ndirectory = (\nself.config.normalize_build_directory(os.environ[BuildEnvVars.LOCATION])\nif BuildEnvVars.LOCATION in os.environ\nelse self.config.directory\n)\nif not os.path.isdir(directory):\nos.makedirs(directory)\nversion_api = self.get_version_api()\nversions = versions or self.config.versions\nif versions:\nunknown_versions = set(versions) - set(version_api)\nif unknown_versions:\nmessage = (\nf'Unknown versions for target `{self.PLUGIN_NAME}`: {\", \".join(map(str, sorted(unknown_versions)))}'\n)\nraise ValueError(message)\nif hooks_only is None:\nhooks_only = env_var_enabled(BuildEnvVars.HOOKS_ONLY)\nconfigured_build_hooks = self.get_build_hooks(directory)\nbuild_hooks = list(configured_build_hooks.values())\nif clean_only:\nclean = True\nelif clean is None:\nclean = env_var_enabled(BuildEnvVars.CLEAN)\nif clean:\nif not hooks_only:\nself.clean(directory, versions)\nfor build_hook in build_hooks:\nbuild_hook.clean(versions)\nif clean_only:\nreturn\nif clean_hooks_after is None:\nclean_hooks_after = env_var_enabled(BuildEnvVars.CLEAN_HOOKS_AFTER)\nfor version in versions:\nself.app.display_debug(f'Building `{self.PLUGIN_NAME}` version `{version}`')\nbuild_data = self.get_default_build_data()\nself.set_build_data_defaults(build_data)\n# Allow inspection of configured build hooks and the order in which they run\nbuild_data['build_hooks'] = tuple(configured_build_hooks)\n# Execute all `initialize` build hooks\nfor build_hook in build_hooks:\nbuild_hook.initialize(version, build_data)\nif hooks_only:\nself.app.display_debug(f'Only ran build hooks for `{self.PLUGIN_NAME}` version `{version}`')\ncontinue\n# Build the artifact\nwith self.config.set_build_data(build_data):\nartifact = version_api[version](directory, **build_data)\n# Execute all `finalize` build hooks\nfor build_hook in build_hooks:\nbuild_hook.finalize(version, build_data, artifact)\nif clean_hooks_after:\nfor build_hook in build_hooks:\nbuild_hook.clean([version])\nyield artifact\ndef recurse_included_files(self) -> Iterable[IncludedFile]:\n\"\"\"\n        Returns a consistently generated series of file objects for every file that should be distributed. Each file\n        object has three `str` attributes:\n        - `path` - the absolute path\n        - `relative_path` - the path relative to the project root; will be an empty string for external files\n        - `distribution_path` - the path to be distributed as\n        \"\"\"\nyield from self.recurse_selected_project_files()\nyield from self.recurse_forced_files(self.config.get_force_include())\ndef recurse_selected_project_files(self) -> Iterable[IncludedFile]:\nif self.config.only_include:\nyield from self.recurse_explicit_files(self.config.only_include)\nelse:\nyield from self.recurse_project_files()\ndef recurse_project_files(self) -> Iterable[IncludedFile]:\nfor root, dirs, files in safe_walk(self.root):\nrelative_path = get_relative_path(root, self.root)\ndirs[:] = sorted(d for d in dirs if not self.config.directory_is_excluded(d, relative_path))\nfiles.sort()\nis_package = '__init__.py' in files\nfor f in files:\nrelative_file_path = os.path.join(relative_path, f)\nif self.config.include_path(relative_file_path, is_package=is_package):\nyield IncludedFile(\nos.path.join(root, f), relative_file_path, self.config.get_distribution_path(relative_file_path)\n)\ndef recurse_forced_files(self, inclusion_map: dict[str, str]) -> Iterable[IncludedFile]:\nfor source, target_path in inclusion_map.items():\nexternal = not source.startswith(self.root)\nif os.path.isfile(source):\nyield IncludedFile(\nsource,\n'' if external else os.path.relpath(source, self.root),\nself.config.get_distribution_path(target_path),\n)\nelif os.path.isdir(source):\nfor root, dirs, files in safe_walk(source):\nrelative_directory = get_relative_path(root, source)\ndirs[:] = sorted(d for d in dirs if d not in EXCLUDED_DIRECTORIES)\nfiles.sort()\nfor f in files:\nrelative_file_path = os.path.join(target_path, relative_directory, f)\nif not self.config.path_is_reserved(relative_file_path):\nyield IncludedFile(\nos.path.join(root, f),\n'' if external else relative_file_path,\nself.config.get_distribution_path(relative_file_path),\n)\ndef recurse_explicit_files(self, inclusion_map: dict[str, str]) -> Iterable[IncludedFile]:\nfor source, target_path in inclusion_map.items():\nexternal = not source.startswith(self.root)\nif os.path.isfile(source):\nyield IncludedFile(\nsource,\n'' if external else os.path.relpath(source, self.root),\nself.config.get_distribution_path(target_path),\n)\nelif os.path.isdir(source):\nfor root, dirs, files in safe_walk(source):\nrelative_directory = get_relative_path(root, source)\ndirs[:] = sorted(d for d in dirs if d not in EXCLUDED_DIRECTORIES)\nfiles.sort()\nis_package = '__init__.py' in files\nfor f in files:\nrelative_file_path = os.path.join(target_path, relative_directory, f)\nif self.config.include_path(relative_file_path, explicit=True, is_package=is_package):\nyield IncludedFile(\nos.path.join(root, f),\n'' if external else relative_file_path,\nself.config.get_distribution_path(relative_file_path),\n)\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree.\n        \"\"\"\nreturn self.__root\n@property\ndef plugin_manager(self) -> PluginManagerBound:\nif self.__plugin_manager is None:\nfrom hatchling.plugin.manager import PluginManager\nself.__plugin_manager = PluginManager()\nreturn self.__plugin_manager\n@property\ndef metadata(self) -> ProjectMetadata:\nif self.__metadata is None:\nfrom hatchling.metadata.core import ProjectMetadata\nself.__metadata = ProjectMetadata(self.root, self.plugin_manager, self.__raw_config)\nreturn self.__metadata\n@property\ndef app(self) -> Application:\n\"\"\"\n        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).\n        \"\"\"\nif self.__app is None:\nfrom hatchling.bridge.app import Application\nself.__app = cast(Application, Application().get_safe_application())\nreturn self.__app\n@property\ndef raw_config(self) -> dict[str, Any]:\nif self.__raw_config is None:\nself.__raw_config = self.metadata.config\nreturn self.__raw_config\n@property\ndef project_config(self) -> dict[str, Any]:\nif self.__project_config is None:\nself.__project_config = self.metadata.core.config\nreturn self.__project_config\n@property\ndef hatch_config(self) -> dict[str, Any]:\nif self.__hatch_config is None:\nself.__hatch_config = self.metadata.hatch.config\nreturn self.__hatch_config\n@property\ndef config(self) -> BuilderConfigBound:\n\"\"\"\n        An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).\n        \"\"\"\nif self.__config is None:\nself.__config = self.get_config_class()(\nself, self.root, self.PLUGIN_NAME, self.build_config, self.target_config\n)\nreturn self.__config\n@property\ndef build_config(self) -> dict[str, Any]:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.build]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [build]\n            ```\n        \"\"\"\nif self.__build_config is None:\nself.__build_config = self.metadata.hatch.build_config\nreturn self.__build_config\n@property\ndef target_config(self) -> dict[str, Any]:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.build.targets.<PLUGIN_NAME>]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [build.targets.<PLUGIN_NAME>]\n            ```\n        \"\"\"\nif self.__target_config is None:\ntarget_config: dict[str, Any] = self.metadata.hatch.build_targets.get(self.PLUGIN_NAME, {})\nif not isinstance(target_config, dict):\nmessage = f'Field `tool.hatch.build.targets.{self.PLUGIN_NAME}` must be a table'\nraise TypeError(message)\nself.__target_config = target_config\nreturn self.__target_config\n@property\ndef project_id(self) -> str:\nif self.__project_id is None:\nself.__project_id = f'{self.normalize_file_name_component(self.metadata.core.name)}-{self.metadata.version}'\nreturn self.__project_id\ndef get_build_hooks(self, directory: str) -> dict[str, BuildHookInterface]:\nconfigured_build_hooks = {}\nfor hook_name, config in self.config.hook_config.items():\nbuild_hook = self.plugin_manager.build_hook.get(hook_name)\nif build_hook is None:\nfrom hatchling.plugin.exceptions import UnknownPluginError\nmessage = f'Unknown build hook: {hook_name}'\nraise UnknownPluginError(message)\nconfigured_build_hooks[hook_name] = build_hook(\nself.root, config, self.config, self.metadata, directory, self.PLUGIN_NAME, self.app\n)\nreturn configured_build_hooks\n@abstractmethod\ndef get_version_api(self) -> dict[str, Callable]:\n\"\"\"\n        A mapping of `str` versions to a callable that is used for building.\n        Each callable must have the following signature:\n        ```python\n        def ...(build_dir: str, build_data: dict) -> str:\n        ```\n        The return value must be the absolute path to the built artifact.\n        \"\"\"\ndef get_default_versions(self) -> list[str]:\n\"\"\"\n        A list of versions to build when users do not specify any, defaulting to all versions.\n        \"\"\"\nreturn list(self.get_version_api())\ndef get_default_build_data(self) -> dict[str, Any]:\n\"\"\"\n        A mapping that can be modified by [build hooks](../build-hook/reference.md) to influence the behavior of builds.\n        \"\"\"\nreturn {}\ndef set_build_data_defaults(self, build_data: dict[str, Any]) -> None:\nbuild_data.setdefault('artifacts', [])\nbuild_data.setdefault('force_include', {})\ndef clean(self, directory: str, versions: list[str]) -> None:\n\"\"\"\n        Called before builds if the `-c`/`--clean` flag was passed to the\n        [`build`](../../cli/reference.md#hatch-build) command.\n        \"\"\"\n@classmethod\ndef get_config_class(cls) -> type[BuilderConfig]:\n\"\"\"\n        Must return a subclass of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).\n        \"\"\"\nreturn BuilderConfig\n@staticmethod\ndef normalize_file_name_component(file_name: str) -> str:\n\"\"\"\n        https://peps.python.org/pep-0427/#escaping-and-unicode\n        \"\"\"\nreturn re.sub(r'[^\\w\\d.]+', '_', file_name, re.UNICODE)\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.app","title":"app: Application property","text":"

An instance of Application.

"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.root","title":"root: str property","text":"

The root of the project tree.

"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.build_config","title":"build_config: dict[str, Any] property","text":"pyproject.toml hatch.toml
[tool.hatch.build]\n
[build]\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.target_config","title":"target_config: dict[str, Any] property","text":"pyproject.toml hatch.toml
[tool.hatch.build.targets.<PLUGIN_NAME>]\n
[build.targets.<PLUGIN_NAME>]\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.config","title":"config: BuilderConfigBound property","text":"

An instance of BuilderConfig.

"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.get_config_class","title":"get_config_class() -> type[BuilderConfig] classmethod","text":"

Must return a subclass of BuilderConfig.

Source code in backend/src/hatchling/builders/plugin/interface.py
@classmethod\ndef get_config_class(cls) -> type[BuilderConfig]:\n\"\"\"\n    Must return a subclass of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).\n    \"\"\"\nreturn BuilderConfig\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.get_version_api","title":"get_version_api() -> dict[str, Callable] abstractmethod","text":"

A mapping of str versions to a callable that is used for building. Each callable must have the following signature:

def ...(build_dir: str, build_data: dict) -> str:\n

The return value must be the absolute path to the built artifact.

Source code in backend/src/hatchling/builders/plugin/interface.py
@abstractmethod\ndef get_version_api(self) -> dict[str, Callable]:\n\"\"\"\n    A mapping of `str` versions to a callable that is used for building.\n    Each callable must have the following signature:\n    ```python\n    def ...(build_dir: str, build_data: dict) -> str:\n    ```\n    The return value must be the absolute path to the built artifact.\n    \"\"\"\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.get_default_versions","title":"get_default_versions() -> list[str]","text":"

A list of versions to build when users do not specify any, defaulting to all versions.

Source code in backend/src/hatchling/builders/plugin/interface.py
def get_default_versions(self) -> list[str]:\n\"\"\"\n    A list of versions to build when users do not specify any, defaulting to all versions.\n    \"\"\"\nreturn list(self.get_version_api())\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.clean","title":"clean(directory: str, versions: list[str]) -> None","text":"

Called before builds if the -c/--clean flag was passed to the build command.

Source code in backend/src/hatchling/builders/plugin/interface.py
def clean(self, directory: str, versions: list[str]) -> None:\n\"\"\"\n    Called before builds if the `-c`/`--clean` flag was passed to the\n    [`build`](../../cli/reference.md#hatch-build) command.\n    \"\"\"\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.recurse_included_files","title":"recurse_included_files() -> Iterable[IncludedFile]","text":"

Returns a consistently generated series of file objects for every file that should be distributed. Each file object has three str attributes:

Source code in backend/src/hatchling/builders/plugin/interface.py
def recurse_included_files(self) -> Iterable[IncludedFile]:\n\"\"\"\n    Returns a consistently generated series of file objects for every file that should be distributed. Each file\n    object has three `str` attributes:\n    - `path` - the absolute path\n    - `relative_path` - the path relative to the project root; will be an empty string for external files\n    - `distribution_path` - the path to be distributed as\n    \"\"\"\nyield from self.recurse_selected_project_files()\nyield from self.recurse_forced_files(self.config.get_force_include())\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.get_default_build_data","title":"get_default_build_data() -> dict[str, Any]","text":"

A mapping that can be modified by build hooks to influence the behavior of builds.

Source code in backend/src/hatchling/builders/plugin/interface.py
def get_default_build_data(self) -> dict[str, Any]:\n\"\"\"\n    A mapping that can be modified by [build hooks](../build-hook/reference.md) to influence the behavior of builds.\n    \"\"\"\nreturn {}\n
"},{"location":"plugins/builder/sdist/","title":"Source distribution builder","text":"

A source distribution, or sdist, is an archive of Python \"source code\". Although largely unspecified, by convention it should include everything that is required to build a wheel without making network requests.

"},{"location":"plugins/builder/sdist/#configuration","title":"Configuration","text":"

The builder plugin name is sdist.

pyproject.toml hatch.toml
[tool.hatch.build.targets.sdist]\n
[build.targets.sdist]\n
"},{"location":"plugins/builder/sdist/#options","title":"Options","text":"Option Default Description core-metadata-version \"2.1\" The version of core metadata to use strict-naming true Whether or not file names should contain the normalized version of the project name support-legacy false Whether or not to include a setup.py file to support legacy installation mechanisms"},{"location":"plugins/builder/sdist/#versions","title":"Versions","text":"Version Description standard (default) The latest conventional format"},{"location":"plugins/builder/sdist/#default-file-selection","title":"Default file selection","text":"

When the user has not set any file selection options, all files that are not ignored by your VCS will be included.

Note

The following files are always included and cannot be excluded:

"},{"location":"plugins/builder/sdist/#reproducibility","title":"Reproducibility","text":"

Reproducible builds are supported.

"},{"location":"plugins/builder/sdist/#build-data","title":"Build data","text":"

This is data that can be modified by build hooks.

Data Default Description dependencies Extra project dependencies"},{"location":"plugins/builder/wheel/","title":"Wheel builder","text":"

A wheel is a binary distribution of a Python package that can be installed directly into an environment.

"},{"location":"plugins/builder/wheel/#configuration","title":"Configuration","text":"

The builder plugin name is wheel.

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel]\n
[build.targets.wheel]\n
"},{"location":"plugins/builder/wheel/#options","title":"Options","text":"Option Default Description core-metadata-version \"2.1\" The version of core metadata to use shared-data A mapping similar to the forced inclusion option corresponding to data that will be installed globally in a given Python environment, usually under sys.prefix extra-metadata A mapping similar to the forced inclusion option corresponding to extra metadata that will be shipped in a directory named extra_metadata strict-naming true Whether or not file names should contain the normalized version of the project name macos-max-compat true Whether or not on macOS, when build hooks have set the infer_tag build data, the wheel name should signal broad support rather than specific versions for newer SDK versions.Note: The default will become false, and this option eventually removed, sometime after consumers like pip start supporting these newer SDK versions."},{"location":"plugins/builder/wheel/#versions","title":"Versions","text":"Version Description standard (default) The latest standardized format editable A wheel that only ships .pth files or import hooks for real-time development"},{"location":"plugins/builder/wheel/#default-file-selection","title":"Default file selection","text":"

When the user has not set any file selection options, the project name will be used to determine the package to ship in the following heuristic order:

  1. <NAME>/__init__.py
  2. src/<NAME>/__init__.py
  3. <NAME>.py
  4. <NAMESPACE>/<NAME>/__init__.py
  5. Otherwise, every Python package and file that does not start with the word test will be included
"},{"location":"plugins/builder/wheel/#reproducibility","title":"Reproducibility","text":"

Reproducible builds are supported.

"},{"location":"plugins/builder/wheel/#build-data","title":"Build data","text":"

This is data that can be modified by build hooks.

Data Default Description tag The full tag part of the filename (e.g. py3-none-any), defaulting to a cross-platform wheel with the supported major versions of Python based on project metadata infer_tag False When tag is not set, this may be enabled to use the one most specific to the platform, Python interpreter, and ABI pure_python True Whether or not to write metadata indicating that the package does not contain any platform-specific files dependencies Extra project dependencies extra_metadata Additional extra-metadata entries, which take precedence in case of conflicts force_include_editable Similar to the force_include option but specifically for the editable version and takes precedence"},{"location":"plugins/environment/reference/","title":"Environment plugins","text":"

See the documentation for environment configuration.

"},{"location":"plugins/environment/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/environment/reference/#installation","title":"Installation","text":"

Any required environment types that are not built-in must be manually installed alongside Hatch or listed in the tool.hatch.env.requires array for automatic management:

pyproject.toml hatch.toml
[tool.hatch.env]\nrequires = [\n\"...\",\n]\n
[env]\nrequires = [\n\"...\",\n]\n
"},{"location":"plugins/environment/reference/#life-cycle","title":"Life cycle","text":"

Whenever an environment is used, the following logic is performed:

Source code in src/hatch/cli/application.py
def prepare_environment(self, environment):\nif not environment.exists():\nwith self.status(f'Creating environment: {environment.name}'):\nenvironment.create()\nif not environment.skip_install:\nif environment.pre_install_commands:\nwith self.status('Running pre-installation commands'):\nself.run_shell_commands(environment, environment.pre_install_commands, source='pre-install')\nif environment.dev_mode:\nwith self.status('Installing project in development mode'):\nenvironment.install_project_dev_mode()\nelse:\nwith self.status('Installing project'):\nenvironment.install_project()\nif environment.post_install_commands:\nwith self.status('Running post-installation commands'):\nself.run_shell_commands(environment, environment.post_install_commands, source='post-install')\nwith self.status('Checking dependencies'):\ndependencies_in_sync = environment.dependencies_in_sync()\nif not dependencies_in_sync:\nwith self.status('Syncing dependencies'):\nenvironment.sync_dependencies()\n
"},{"location":"plugins/environment/reference/#build-environments","title":"Build environments","text":"

All environment types should offer support for a special sub-environment in which projects can be built. This environment is used in the following scenarios:

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface","title":"EnvironmentInterface","text":"

Example usage:

plugin.py hooks.py
from hatch.env.plugin.interface import EnvironmentInterface\n\n\nclass SpecialEnvironment(EnvironmentInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialEnvironment\n\n\n@hookimpl\ndef hatch_register_environment():\n    return SpecialEnvironment\n
Source code in src/hatch/env/plugin/interface.py
class EnvironmentInterface(ABC):\n\"\"\"\n    Example usage:\n    === \":octicons-file-code-16: plugin.py\"\n        ```python\n        from hatch.env.plugin.interface import EnvironmentInterface\n        class SpecialEnvironment(EnvironmentInterface):\n            PLUGIN_NAME = 'special'\n            ...\n        ```\n    === \":octicons-file-code-16: hooks.py\"\n        ```python\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialEnvironment\n        @hookimpl\n        def hatch_register_environment():\n            return SpecialEnvironment\n        ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(\nself,\nroot,\nmetadata,\nname,\nconfig,\nmatrix_variables,\ndata_directory,\nisolated_data_directory,\nplatform,\nverbosity,\napp=None,\n):\nself.__root = root\nself.__metadata = metadata\nself.__name = name\nself.__config = config\nself.__matrix_variables = matrix_variables\nself.__data_directory = data_directory\nself.__isolated_data_directory = isolated_data_directory\nself.__platform = platform\nself.__verbosity = verbosity\nself.__app = app\nself.__context = None\nself._system_python = None\nself._env_vars = None\nself._env_include = None\nself._env_exclude = None\nself._environment_dependencies_complex = None\nself._environment_dependencies = None\nself._dependencies_complex = None\nself._dependencies = None\nself._platforms = None\nself._skip_install = None\nself._dev_mode = None\nself._features = None\nself._description = None\nself._scripts = None\nself._pre_install_commands = None\nself._post_install_commands = None\n@property\ndef matrix_variables(self):\nreturn self.__matrix_variables\n@property\ndef app(self):\n\"\"\"\n        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).\n        \"\"\"\nif self.__app is None:\nfrom hatchling.bridge.app import Application\nself.__app = Application().get_safe_application()\nreturn self.__app\n@property\ndef context(self):\nif self.__context is None:\nself.__context = self.get_context()\nreturn self.__context\n@property\ndef verbosity(self):\nreturn self.__verbosity\n@property\ndef root(self):\n\"\"\"\n        The root of the project tree as a path-like object.\n        \"\"\"\nreturn self.__root\n@property\ndef metadata(self):\nreturn self.__metadata\n@property\ndef name(self) -> str:\n\"\"\"\n        The name of the environment.\n        \"\"\"\nreturn self.__name\n@property\ndef platform(self):\n\"\"\"\n        An instance of [Platform](../utilities.md#hatch.utils.platform.Platform).\n        \"\"\"\nreturn self.__platform\n@property\ndef data_directory(self):\n\"\"\"\n        The [directory](../../config/hatch.md#environments) this plugin should use for storage as a path-like object.\n        If the user has not configured one then this will be the same as the\n        [isolated data directory](reference.md#hatch.env.plugin.interface.EnvironmentInterface.isolated_data_directory).\n        \"\"\"\nreturn self.__data_directory\n@property\ndef isolated_data_directory(self):\n\"\"\"\n        The default [directory](../../config/hatch.md#environments) reserved exclusively for this plugin as a path-like\n        object.\n        \"\"\"\nreturn self.__isolated_data_directory\n@property\ndef config(self) -> dict:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.envs.<ENV_NAME>]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [envs.<ENV_NAME>]\n            ```\n        \"\"\"\nreturn self.__config\n@property\ndef system_python(self):\nif self._system_python is None:\nsystem_python = os.environ.get(AppEnvVars.PYTHON)\nif system_python == 'self':\nsystem_python = sys.executable\nsystem_python = (\nsystem_python\nor self.platform.modules.shutil.which('python')\nor self.platform.modules.shutil.which('python3')\nor sys.executable\n)\nif not isabs(system_python):\nsystem_python = self.platform.modules.shutil.which(system_python)\nself._system_python = system_python\nreturn self._system_python\n@property\ndef env_vars(self) -> dict:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.envs.<ENV_NAME>.env-vars]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [envs.<ENV_NAME>.env-vars]\n            ```\n        \"\"\"\nif self._env_vars is None:\nenv_vars = self.config.get('env-vars', {})\nif not isinstance(env_vars, dict):\nmessage = f'Field `tool.hatch.envs.{self.name}.env-vars` must be a mapping'\nraise TypeError(message)\nfor key, value in env_vars.items():\nif not isinstance(value, str):\nmessage = (\nf'Environment variable `{key}` of field `tool.hatch.envs.{self.name}.env-vars` must be a string'\n)\nraise TypeError(message)\nnew_env_vars = {}\nwith self.metadata.context.apply_context(self.context):\nfor key, value in env_vars.items():\nnew_env_vars[key] = self.metadata.context.format(value)\nnew_env_vars[AppEnvVars.ENV_ACTIVE] = self.name\nself._env_vars = new_env_vars\nreturn self._env_vars\n@property\ndef env_include(self) -> list[str]:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.envs.<ENV_NAME>]\n            env-include = [...]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [envs.<ENV_NAME>]\n            env-include = [...]\n            ```\n        \"\"\"\nif self._env_include is None:\nenv_include = self.config.get('env-include', [])\nif not isinstance(env_include, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.env-include` must be an array'\nraise TypeError(message)\nfor i, pattern in enumerate(env_include, 1):\nif not isinstance(pattern, str):\nmessage = f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-include` must be a string'\nraise TypeError(message)\nif env_include:\nself._env_include = ['HATCH_BUILD_*', *env_include]\nelse:\nself._env_include = env_include\nreturn self._env_include\n@property\ndef env_exclude(self) -> list[str]:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.envs.<ENV_NAME>]\n            env-exclude = [...]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [envs.<ENV_NAME>]\n            env-exclude = [...]\n            ```\n        \"\"\"\nif self._env_exclude is None:\nenv_exclude = self.config.get('env-exclude', [])\nif not isinstance(env_exclude, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.env-exclude` must be an array'\nraise TypeError(message)\nfor i, pattern in enumerate(env_exclude, 1):\nif not isinstance(pattern, str):\nmessage = f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-exclude` must be a string'\nraise TypeError(message)\nself._env_exclude = env_exclude\nreturn self._env_exclude\n@property\ndef environment_dependencies_complex(self):\nif self._environment_dependencies_complex is None:\nfrom packaging.requirements import InvalidRequirement, Requirement\ndependencies_complex = []\nwith self.apply_context():\nfor option in ('dependencies', 'extra-dependencies'):\ndependencies = self.config.get(option, [])\nif not isinstance(dependencies, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.{option}` must be an array'\nraise TypeError(message)\nfor i, entry in enumerate(dependencies, 1):\nif not isinstance(entry, str):\nmessage = (\nf'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` must be a string'\n)\nraise TypeError(message)\ntry:\ndependencies_complex.append(Requirement(self.metadata.context.format(entry)))\nexcept InvalidRequirement as e:\nmessage = f'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` is invalid: {e}'\nraise ValueError(message) from None\nself._environment_dependencies_complex = dependencies_complex\nreturn self._environment_dependencies_complex\n@property\ndef environment_dependencies(self) -> list[str]:\n\"\"\"\n        The list of all [environment dependencies](../../config/environment/overview.md#dependencies).\n        \"\"\"\nif self._environment_dependencies is None:\nself._environment_dependencies = [str(dependency) for dependency in self.environment_dependencies_complex]\nreturn self._environment_dependencies\n@property\ndef dependencies_complex(self):\nif self._dependencies_complex is None:\nall_dependencies_complex = list(self.environment_dependencies_complex)\n# Ensure these are checked last to speed up initial environment creation since\n# they will already be installed along with the project\nif not self.skip_install and self.dev_mode:\nfrom hatch.utils.dep import get_project_dependencies_complex\ndependencies_complex, optional_dependencies_complex = get_project_dependencies_complex(self)\nall_dependencies_complex.extend(dependencies_complex.values())\nfor feature in self.features:\nif feature not in optional_dependencies_complex:\nmessage = (\nf'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not '\nf'defined in the dynamic field `project.optional-dependencies`'\n)\nraise ValueError(message)\nall_dependencies_complex.extend(optional_dependencies_complex[feature].values())\nself._dependencies_complex = all_dependencies_complex\nreturn self._dependencies_complex\n@property\ndef dependencies(self) -> list[str]:\n\"\"\"\n        The list of all [project dependencies](../../config/metadata.md#dependencies) (if\n        [installed](../../config/environment/overview.md#skip-install) and in\n        [dev mode](../../config/environment/overview.md#dev-mode)) and\n        [environment dependencies](../../config/environment/overview.md#dependencies).\n        \"\"\"\nif self._dependencies is None:\nself._dependencies = [str(dependency) for dependency in self.dependencies_complex]\nreturn self._dependencies\n@property\ndef platforms(self) -> list[str]:\n\"\"\"\n        All names are stored as their lower-cased version.\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.envs.<ENV_NAME>]\n            platforms = [...]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [envs.<ENV_NAME>]\n            platforms = [...]\n            ```\n        \"\"\"\nif self._platforms is None:\nplatforms = self.config.get('platforms', [])\nif not isinstance(platforms, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.platforms` must be an array'\nraise TypeError(message)\nfor i, command in enumerate(platforms, 1):\nif not isinstance(command, str):\nmessage = f'Platform #{i} of field `tool.hatch.envs.{self.name}.platforms` must be a string'\nraise TypeError(message)\nself._platforms = [platform.lower() for platform in platforms]\nreturn self._platforms\n@property\ndef skip_install(self) -> bool:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.envs.<ENV_NAME>]\n            skip-install = ...\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [envs.<ENV_NAME>]\n            skip-install = ...\n            ```\n        \"\"\"\nif self._skip_install is None:\nskip_install = self.config.get('skip-install', not self.metadata.has_project_file())\nif not isinstance(skip_install, bool):\nmessage = f'Field `tool.hatch.envs.{self.name}.skip-install` must be a boolean'\nraise TypeError(message)\nself._skip_install = skip_install\nreturn self._skip_install\n@property\ndef dev_mode(self) -> bool:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.envs.<ENV_NAME>]\n            dev-mode = ...\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [envs.<ENV_NAME>]\n            dev-mode = ...\n            ```\n        \"\"\"\nif self._dev_mode is None:\ndev_mode = self.config.get('dev-mode', True)\nif not isinstance(dev_mode, bool):\nmessage = f'Field `tool.hatch.envs.{self.name}.dev-mode` must be a boolean'\nraise TypeError(message)\nself._dev_mode = dev_mode\nreturn self._dev_mode\n@property\ndef features(self):\nif self._features is None:\nfrom hatchling.metadata.utils import normalize_project_name\nfeatures = self.config.get('features', [])\nif not isinstance(features, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.features` must be an array of strings'\nraise TypeError(message)\nall_features = set()\nfor i, feature in enumerate(features, 1):\nif not isinstance(feature, str):\nmessage = f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` must be a string'\nraise TypeError(message)\nelif not feature:\nmessage = f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` cannot be an empty string'\nraise ValueError(message)\nif not self.metadata.hatch.metadata.allow_ambiguous_features:\nfeature = normalize_project_name(feature)\nif (\nnot self.metadata.hatch.metadata.hook_config\nand feature not in self.metadata.core.optional_dependencies\n):\nmessage = (\nf'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not '\nf'defined in field `project.optional-dependencies`'\n)\nraise ValueError(message)\nall_features.add(feature)\nself._features = sorted(all_features)\nreturn self._features\n@property\ndef description(self) -> str:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.envs.<ENV_NAME>]\n            description = ...\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [envs.<ENV_NAME>]\n            description = ...\n            ```\n        \"\"\"\nif self._description is None:\ndescription = self.config.get('description', '')\nif not isinstance(description, str):\nmessage = f'Field `tool.hatch.envs.{self.name}.description` must be a string'\nraise TypeError(message)\nself._description = description\nreturn self._description\n@property\ndef scripts(self):\nif self._scripts is None:\nscript_config = self.config.get('scripts', {})\nif not isinstance(script_config, dict):\nmessage = f'Field `tool.hatch.envs.{self.name}.scripts` must be a table'\nraise TypeError(message)\nconfig = {}\nfor name, data in script_config.items():\nif ' ' in name:\nmessage = (\nf'Script name `{name}` in field `tool.hatch.envs.{self.name}.scripts` must not contain spaces'\n)\nraise ValueError(message)\ncommands = []\nif isinstance(data, str):\ncommands.append(data)\nelif isinstance(data, list):\nfor i, command in enumerate(data, 1):\nif not isinstance(command, str):\nmessage = (\nf'Command #{i} in field `tool.hatch.envs.{self.name}.scripts.{name}` must be a string'\n)\nraise TypeError(message)\ncommands.append(command)\nelse:\nmessage = (\nf'Field `tool.hatch.envs.{self.name}.scripts.{name}` must be a string or an array of strings'\n)\nraise TypeError(message)\nconfig[name] = commands\nseen = {}\nactive = []\nfor script_name, commands in config.items():\ncommands[:] = expand_script_commands(self.name, script_name, commands, config, seen, active)\nself._scripts = config\nreturn self._scripts\n@property\ndef pre_install_commands(self):\nif self._pre_install_commands is None:\npre_install_commands = self.config.get('pre-install-commands', [])\nif not isinstance(pre_install_commands, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.pre-install-commands` must be an array'\nraise TypeError(message)\nfor i, command in enumerate(pre_install_commands, 1):\nif not isinstance(command, str):\nmessage = (\nf'Command #{i} of field `tool.hatch.envs.{self.name}.pre-install-commands` must be a string'\n)\nraise TypeError(message)\nself._pre_install_commands = list(pre_install_commands)\nreturn self._pre_install_commands\n@property\ndef post_install_commands(self):\nif self._post_install_commands is None:\npost_install_commands = self.config.get('post-install-commands', [])\nif not isinstance(post_install_commands, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.post-install-commands` must be an array'\nraise TypeError(message)\nfor i, command in enumerate(post_install_commands, 1):\nif not isinstance(command, str):\nmessage = (\nf'Command #{i} of field `tool.hatch.envs.{self.name}.post-install-commands` must be a string'\n)\nraise TypeError(message)\nself._post_install_commands = list(post_install_commands)\nreturn self._post_install_commands\ndef activate(self):\n\"\"\"\n        A convenience method called when using the environment as a context manager:\n        ```python\n        with environment:\n            ...\n        ```\n        \"\"\"\ndef deactivate(self):\n\"\"\"\n        A convenience method called after using the environment as a context manager:\n        ```python\n        with environment:\n            ...\n        ```\n        \"\"\"\n@abstractmethod\ndef find(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should return information about how to locate the environment.\n        \"\"\"\n@abstractmethod\ndef create(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should perform the necessary steps to set up the environment.\n        \"\"\"\n@abstractmethod\ndef remove(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should perform the necessary steps to completely remove the environment from the system and will only\n        be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or\n        [`env prune`](../../cli/reference.md#hatch-env-prune) commands.\n        If the\n        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n        has a caching mechanism, this should remove that as well.\n        \"\"\"\n@abstractmethod\ndef exists(self) -> bool:\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should indicate whether or not the environment has already been created.\n        \"\"\"\n@abstractmethod\ndef install_project(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should install the project in the environment.\n        \"\"\"\n@abstractmethod\ndef install_project_dev_mode(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should install the project in the environment such that the environment\n        always reflects the current state of the project.\n        \"\"\"\n@abstractmethod\ndef dependencies_in_sync(self) -> bool:\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should indicate whether or not the environment is compatible with the current\n        [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies).\n        \"\"\"\n@abstractmethod\ndef sync_dependencies(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should install the\n        [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies)\n        in the environment.\n        \"\"\"\n@contextmanager\ndef build_environment(self, dependencies: list[str]):\n\"\"\"\n        This should set up an isolated environment in which to [`build`](../../cli/reference.md#hatch-build) the project\n        given a set of dependencies and must be a context manager:\n        ```python\n        with environment.build_environment([...]):\n            ...\n        ```\n        The build environment should reflect any\n        [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)\n        the user defined either currently or at the time of\n        [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).\n        \"\"\"\nwith self.get_env_vars():\nyield\ndef get_build_process(self, build_environment, **kwargs):\n\"\"\"\n        This will be called when the\n        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n        is active:\n        ```python\n        with environment.build_environment([...]) as build_environment:\n            build_process = environment.get_build_process(build_environment, ...)\n        ```\n        This should return the standard library's\n        [subprocess.Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)\n        with all output captured by `stdout`. The command is constructed by passing all keyword arguments to\n        [construct_build_command](reference.md#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command).\n        For an example, open the default implementation below:\n        \"\"\"\nreturn self.platform.capture_process(self.construct_build_command(**kwargs))\ndef build_environment_exists(self):\n\"\"\"\n        If the\n        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n        has a caching mechanism, this should indicate whether or not it has already been created.\n        \"\"\"\nreturn False\ndef enter_shell(self, name: str, path: str, args: Iterable[str]):\n\"\"\"\n        Spawn a [shell](../../config/hatch.md#shell) within the environment.\n        This should either use\n        [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)\n        directly or provide the same guarantee.\n        \"\"\"\nwith self.command_context():\nself.platform.exit_with_command([path, *args])\ndef run_shell_command(self, command: str, **kwargs):\n\"\"\"\n        This should return the standard library's\n        [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess)\n        and will always be called when the\n        [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)\n        is active, with the expectation of providing the same guarantee.\n        \"\"\"\nkwargs.setdefault('shell', True)\nreturn self.platform.run_command(command, **kwargs)\n@contextmanager\ndef command_context(self):\n\"\"\"\n        A context manager that when active should make executed shell commands reflect any\n        [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)\n        the user defined either currently or at the time of\n        [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).\n        For an example, open the default implementation below:\n        \"\"\"\nwith self.get_env_vars():\nyield\ndef resolve_commands(self, commands: list[str]):\n\"\"\"\n        This expands each command into one or more commands based on any\n        [scripts](../../config/environment/overview.md#scripts) that the user defined.\n        \"\"\"\nfor command in commands:\nyield from self.expand_command(command)\ndef expand_command(self, command):\npossible_script, args, ignore_exit_code = parse_script_command(command)\n# Indicate undefined\nif not args:\nargs = None\nwith self.apply_context():\nif possible_script in self.scripts:\nfor cmd in self.scripts[possible_script]:\nyield self.metadata.context.format(cmd, args=args).strip()\nelse:\nyield self.metadata.context.format(command, args=args).strip()\ndef construct_build_command(\nself,\n*,\ndirectory=None,\ntargets=(),\nhooks_only=False,\nno_hooks=False,\nclean=False,\nclean_hooks_after=False,\nclean_only=False,\n):\n\"\"\"\n        This is the canonical way [`build`](../../cli/reference.md#hatch-build) command options are translated to\n        a subprocess command issued to [builders](../builder/reference.md).\n        \"\"\"\ncommand = ['python', '-u', '-m', 'hatchling', 'build', '--app']\nif directory:\ncommand.extend(('--directory', directory))\nif targets:\nfor target in targets:\ncommand.extend(('--target', target))\nif hooks_only:\ncommand.append('--hooks-only')\nif no_hooks:\ncommand.append('--no-hooks')\nif clean:\ncommand.append('--clean')\nif clean_hooks_after:\ncommand.append('--clean-hooks-after')\nif clean_only:\ncommand.append('--clean-only')\nreturn command\ndef construct_pip_install_command(self, args: list[str]):\n\"\"\"\n        A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/)\n        command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.\n        \"\"\"\ncommand = ['python', '-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-python-version-warning']\n# Default to -1 verbosity\nadd_verbosity_flag(command, self.verbosity, adjustment=-1)\ncommand.extend(args)\nreturn command\ndef join_command_args(self, args: list[str]):\n\"\"\"\n        This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string\n        from the received arguments.\n        \"\"\"\nreturn self.platform.join_command_args(args)\ndef apply_features(self, requirement: str):\n\"\"\"\n        A convenience method that applies any user defined [features](../../config/environment/overview.md#features)\n        to the given requirement.\n        \"\"\"\nif self.features:\nfeatures = ','.join(self.features)\nreturn f'{requirement}[{features}]'\nreturn requirement\ndef check_compatibility(self):\n\"\"\"\n        This raises an exception if the environment is not compatible with the user's setup. The default behavior\n        checks for [platform compatibility](../../config/environment/overview.md#supported-platforms)\n        and any method override should keep this check.\n        \"\"\"\nif self.platforms and self.platform.name not in self.platforms:\nmessage = 'unsupported platform'\nraise OSError(message)\ndef get_env_vars(self) -> EnvVars:\n\"\"\"\n        Returns a mapping of environment variables that should be available to the environment. The object can\n        be used as a context manager to temporarily apply the environment variables to the current process.\n        !!! note\n            The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment.\n        \"\"\"\nreturn EnvVars(self.env_vars, self.env_include, self.env_exclude)\ndef get_env_var_option(self, option: str) -> str:\n\"\"\"\n        Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`.\n        \"\"\"\nreturn os.environ.get(f'{AppEnvVars.ENV_OPTION_PREFIX}{self.PLUGIN_NAME}_{option}'.upper(), '')\ndef get_context(self):\n\"\"\"\n        Returns a subclass of\n        [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter).\n        \"\"\"\nfrom hatch.env.context import EnvironmentContextFormatter\nreturn EnvironmentContextFormatter(self)\n@staticmethod\ndef get_option_types() -> dict:\n\"\"\"\n        Returns a mapping of supported options to their respective types so that they can be used by\n        [overrides](../../config/environment/advanced.md#option-overrides).\n        \"\"\"\nreturn {}\n@contextmanager\ndef apply_context(self):\nwith self.get_env_vars(), self.metadata.context.apply_context(self.context):\nyield\ndef __enter__(self):\nself.activate()\nreturn self\ndef __exit__(self, exc_type, exc_value, traceback):\nself.deactivate()\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.app","title":"app property","text":"

An instance of Application.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.root","title":"root property","text":"

The root of the project tree as a path-like object.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.name","title":"name: str property","text":"

The name of the environment.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.data_directory","title":"data_directory property","text":"

The directory this plugin should use for storage as a path-like object. If the user has not configured one then this will be the same as the isolated data directory.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.isolated_data_directory","title":"isolated_data_directory property","text":"

The default directory reserved exclusively for this plugin as a path-like object.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.config","title":"config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\n
[envs.<ENV_NAME>]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.platform","title":"platform property","text":"

An instance of Platform.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.environment_dependencies","title":"environment_dependencies: list[str] property","text":"

The list of all environment dependencies.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.dependencies","title":"dependencies: list[str] property","text":"

The list of all project dependencies (if installed and in dev mode) and environment dependencies.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.env_vars","title":"env_vars: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>.env-vars]\n
[envs.<ENV_NAME>.env-vars]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.env_include","title":"env_include: list[str] property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nenv-include = [...]\n
[envs.<ENV_NAME>]\nenv-include = [...]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.env_exclude","title":"env_exclude: list[str] property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nenv-exclude = [...]\n
[envs.<ENV_NAME>]\nenv-exclude = [...]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.platforms","title":"platforms: list[str] property","text":"

All names are stored as their lower-cased version.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nplatforms = [...]\n
[envs.<ENV_NAME>]\nplatforms = [...]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.skip_install","title":"skip_install: bool property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nskip-install = ...\n
[envs.<ENV_NAME>]\nskip-install = ...\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.dev_mode","title":"dev_mode: bool property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\ndev-mode = ...\n
[envs.<ENV_NAME>]\ndev-mode = ...\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.description","title":"description: str property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\ndescription = ...\n
[envs.<ENV_NAME>]\ndescription = ...\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.activate","title":"activate()","text":"

A convenience method called when using the environment as a context manager:

with environment:\n    ...\n
Source code in src/hatch/env/plugin/interface.py
def activate(self):\n\"\"\"\n    A convenience method called when using the environment as a context manager:\n    ```python\n    with environment:\n        ...\n    ```\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.deactivate","title":"deactivate()","text":"

A convenience method called after using the environment as a context manager:

with environment:\n    ...\n
Source code in src/hatch/env/plugin/interface.py
def deactivate(self):\n\"\"\"\n    A convenience method called after using the environment as a context manager:\n    ```python\n    with environment:\n        ...\n    ```\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.find","title":"find() abstractmethod","text":"

REQUIRED

This should return information about how to locate the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef find(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should return information about how to locate the environment.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.create","title":"create() abstractmethod","text":"

REQUIRED

This should perform the necessary steps to set up the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef create(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should perform the necessary steps to set up the environment.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.remove","title":"remove() abstractmethod","text":"

REQUIRED

This should perform the necessary steps to completely remove the environment from the system and will only be triggered manually by users with the env remove or env prune commands.

If the build environment has a caching mechanism, this should remove that as well.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef remove(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should perform the necessary steps to completely remove the environment from the system and will only\n    be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or\n    [`env prune`](../../cli/reference.md#hatch-env-prune) commands.\n    If the\n    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n    has a caching mechanism, this should remove that as well.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.exists","title":"exists() -> bool abstractmethod","text":"

REQUIRED

This should indicate whether or not the environment has already been created.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef exists(self) -> bool:\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should indicate whether or not the environment has already been created.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.install_project","title":"install_project() abstractmethod","text":"

REQUIRED

This should install the project in the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef install_project(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should install the project in the environment.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.install_project_dev_mode","title":"install_project_dev_mode() abstractmethod","text":"

REQUIRED

This should install the project in the environment such that the environment always reflects the current state of the project.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef install_project_dev_mode(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should install the project in the environment such that the environment\n    always reflects the current state of the project.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.dependencies_in_sync","title":"dependencies_in_sync() -> bool abstractmethod","text":"

REQUIRED

This should indicate whether or not the environment is compatible with the current dependencies.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef dependencies_in_sync(self) -> bool:\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should indicate whether or not the environment is compatible with the current\n    [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies).\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.sync_dependencies","title":"sync_dependencies() abstractmethod","text":"

REQUIRED

This should install the dependencies in the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef sync_dependencies(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should install the\n    [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies)\n    in the environment.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.build_environment","title":"build_environment(dependencies: list[str])","text":"

This should set up an isolated environment in which to build the project given a set of dependencies and must be a context manager:

with environment.build_environment([...]):\n    ...\n

The build environment should reflect any environment variables the user defined either currently or at the time of creation.

Source code in src/hatch/env/plugin/interface.py
@contextmanager\ndef build_environment(self, dependencies: list[str]):\n\"\"\"\n    This should set up an isolated environment in which to [`build`](../../cli/reference.md#hatch-build) the project\n    given a set of dependencies and must be a context manager:\n    ```python\n    with environment.build_environment([...]):\n        ...\n    ```\n    The build environment should reflect any\n    [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)\n    the user defined either currently or at the time of\n    [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).\n    \"\"\"\nwith self.get_env_vars():\nyield\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.build_environment_exists","title":"build_environment_exists()","text":"

If the build environment has a caching mechanism, this should indicate whether or not it has already been created.

Source code in src/hatch/env/plugin/interface.py
def build_environment_exists(self):\n\"\"\"\n    If the\n    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n    has a caching mechanism, this should indicate whether or not it has already been created.\n    \"\"\"\nreturn False\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_build_process","title":"get_build_process(build_environment, **kwargs)","text":"

This will be called when the build environment is active:

with environment.build_environment([...]) as build_environment:\n    build_process = environment.get_build_process(build_environment, ...)\n

This should return the standard library's subprocess.Popen with all output captured by stdout. The command is constructed by passing all keyword arguments to construct_build_command.

For an example, open the default implementation below:

Source code in src/hatch/env/plugin/interface.py
def get_build_process(self, build_environment, **kwargs):\n\"\"\"\n    This will be called when the\n    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n    is active:\n    ```python\n    with environment.build_environment([...]) as build_environment:\n        build_process = environment.get_build_process(build_environment, ...)\n    ```\n    This should return the standard library's\n    [subprocess.Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)\n    with all output captured by `stdout`. The command is constructed by passing all keyword arguments to\n    [construct_build_command](reference.md#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command).\n    For an example, open the default implementation below:\n    \"\"\"\nreturn self.platform.capture_process(self.construct_build_command(**kwargs))\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command","title":"construct_build_command(*, directory = None, targets = (), hooks_only = False, no_hooks = False, clean = False, clean_hooks_after = False, clean_only = False)","text":"

This is the canonical way build command options are translated to a subprocess command issued to builders.

Source code in src/hatch/env/plugin/interface.py
def construct_build_command(\nself,\n*,\ndirectory=None,\ntargets=(),\nhooks_only=False,\nno_hooks=False,\nclean=False,\nclean_hooks_after=False,\nclean_only=False,\n):\n\"\"\"\n    This is the canonical way [`build`](../../cli/reference.md#hatch-build) command options are translated to\n    a subprocess command issued to [builders](../builder/reference.md).\n    \"\"\"\ncommand = ['python', '-u', '-m', 'hatchling', 'build', '--app']\nif directory:\ncommand.extend(('--directory', directory))\nif targets:\nfor target in targets:\ncommand.extend(('--target', target))\nif hooks_only:\ncommand.append('--hooks-only')\nif no_hooks:\ncommand.append('--no-hooks')\nif clean:\ncommand.append('--clean')\nif clean_hooks_after:\ncommand.append('--clean-hooks-after')\nif clean_only:\ncommand.append('--clean-only')\nreturn command\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.command_context","title":"command_context()","text":"

A context manager that when active should make executed shell commands reflect any environment variables the user defined either currently or at the time of creation.

For an example, open the default implementation below:

Source code in src/hatch/env/plugin/interface.py
@contextmanager\ndef command_context(self):\n\"\"\"\n    A context manager that when active should make executed shell commands reflect any\n    [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)\n    the user defined either currently or at the time of\n    [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).\n    For an example, open the default implementation below:\n    \"\"\"\nwith self.get_env_vars():\nyield\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.enter_shell","title":"enter_shell(name: str, path: str, args: Iterable[str])","text":"

Spawn a shell within the environment.

This should either use command_context directly or provide the same guarantee.

Source code in src/hatch/env/plugin/interface.py
def enter_shell(self, name: str, path: str, args: Iterable[str]):\n\"\"\"\n    Spawn a [shell](../../config/hatch.md#shell) within the environment.\n    This should either use\n    [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)\n    directly or provide the same guarantee.\n    \"\"\"\nwith self.command_context():\nself.platform.exit_with_command([path, *args])\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.run_shell_command","title":"run_shell_command(command: str, **kwargs: str)","text":"

This should return the standard library's subprocess.CompletedProcess and will always be called when the command_context is active, with the expectation of providing the same guarantee.

Source code in src/hatch/env/plugin/interface.py
def run_shell_command(self, command: str, **kwargs):\n\"\"\"\n    This should return the standard library's\n    [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess)\n    and will always be called when the\n    [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)\n    is active, with the expectation of providing the same guarantee.\n    \"\"\"\nkwargs.setdefault('shell', True)\nreturn self.platform.run_command(command, **kwargs)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.resolve_commands","title":"resolve_commands(commands: list[str])","text":"

This expands each command into one or more commands based on any scripts that the user defined.

Source code in src/hatch/env/plugin/interface.py
def resolve_commands(self, commands: list[str]):\n\"\"\"\n    This expands each command into one or more commands based on any\n    [scripts](../../config/environment/overview.md#scripts) that the user defined.\n    \"\"\"\nfor command in commands:\nyield from self.expand_command(command)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars","title":"get_env_vars() -> EnvVars","text":"

Returns a mapping of environment variables that should be available to the environment. The object can be used as a context manager to temporarily apply the environment variables to the current process.

Note

The environment variable HATCH_ENV_ACTIVE will always be set to the name of the environment.

Source code in src/hatch/env/plugin/interface.py
def get_env_vars(self) -> EnvVars:\n\"\"\"\n    Returns a mapping of environment variables that should be available to the environment. The object can\n    be used as a context manager to temporarily apply the environment variables to the current process.\n    !!! note\n        The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment.\n    \"\"\"\nreturn EnvVars(self.env_vars, self.env_include, self.env_exclude)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.apply_features","title":"apply_features(requirement: str)","text":"

A convenience method that applies any user defined features to the given requirement.

Source code in src/hatch/env/plugin/interface.py
def apply_features(self, requirement: str):\n\"\"\"\n    A convenience method that applies any user defined [features](../../config/environment/overview.md#features)\n    to the given requirement.\n    \"\"\"\nif self.features:\nfeatures = ','.join(self.features)\nreturn f'{requirement}[{features}]'\nreturn requirement\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.construct_pip_install_command","title":"construct_pip_install_command(args: list[str])","text":"

A convenience method for constructing a pip install command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.

Source code in src/hatch/env/plugin/interface.py
def construct_pip_install_command(self, args: list[str]):\n\"\"\"\n    A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/)\n    command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.\n    \"\"\"\ncommand = ['python', '-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-python-version-warning']\n# Default to -1 verbosity\nadd_verbosity_flag(command, self.verbosity, adjustment=-1)\ncommand.extend(args)\nreturn command\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.join_command_args","title":"join_command_args(args: list[str])","text":"

This is used by the run command to construct the root command string from the received arguments.

Source code in src/hatch/env/plugin/interface.py
def join_command_args(self, args: list[str]):\n\"\"\"\n    This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string\n    from the received arguments.\n    \"\"\"\nreturn self.platform.join_command_args(args)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.check_compatibility","title":"check_compatibility()","text":"

This raises an exception if the environment is not compatible with the user's setup. The default behavior checks for platform compatibility and any method override should keep this check.

Source code in src/hatch/env/plugin/interface.py
def check_compatibility(self):\n\"\"\"\n    This raises an exception if the environment is not compatible with the user's setup. The default behavior\n    checks for [platform compatibility](../../config/environment/overview.md#supported-platforms)\n    and any method override should keep this check.\n    \"\"\"\nif self.platforms and self.platform.name not in self.platforms:\nmessage = 'unsupported platform'\nraise OSError(message)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_option_types","title":"get_option_types() -> dict staticmethod","text":"

Returns a mapping of supported options to their respective types so that they can be used by overrides.

Source code in src/hatch/env/plugin/interface.py
@staticmethod\ndef get_option_types() -> dict:\n\"\"\"\n    Returns a mapping of supported options to their respective types so that they can be used by\n    [overrides](../../config/environment/advanced.md#option-overrides).\n    \"\"\"\nreturn {}\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_env_var_option","title":"get_env_var_option(option: str) -> str","text":"

Returns the value of the upper-cased environment variable HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>.

Source code in src/hatch/env/plugin/interface.py
def get_env_var_option(self, option: str) -> str:\n\"\"\"\n    Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`.\n    \"\"\"\nreturn os.environ.get(f'{AppEnvVars.ENV_OPTION_PREFIX}{self.PLUGIN_NAME}_{option}'.upper(), '')\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_context","title":"get_context()","text":"

Returns a subclass of EnvironmentContextFormatter.

Source code in src/hatch/env/plugin/interface.py
def get_context(self):\n\"\"\"\n    Returns a subclass of\n    [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter).\n    \"\"\"\nfrom hatch.env.context import EnvironmentContextFormatter\nreturn EnvironmentContextFormatter(self)\n
"},{"location":"plugins/environment/virtual/","title":"Virtual environment","text":"

This uses virtual environments backed by the standard virtualenv tool.

"},{"location":"plugins/environment/virtual/#configuration","title":"Configuration","text":"

The environment plugin name is virtual.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\ntype = \"virtual\"\n
[envs.<ENV_NAME>]\ntype = \"virtual\"\n
"},{"location":"plugins/environment/virtual/#options","title":"Options","text":"Option Default Description system-packages false Whether or not to give the virtual environment access to the system site-packages directory python The version of Python to find on your system and subsequently use to create the environment, defaulting to the HATCH_PYTHON environment variable, followed by the first Python executable found along your PATH, followed by the Python executable Hatch is running on. Setting the HATCH_PYTHON environment variable to self will force the use of the Python executable Hatch is running on. For more information, see the documentation. path An explicit path to the virtual environment. The path may be absolute or relative to the project root. Any environments that inherit this option will also use this path. The environment variable HATCH_ENV_TYPE_VIRTUAL_PATH may be used, which will take precedence."},{"location":"plugins/environment/virtual/#location","title":"Location","text":"

The location of environments is determined in the following heuristic order:

  1. The path option
  2. A directory named after the environment within the configured virtual environment directory if the directory resides somewhere within the project root or if it is set to a .virtualenvs directory within the user's home directory
  3. Otherwise, environments are stored within the configured virtual environment directory in a deeply nested structure in order to support multiple projects

Additionally, when the path option is not used, the name of the directory for the default environment will be the normalized project name to provide a more meaningful default shell prompt.

"},{"location":"plugins/environment/virtual/#troubleshooting","title":"Troubleshooting","text":""},{"location":"plugins/environment/virtual/#macos-sip","title":"macOS SIP","text":"

If you need to set linker environment variables like those starting with DYLD_ or LD_, any executable secured by System Integrity Protection that is invoked when running commands will not see those environment variable modifications as macOS strips those.

Hatch interprets such commands as shell commands but deliberately ignores such paths to protected shells. This workaround suffices for the majority of use cases but there are 2 situations in which it may not:

  1. There are no unprotected sh, bash, zsh, nor fish executables found along PATH.
  2. The desired executable is a project's script, and the location of environments contains spaces or is longer than 1241 characters. In this case pip and other installers will create such an entry point with a shebang pointing to /bin/sh (which is protected) to avoid shebang limitations. Rather than changing the location, you could invoke the script as e.g. python -m pytest (if the project supports that method of invocation by shipping a __main__.py).
  1. The shebang length limit is usually 127 but 3 characters surround the executable path: #!<EXE_PATH>\\n \u21a9

"},{"location":"plugins/environment-collector/custom/","title":"Custom environment collector","text":"

This is a custom class in a given Python file that inherits from the EnvironmentCollectorInterface.

"},{"location":"plugins/environment-collector/custom/#configuration","title":"Configuration","text":"

The environment collector plugin name is custom.

pyproject.toml hatch.toml
[tool.hatch.env.collectors.custom]\n
[env.collectors.custom]\n
"},{"location":"plugins/environment-collector/custom/#options","title":"Options","text":"Option Default Description path hatch_plugins.py The path of the Python file"},{"location":"plugins/environment-collector/custom/#example","title":"Example","text":"hatch_plugins.py
from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface\n\n\nclass CustomEnvironmentCollector(EnvironmentCollectorInterface):\n    ...\n

If multiple subclasses are found, you must define a function named get_environment_collector that returns the desired environment collector.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

"},{"location":"plugins/environment-collector/default/","title":"Default environment collector","text":"

This adds the default environment with type set to virtual and will always be applied.

"},{"location":"plugins/environment-collector/default/#configuration","title":"Configuration","text":"

The environment collector plugin name is default.

pyproject.toml hatch.toml
[tool.hatch.env.collectors.default]\n
[env.collectors.default]\n
"},{"location":"plugins/environment-collector/default/#options","title":"Options","text":"

There are no options available currently.

"},{"location":"plugins/environment-collector/reference/","title":"Environment collector plugins","text":"

Environment collectors allow for dynamically modifying environments or adding environments beyond those defined in config. Users can override default values provided by each environment.

"},{"location":"plugins/environment-collector/reference/#installation","title":"Installation","text":"

Any required environment collectors that are not built-in must be manually installed alongside Hatch or listed in the tool.hatch.env.requires array for automatic management:

pyproject.toml hatch.toml
[tool.hatch.env]\nrequires = [\n\"...\",\n]\n
[env]\nrequires = [\n\"...\",\n]\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface","title":"EnvironmentCollectorInterface","text":"

Example usage:

plugin.py hooks.py
from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface\n\n\nclass SpecialEnvironmentCollector(EnvironmentCollectorInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialEnvironmentCollector\n\n\n@hookimpl\ndef hatch_register_environment_collector():\n    return SpecialEnvironmentCollector\n
Source code in src/hatch/env/collectors/plugin/interface.py
class EnvironmentCollectorInterface:\n\"\"\"\n    Example usage:\n    === \":octicons-file-code-16: plugin.py\"\n        ```python\n        from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface\n        class SpecialEnvironmentCollector(EnvironmentCollectorInterface):\n            PLUGIN_NAME = 'special'\n            ...\n        ```\n    === \":octicons-file-code-16: hooks.py\"\n        ```python\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialEnvironmentCollector\n        @hookimpl\n        def hatch_register_environment_collector():\n            return SpecialEnvironmentCollector\n        ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, root, config):\nself.__root = root\nself.__config = config\n@property\ndef root(self):\n\"\"\"\n        The root of the project tree as a path-like object.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.env.collectors.<PLUGIN_NAME>]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [env.collectors.<PLUGIN_NAME>]\n            ```\n        \"\"\"\nreturn self.__config\ndef get_initial_config(self) -> dict[str, dict]:\n\"\"\"\n        Returns configuration for environments keyed by the environment or matrix name.\n        \"\"\"\nreturn {}\ndef finalize_config(self, config: dict[str, dict]):\n\"\"\"\n        Finalizes configuration for environments keyed by the environment or matrix name. This will override\n        any user-defined settings and any collectors that ran before this call.\n        This is called before matrices are turned into concrete environments.\n        \"\"\"\ndef finalize_environments(self, config: dict[str, dict]):\n\"\"\"\n        Finalizes configuration for environments keyed by the environment name. This will override\n        any user-defined settings and any collectors that ran before this call.\n        This is called after matrices are turned into concrete environments.\n        \"\"\"\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.root","title":"root property","text":"

The root of the project tree as a path-like object.

"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.config","title":"config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.env.collectors.<PLUGIN_NAME>]\n
[env.collectors.<PLUGIN_NAME>]\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.get_initial_config","title":"get_initial_config() -> dict[str, dict]","text":"

Returns configuration for environments keyed by the environment or matrix name.

Source code in src/hatch/env/collectors/plugin/interface.py
def get_initial_config(self) -> dict[str, dict]:\n\"\"\"\n    Returns configuration for environments keyed by the environment or matrix name.\n    \"\"\"\nreturn {}\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.finalize_config","title":"finalize_config(config: dict[str, dict])","text":"

Finalizes configuration for environments keyed by the environment or matrix name. This will override any user-defined settings and any collectors that ran before this call.

This is called before matrices are turned into concrete environments.

Source code in src/hatch/env/collectors/plugin/interface.py
def finalize_config(self, config: dict[str, dict]):\n\"\"\"\n    Finalizes configuration for environments keyed by the environment or matrix name. This will override\n    any user-defined settings and any collectors that ran before this call.\n    This is called before matrices are turned into concrete environments.\n    \"\"\"\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.finalize_environments","title":"finalize_environments(config: dict[str, dict])","text":"

Finalizes configuration for environments keyed by the environment name. This will override any user-defined settings and any collectors that ran before this call.

This is called after matrices are turned into concrete environments.

Source code in src/hatch/env/collectors/plugin/interface.py
def finalize_environments(self, config: dict[str, dict]):\n\"\"\"\n    Finalizes configuration for environments keyed by the environment name. This will override\n    any user-defined settings and any collectors that ran before this call.\n    This is called after matrices are turned into concrete environments.\n    \"\"\"\n
"},{"location":"plugins/metadata-hook/custom/","title":"Custom metadata hook","text":"

This is a custom class in a given Python file that inherits from the MetadataHookInterface.

"},{"location":"plugins/metadata-hook/custom/#configuration","title":"Configuration","text":"

The metadata hook plugin name is custom.

pyproject.toml hatch.toml
[tool.hatch.metadata.hooks.custom]\n
[metadata.hooks.custom]\n
"},{"location":"plugins/metadata-hook/custom/#options","title":"Options","text":"Option Default Description path hatch_build.py The path of the Python file"},{"location":"plugins/metadata-hook/custom/#example","title":"Example","text":"hatch_build.py
from hatchling.metadata.plugin.interface import MetadataHookInterface\n\n\nclass CustomMetadataHook(MetadataHookInterface):\n    ...\n

If multiple subclasses are found, you must define a function named get_metadata_hook that returns the desired build hook.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

"},{"location":"plugins/metadata-hook/reference/","title":"Metadata hook plugins","text":"

Metadata hooks allow for the modification of project metadata after it has been loaded.

"},{"location":"plugins/metadata-hook/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface","title":"MetadataHookInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.metadata.plugin.interface import MetadataHookInterface\n\n\nclass SpecialMetadataHook(MetadataHookInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialMetadataHook\n\n\n@hookimpl\ndef hatch_register_metadata_hook():\n    return SpecialMetadataHook\n
Source code in backend/src/hatchling/metadata/plugin/interface.py
class MetadataHookInterface(ABC):  # no cov\n\"\"\"\n    Example usage:\n    === \":octicons-file-code-16: plugin.py\"\n        ```python\n        from hatchling.metadata.plugin.interface import MetadataHookInterface\n        class SpecialMetadataHook(MetadataHookInterface):\n            PLUGIN_NAME = 'special'\n            ...\n        ```\n    === \":octicons-file-code-16: hooks.py\"\n        ```python\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialMetadataHook\n        @hookimpl\n        def hatch_register_metadata_hook():\n            return SpecialMetadataHook\n        ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, root: str, config: dict) -> None:\nself.__root = root\nself.__config = config\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict:\n\"\"\"\n        The hook configuration.\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.metadata.hooks.<PLUGIN_NAME>]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [metadata.hooks.<PLUGIN_NAME>]\n            ```\n        \"\"\"\nreturn self.__config\n@abstractmethod\ndef update(self, metadata: dict) -> None:\n\"\"\"\n        This updates the metadata mapping of the `project` table in-place.\n        \"\"\"\ndef get_known_classifiers(self) -> list[str]:\n\"\"\"\n        This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.\n        \"\"\"\nreturn []\n
"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.root","title":"root: str property","text":"

The root of the project tree.

"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.config","title":"config: dict property","text":"

The hook configuration.

pyproject.toml hatch.toml
[tool.hatch.metadata.hooks.<PLUGIN_NAME>]\n
[metadata.hooks.<PLUGIN_NAME>]\n
"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.update","title":"update(metadata: dict) -> None abstractmethod","text":"

This updates the metadata mapping of the project table in-place.

Source code in backend/src/hatchling/metadata/plugin/interface.py
@abstractmethod\ndef update(self, metadata: dict) -> None:\n\"\"\"\n    This updates the metadata mapping of the `project` table in-place.\n    \"\"\"\n
"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.get_known_classifiers","title":"get_known_classifiers() -> list[str]","text":"

This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.

Source code in backend/src/hatchling/metadata/plugin/interface.py
def get_known_classifiers(self) -> list[str]:\n\"\"\"\n    This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.\n    \"\"\"\nreturn []\n
"},{"location":"plugins/publisher/package-index/","title":"Index publisher","text":"

See the documentation for publishing.

"},{"location":"plugins/publisher/package-index/#configuration","title":"Configuration","text":"

The publisher plugin name is index.

config.toml
[publish.index]\n
"},{"location":"plugins/publisher/package-index/#options","title":"Options","text":"Flag Config name Description -r/--repo repo The repository with which to publish artifacts -u/--user user The user with which to authenticate -a/--auth auth The credentials to use for authentication --ca-cert ca-cert The path to a CA bundle --client-cert client-cert The path to a client certificate, optionally containing the private key --client-key client-key The path to the client certificate's private key repos A table of named repositories to their respective options"},{"location":"plugins/publisher/package-index/#repositories","title":"Repositories","text":"

All top-level options can be overridden per repository using the repos table with a required url attribute for each repository. The following shows the default configuration:

config.toml
[publish.index.repos.main]\nurl = \"https://upload.pypi.org/legacy/\"\n\n[publish.index.repos.test]\nurl = \"https://test.pypi.org/legacy/\"\n

The repo and repos options have no effect.

"},{"location":"plugins/publisher/reference/","title":"Publisher plugins","text":""},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface","title":"PublisherInterface","text":"

Example usage:

plugin.py hooks.py
from hatch.publish.plugin.interface import PublisherInterface\n\n\nclass SpecialPublisher(PublisherInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialPublisher\n\n\n@hookimpl\ndef hatch_register_publisher():\n    return SpecialPublisher\n
Source code in src/hatch/publish/plugin/interface.py
class PublisherInterface(ABC):\n\"\"\"\n    Example usage:\n    === \":octicons-file-code-16: plugin.py\"\n        ```python\n        from hatch.publish.plugin.interface import PublisherInterface\n        class SpecialPublisher(PublisherInterface):\n            PLUGIN_NAME = 'special'\n            ...\n        ```\n    === \":octicons-file-code-16: hooks.py\"\n        ```python\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialPublisher\n        @hookimpl\n        def hatch_register_publisher():\n            return SpecialPublisher\n        ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, app, root, cache_dir, project_config, plugin_config):\nself.__app = app\nself.__root = root\nself.__cache_dir = cache_dir\nself.__project_config = project_config\nself.__plugin_config = plugin_config\nself.__disable = None\n@property\ndef app(self):\n\"\"\"\n        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).\n        \"\"\"\nreturn self.__app\n@property\ndef root(self):\n\"\"\"\n        The root of the project tree as a path-like object.\n        \"\"\"\nreturn self.__root\n@property\ndef cache_dir(self):\n\"\"\"\n        The directory reserved exclusively for this plugin as a path-like object.\n        \"\"\"\nreturn self.__cache_dir\n@property\ndef project_config(self) -> dict:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.publish.<PLUGIN_NAME>]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [publish.<PLUGIN_NAME>]\n            ```\n        \"\"\"\nreturn self.__project_config\n@property\ndef plugin_config(self) -> dict:\n\"\"\"\n        This is defined in Hatch's [config file](../../config/hatch.md).\n        === \":octicons-file-code-16: config.toml\"\n            ```toml\n            [publish.<PLUGIN_NAME>]\n            ```\n        \"\"\"\nreturn self.__plugin_config\n@property\ndef disable(self):\n\"\"\"\n        Whether this plugin is disabled, thus requiring confirmation when publishing. Local\n        [project configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.project_config)\n        takes precedence over global\n        [plugin configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.plugin_config).\n        \"\"\"\nif self.__disable is None:\nif 'disable' in self.project_config:\ndisable = self.project_config['disable']\nif not isinstance(disable, bool):\nmessage = f'Field `tool.hatch.publish.{self.PLUGIN_NAME}.disable` must be a boolean'\nraise TypeError(message)\nelse:\ndisable = self.plugin_config.get('disable', False)\nif not isinstance(disable, bool):\nmessage = f'Global plugin configuration `publish.{self.PLUGIN_NAME}.disable` must be a boolean'\nraise TypeError(message)\nself.__disable = disable\nreturn self.__disable\n@abstractmethod\ndef publish(self, artifacts: list[str], options: dict):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This is called directly by the [`publish`](../../cli/reference.md#hatch-publish) command\n        with the arguments and options it receives.\n        \"\"\"\n
"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.app","title":"app property","text":"

An instance of Application.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.root","title":"root property","text":"

The root of the project tree as a path-like object.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.cache_dir","title":"cache_dir property","text":"

The directory reserved exclusively for this plugin as a path-like object.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.project_config","title":"project_config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.publish.<PLUGIN_NAME>]\n
[publish.<PLUGIN_NAME>]\n
"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.plugin_config","title":"plugin_config: dict property","text":"

This is defined in Hatch's config file.

config.toml
[publish.<PLUGIN_NAME>]\n
"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.disable","title":"disable property","text":"

Whether this plugin is disabled, thus requiring confirmation when publishing. Local project configuration takes precedence over global plugin configuration.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.publish","title":"publish(artifacts: list[str], options: dict) abstractmethod","text":"

REQUIRED

This is called directly by the publish command with the arguments and options it receives.

Source code in src/hatch/publish/plugin/interface.py
@abstractmethod\ndef publish(self, artifacts: list[str], options: dict):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This is called directly by the [`publish`](../../cli/reference.md#hatch-publish) command\n    with the arguments and options it receives.\n    \"\"\"\n
"},{"location":"plugins/version-scheme/reference/","title":"Version scheme plugins","text":""},{"location":"plugins/version-scheme/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface","title":"VersionSchemeInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.version.scheme.plugin.interface import VersionSchemeInterface\n\n\nclass SpecialVersionScheme(VersionSchemeInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialVersionScheme\n\n\n@hookimpl\ndef hatch_register_version_scheme():\n    return SpecialVersionScheme\n
Source code in backend/src/hatchling/version/scheme/plugin/interface.py
class VersionSchemeInterface(ABC):  # no cov\n\"\"\"\n    Example usage:\n    === \":octicons-file-code-16: plugin.py\"\n        ```python\n        from hatchling.version.scheme.plugin.interface import VersionSchemeInterface\n        class SpecialVersionScheme(VersionSchemeInterface):\n            PLUGIN_NAME = 'special'\n            ...\n        ```\n    === \":octicons-file-code-16: hooks.py\"\n        ```python\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialVersionScheme\n        @hookimpl\n        def hatch_register_version_scheme():\n            return SpecialVersionScheme\n        ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, root: str, config: dict) -> None:\nself.__root = root\nself.__config = config\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree as a string.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.version]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [version]\n            ```\n        \"\"\"\nreturn self.__config\n@abstractmethod\ndef update(self, desired_version: str, original_version: str, version_data: dict) -> str:\n\"\"\"\n        This should return a normalized form of the desired version and verify that it\n        is higher than the original version.\n        \"\"\"\n
"},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.root","title":"root: str property","text":"

The root of the project tree as a string.

"},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.config","title":"config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.version]\n
[version]\n
"},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.update","title":"update(desired_version: str, original_version: str, version_data: dict) -> str abstractmethod","text":"

This should return a normalized form of the desired version and verify that it is higher than the original version.

Source code in backend/src/hatchling/version/scheme/plugin/interface.py
@abstractmethod\ndef update(self, desired_version: str, original_version: str, version_data: dict) -> str:\n\"\"\"\n    This should return a normalized form of the desired version and verify that it\n    is higher than the original version.\n    \"\"\"\n
"},{"location":"plugins/version-scheme/standard/","title":"Standard version scheme","text":"

See the documentation for versioning.

"},{"location":"plugins/version-scheme/standard/#configuration","title":"Configuration","text":"

The version scheme plugin name is standard.

pyproject.toml hatch.toml
[tool.hatch.version]\nscheme = \"standard\"\n
[version]\nscheme = \"standard\"\n
"},{"location":"plugins/version-scheme/standard/#options","title":"Options","text":"Option Description validate-bump When setting a specific version, this determines whether to check that the new version is higher than the original. The default is true."},{"location":"plugins/version-source/code/","title":"Code version source","text":""},{"location":"plugins/version-source/code/#updates","title":"Updates","text":"

Setting the version is not supported.

"},{"location":"plugins/version-source/code/#configuration","title":"Configuration","text":"

The version source plugin name is code.

pyproject.toml hatch.toml
[tool.hatch.version]\nsource = \"code\"\n
[version]\nsource = \"code\"\n
"},{"location":"plugins/version-source/code/#options","title":"Options","text":"Option Description path (required) A relative path to a Python file or extension module that will be loaded expression A Python expression that when evaluated in the context of the loaded file returns the version. The default expression is simply __version__. search-paths A list of relative paths to directories that will be prepended to Python's search path"},{"location":"plugins/version-source/code/#missing-imports","title":"Missing imports","text":"

If the chosen path imports another module in your project, then you'll need to use absolute imports coupled with the search-paths option. For example, say you need to load the following file:

src/pkg/__init__.py
from ._version import get_version\n\n__version__ = get_version()\n

You should change it to:

src/pkg/__init__.py
from pkg._version import get_version\n\n__version__ = get_version()\n

and the configuration would become:

pyproject.toml hatch.toml
[tool.hatch.version]\nsource = \"code\"\npath = \"src/pkg/__init__.py\"\nsearch-paths = [\"src\"]\n
[version]\nsource = \"code\"\npath = \"src/pkg/__init__.py\"\nsearch-paths = [\"src\"]\n
"},{"location":"plugins/version-source/env/","title":"Environment version source","text":"

Retrieves the version from an environment variable. This can be useful in build pipelines where the version is set by an external trigger.

"},{"location":"plugins/version-source/env/#updates","title":"Updates","text":"

Setting the version is not supported.

"},{"location":"plugins/version-source/env/#configuration","title":"Configuration","text":"

The version source plugin name is env.

pyproject.toml hatch.toml
[tool.hatch.version]\nsource = \"env\"\n
[version]\nsource = \"env\"\n
"},{"location":"plugins/version-source/env/#options","title":"Options","text":"Option Description variable (required) The name of the environment variable"},{"location":"plugins/version-source/reference/","title":"Version source plugins","text":""},{"location":"plugins/version-source/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface","title":"VersionSourceInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.version.source.plugin.interface import VersionSourceInterface\n\n\nclass SpecialVersionSource(VersionSourceInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialVersionSource\n\n\n@hookimpl\ndef hatch_register_version_source():\n    return SpecialVersionSource\n
Source code in backend/src/hatchling/version/source/plugin/interface.py
class VersionSourceInterface(ABC):  # no cov\n\"\"\"\n    Example usage:\n    === \":octicons-file-code-16: plugin.py\"\n        ```python\n        from hatchling.version.source.plugin.interface import VersionSourceInterface\n        class SpecialVersionSource(VersionSourceInterface):\n            PLUGIN_NAME = 'special'\n            ...\n        ```\n    === \":octicons-file-code-16: hooks.py\"\n        ```python\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialVersionSource\n        @hookimpl\n        def hatch_register_version_source():\n            return SpecialVersionSource\n        ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, root: str, config: dict) -> None:\nself.__root = root\nself.__config = config\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree as a string.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict:\n\"\"\"\n        === \":octicons-file-code-16: pyproject.toml\"\n            ```toml\n            [tool.hatch.version]\n            ```\n        === \":octicons-file-code-16: hatch.toml\"\n            ```toml\n            [version]\n            ```\n        \"\"\"\nreturn self.__config\n@abstractmethod\ndef get_version_data(self) -> dict:\n\"\"\"\n        This should return a mapping with a `version` key representing the current version of the project and will be\n        displayed when invoking the [`version`](../../cli/reference.md#hatch-version) command without any arguments.\n        The mapping can contain anything else and will be passed to\n        [set_version](reference.md#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version)\n        when updating the version.\n        \"\"\"\ndef set_version(self, version: str, version_data: dict) -> None:\n\"\"\"\n        This should update the version to the first argument with the data provided during retrieval.\n        \"\"\"\nraise NotImplementedError\n
"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.root","title":"root: str property","text":"

The root of the project tree as a string.

"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.config","title":"config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.version]\n
[version]\n
"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.get_version_data","title":"get_version_data() -> dict abstractmethod","text":"

This should return a mapping with a version key representing the current version of the project and will be displayed when invoking the version command without any arguments.

The mapping can contain anything else and will be passed to set_version when updating the version.

Source code in backend/src/hatchling/version/source/plugin/interface.py
@abstractmethod\ndef get_version_data(self) -> dict:\n\"\"\"\n    This should return a mapping with a `version` key representing the current version of the project and will be\n    displayed when invoking the [`version`](../../cli/reference.md#hatch-version) command without any arguments.\n    The mapping can contain anything else and will be passed to\n    [set_version](reference.md#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version)\n    when updating the version.\n    \"\"\"\n
"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version","title":"set_version(version: str, version_data: dict) -> None","text":"

This should update the version to the first argument with the data provided during retrieval.

Source code in backend/src/hatchling/version/source/plugin/interface.py
def set_version(self, version: str, version_data: dict) -> None:\n\"\"\"\n    This should update the version to the first argument with the data provided during retrieval.\n    \"\"\"\nraise NotImplementedError\n
"},{"location":"plugins/version-source/regex/","title":"Regex version source","text":"

See the documentation for versioning.

"},{"location":"plugins/version-source/regex/#updates","title":"Updates","text":"

Setting the version is supported.

"},{"location":"plugins/version-source/regex/#configuration","title":"Configuration","text":"

The version source plugin name is regex.

pyproject.toml hatch.toml
[tool.hatch.version]\nsource = \"regex\"\n
[version]\nsource = \"regex\"\n
"},{"location":"plugins/version-source/regex/#options","title":"Options","text":"Option Description path (required) A relative path to a file containing the project's version pattern A regular expression that has a named group called version that represents the version. The default pattern looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v."}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"Hatch","text":"CI/CD Docs Package Meta

Hatch is a modern, extensible Python project manager.

"},{"location":"#features","title":"Features","text":""},{"location":"#license","title":"License","text":"

Hatch is distributed under the terms of the MIT license.

"},{"location":"#navigation","title":"Navigation","text":"

Documentation for specific MAJOR.MINOR versions can be chosen by using the dropdown on the top of every page. The dev version reflects changes that have not yet been released.

Also, desktop readers can use special keyboard shortcuts:

Keys Action Navigate to the \"previous\" page Navigate to the \"next\" page Display the search modal"},{"location":"build/","title":"Builds","text":""},{"location":"build/#configuration","title":"Configuration","text":"

Builds are configured using the tool.hatch.build table. Every target is defined by a section within tool.hatch.build.targets, for example:

pyproject.toml hatch.toml
[tool.hatch.build.targets.sdist]\nexclude = [\n\"/.github\",\n\"/docs\",\n]\n\n[tool.hatch.build.targets.wheel]\npackages = [\"src/foo\"]\n
[build.targets.sdist]\nexclude = [\n\"/.github\",\n\"/docs\",\n]\n\n[build.targets.wheel]\npackages = [\"src/foo\"]\n
"},{"location":"build/#building","title":"Building","text":"

Invoking the build command without any arguments will build the sdist and wheel targets:

$ hatch build\n[sdist]\ndist/hatch_demo-1rc0.tar.gz\n\n[wheel]\ndist/hatch_demo-1rc0-py3-none-any.whl\n

To only build specific targets, use the -t/--target option:

$ hatch build -t wheel\n[wheel]\ndist/hatch_demo-1rc0-py3-none-any.whl\n

If the target supports multiple versions, you can specify the exact versions to build by appending a colon followed by the desired versions separated by commas:

$ hatch -v build -t wheel:standard\n[wheel]\nBuilding `wheel` version `standard`\ndist/hatch_demo-1rc0-py3-none-any.whl\n
"},{"location":"build/#packaging-ecosystem","title":"Packaging ecosystem","text":"

Hatch complies with modern Python packaging specs and therefore your projects can be used by other tools with Hatch serving as just the build backend.

So you could use tox as an alternative to Hatch's environment management, or cibuildwheel to distribute packages for every platform, and they both will transparently use Hatch without any extra modification.

"},{"location":"environment/","title":"Environments","text":"

Environments are designed to allow for isolated workspaces for testing, building documentation, or anything else projects need.

Unless an environment is chosen explicitly, Hatch will use the default environment.

"},{"location":"environment/#creation","title":"Creation","text":"

You can create environments by using the env create command. Let's enter the directory of the project we created in the setup phase:

$ hatch env create\nCreating environment: default\nInstalling project in development mode\nSyncing dependencies\n

Tip

You never need to manually create environments as spawning a shell or running commands within one will automatically trigger creation.

"},{"location":"environment/#entering-environments","title":"Entering environments","text":"

You can spawn a shell within an environment by using the shell command.

$ hatch shell\n(hatch-demo) $\n

Now confirm the project has been installed:

(hatch-demo) $ pip show hatch-demo\nName: hatch-demo\nVersion: 0.0.1\n...\n

Finally, see where your environment's Python is located:

(hatch-demo) $ python -c \"import sys;print(sys.executable)\"\n...\n

You can type exit to leave the environment.

"},{"location":"environment/#command-execution","title":"Command execution","text":"

The run command allows you to execute commands in an environment as if you had already entered it. For example, running the following command will output the same path as before:

hatch run python -c \"import sys;print(sys.executable)\"\n
"},{"location":"environment/#scripts","title":"Scripts","text":"

You can also run any scripts that have been defined.

You'll notice that in the pyproject.toml file there are already scripts defined in the default environment. Try running the test command, which invokes pytest with some default arguments:

hatch run test\n

All additional arguments are passed through to that script, so for example if you wanted to see the version of pytest and which plugins are installed you could do:

hatch run test -VV\n
"},{"location":"environment/#dependencies","title":"Dependencies","text":"

Hatch ensures that environments are always compatible with the currently defined project dependencies (if installed and in dev mode) and environment dependencies.

For example, add cowsay as a dependency then try to run it:

$ hatch run cowsay \"Hello, world!\"\nSyncing dependencies\n  _____________\n| Hello, world! |\n  =============\n             \\\n              \\\n                ^__^\n                (oo)\\_______\n                (__)\\       )\\/\\\n                    ||----w |\n                    ||     ||\n
"},{"location":"environment/#selection","title":"Selection","text":"

You can select which environment to enter or run commands in by using the -e/--env root option or by setting the HATCH_ENV environment variable.

The run command allows for more explicit selection by prepending <ENV_NAME>: to commands. For example, if you had the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.docs]\ndependencies = [\n\"mkdocs\"\n]\n[tool.hatch.envs.docs.scripts]\nbuild = \"mkdocs build --clean --strict\"\nserve = \"mkdocs serve --dev-addr localhost:8000\"\n
[envs.docs]\ndependencies = [\n\"mkdocs\"\n]\n[envs.docs.scripts]\nbuild = \"mkdocs build --clean --strict\"\nserve = \"mkdocs serve --dev-addr localhost:8000\"\n

you could then serve your documentation by running:

hatch run docs:serve\n

Tip

If you've already entered an environment, commands will target it by default.

"},{"location":"environment/#matrix","title":"Matrix","text":"

Every environment can define its own set of matrices:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"pytest\"\n]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeatures = [\"foo\", \"bar\"]\n
[envs.test]\ndependencies = [\n\"pytest\"\n]\n\n[[envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[envs.test.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeatures = [\"foo\", \"bar\"]\n

Using the env show command would then display:

$ hatch env show --ascii\n     Standalone\n+---------+---------+\n| Name    | Type    |\n+=========+=========+\n| default | virtual |\n+---------+---------+\n                       Matrices\n+------+---------+---------------------+--------------+\n| Name | Type    | Envs                | Dependencies |\n+======+=========+=====================+==============+\n| test | virtual | test.py2.7-42       | pytest       |\n|      |         | test.py2.7-3.14     |              |\n|      |         | test.py3.8-42       |              |\n|      |         | test.py3.8-3.14     |              |\n|      |         | test.py3.8-9000-foo |              |\n|      |         | test.py3.8-9000-bar |              |\n|      |         | test.py3.9-9000-foo |              |\n|      |         | test.py3.9-9000-bar |              |\n+------+---------+---------------------+--------------+\n
"},{"location":"environment/#removal","title":"Removal","text":"

You can remove a single environment or environment matrix by using the env remove command or all of a project's environments by using the env prune command.

"},{"location":"install/","title":"Installation","text":""},{"location":"install/#github-releases","title":"GitHub releases","text":"

Each release provides the following:

"},{"location":"install/#pip","title":"pip","text":"

Hatch is available on PyPI and can be installed with pip.

pip install hatch\n

Warning

This method modifies the Python environment in which you choose to install. Consider instead using pipx to avoid dependency conflicts.

"},{"location":"install/#pipx","title":"pipx","text":"

pipx allows for the global installation of Python applications in isolated environments.

pipx install hatch\n
"},{"location":"install/#homebrew","title":"Homebrew","text":"

See the formula for more details.

brew install hatch\n
"},{"location":"install/#conda","title":"Conda","text":"

See the feedstock for more details.

conda install -c conda-forge hatch\n

or with mamba:

mamba install hatch\n

Warning

This method modifies the Conda environment in which you choose to install. Consider instead using pipx or condax to avoid dependency conflicts.

"},{"location":"install/#macports","title":"MacPorts","text":"

See the port for more details.

sudo port install hatch\n
"},{"location":"install/#fedora","title":"Fedora","text":"

The minimum supported version is 37, currently in development as Rawhide.

sudo dnf install hatch\n
"},{"location":"install/#void-linux","title":"Void Linux","text":"
xbps-install hatch\n
"},{"location":"install/#build-system-availability","title":"Build system availability","text":"

Hatchling is Hatch's build backend which you will never need to install manually. See its changelog for version information.

"},{"location":"intro/","title":"Introduction","text":""},{"location":"intro/#setup","title":"Setup","text":"

Projects can be setup for use by Hatch using the new command.

"},{"location":"intro/#new-project","title":"New project","text":"

Let's say you want to create a project named Hatch Demo. You would run:

hatch new \"Hatch Demo\"\n

This would create the following structure in your current working directory:

hatch-demo\n\u251c\u2500\u2500 src\n\u2502   \u2514\u2500\u2500 hatch_demo\n\u2502       \u251c\u2500\u2500 __about__.py\n\u2502       \u2514\u2500\u2500 __init__.py\n\u251c\u2500\u2500 tests\n\u2502   \u2514\u2500\u2500 __init__.py\n\u251c\u2500\u2500 LICENSE.txt\n\u251c\u2500\u2500 README.md\n\u2514\u2500\u2500 pyproject.toml\n

Tip

There are many ways to customize project generation.

"},{"location":"intro/#existing-project","title":"Existing project","text":"

To initialize an existing project, enter the directory containing the project and run the following:

hatch new --init\n

If your project has a setup.py file the command will automatically migrate setuptools configuration for you. Otherwise, this will interactively guide you through the setup process.

"},{"location":"intro/#project-metadata","title":"Project metadata","text":"

Next you'll want to define more of your project's metadata located in the pyproject.toml file. You can specify things like its license, the supported versions of Python, and URLs referring to various parts of your project, like documentation.

"},{"location":"intro/#dependencies","title":"Dependencies","text":"

The last step of the setup process is to define any dependencies that you'd like your project to begin with.

"},{"location":"intro/#configuration","title":"Configuration","text":"

All project-specific configuration recognized by Hatch can be defined in either the pyproject.toml file, or a file named hatch.toml where options are not contained within the tool.hatch table:

pyproject.toml hatch.toml
[tool.hatch]\noption = \"...\"\n\n[tool.hatch.table1]\noption = \"...\"\n\n[tool.hatch.table2]\noption = \"...\"\n
option = \"...\"\n\n[table1]\noption = \"...\"\n\n[table2]\noption = \"...\"\n

Top level keys in the latter file take precedence when defined in both.

Tip

If you want to make your file more compact, you can use dotted keys, turning the above example into:

pyproject.toml hatch.toml
[tool.hatch]\noption = \"...\"\ntable1.option = \"...\"\ntable2.option = \"...\"\n
option = \"...\"\ntable1.option = \"...\"\ntable2.option = \"...\"\n
"},{"location":"next-steps/","title":"Next steps","text":""},{"location":"next-steps/#learn-more","title":"Learn more","text":"

At this point you should have a basic understanding of how to use Hatch.

Now you may want to check out advanced configuration for environments or builds, set up your preferred shell, or read more about Hatch's CLI.

After that, check out the Hatch Showcase project to see examples of what is possible.

Finally, if you see a need, feel free to write a plugin for extended functionality.

"},{"location":"next-steps/#community","title":"Community","text":"

For any projects using Hatch, you may add its official badge somewhere prominent like the README.

MarkdownreStructuredText
[![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch)\n
.. image:: https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg\n   :alt: Hatch project\n   :target: https://github.com/pypa/hatch\n
"},{"location":"publish/","title":"Publishing","text":"

After your project is built, you can distribute it using the publish command.

The -p/--publisher option controls which publisher to use, with the default being index.

"},{"location":"publish/#artifact-selection","title":"Artifact selection","text":"

By default, the dist directory located at the root of your project will be used:

$ hatch publish\ndist/hatch_demo-1rc0-py3-none-any.whl ... success\ndist/hatch_demo-1rc0.tar.gz ... success\n\n[hatch-demo]\nhttps://pypi.org/project/hatch-demo/1rc0/\n

You can instead pass specific paths as arguments:

hatch publish /path/to/artifacts foo-1.tar.gz\n

Only files ending with .whl or .tar.gz will be published.

"},{"location":"publish/#repository","title":"Repository","text":"

You can select the repository with which to upload using the -r/--repo option or by setting the HATCH_INDEX_REPO environment variable.

Rather than specifying the full URL of a repository, you can use a named repository from a publish.index.repos table defined in Hatch's config file:

config.toml
[publish.index.repos.private]\nurl = \"...\"\n...\n

The following repository names are reserved by Hatch and cannot be overridden:

Name Repository main https://upload.pypi.org/legacy/ test https://test.pypi.org/legacy/

The main repository is used by default.

"},{"location":"publish/#authentication","title":"Authentication","text":"

The first time you publish to a repository you need to authenticate using the -u/--user (environment variable HATCH_INDEX_USER) and -a/--auth (environment variable HATCH_INDEX_AUTH) options. You will be prompted if either option is not provided.

The user that most recently published to the chosen repository is cached, with their credentials saved to the system keyring, so that they will no longer need to provide authentication information.

For automated releasing to PyPI, it is recommended that you use per-project API tokens.

"},{"location":"publish/#confirmation","title":"Confirmation","text":"

You can require a confirmation prompt or use of the -y/--yes flag by setting publishers' disable option to true in either Hatch's config file or project-specific configuration (which takes precedence):

config.toml pyproject.toml hatch.toml
[publish.index]\ndisable = true\n
[tool.hatch.publish.index]\ndisable = true\n
[publish.index]\ndisable = true\n
"},{"location":"version/","title":"Versioning","text":""},{"location":"version/#configuration","title":"Configuration","text":"

When the version is not statically set, configuration is defined in the tool.hatch.version table. The source option determines the source to use for retrieving and updating the version. The regex source is used by default.

The regex source requires an option path that represents a relative path to a file containing the project's version:

pyproject.toml hatch.toml
[tool.hatch.version]\npath = \"src/hatch_demo/__about__.py\"\n
[version]\npath = \"src/hatch_demo/__about__.py\"\n

The default pattern looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v.

If this doesn't reflect how you store the version, you can define a different regular expression using the pattern option:

pyproject.toml hatch.toml
[tool.hatch.version]\npath = \"pkg/__init__.py\"\npattern = \"BUILD = 'b(?P<version>[^']+)'\"\n
[version]\npath = \"pkg/__init__.py\"\npattern = \"BUILD = 'b(?P<version>[^']+)'\"\n

The pattern must have a named group called version that represents the version.

"},{"location":"version/#display","title":"Display","text":"

Invoking the version command without any arguments will display the current version of the project:

$ hatch version\n0.0.1\n
"},{"location":"version/#updating","title":"Updating","text":"

You can update the version like so:

$ hatch version \"0.1.0\"\nOld: 0.0.1\nNew: 0.1.0\n

The scheme option determines the scheme to use for parsing both the existing and new versions. The standard scheme is used by default, which is based on PEP 440.

Rather than setting the version explicitly, you can select the name of a segment used to increment the version:

$ hatch version minor\nOld: 0.1.0\nNew: 0.2.0\n

You can chain multiple segment updates with a comma. For example, if you wanted to release a preview of your project's first major version, you could do:

$ hatch version major,rc\nOld: 0.2.0\nNew: 1.0.0rc0\n

When you want to release the final version, you would do:

$ hatch version release\nOld: 1.0.0rc0\nNew: 1.0.0\n
"},{"location":"version/#supported-segments","title":"Supported segments","text":"

Here are the supported segments and how they would influence an existing version of 1.0.0:

Segments New version release 1.0.0 major 2.0.0 minor 1.1.0 micropatchfix 1.0.1 aalpha 1.0.0a0 bbeta 1.0.0b0 crcprepreview 1.0.0rc0 rrevpost 1.0.0.post0 dev 1.0.0.dev0"},{"location":"blog/","title":"Blog","text":""},{"location":"blog/2022/10/08/hatch-v160/","title":"Hatch v1.6.0","text":"

Hatch v1.6.0 brings improvements to build environments, better handling of dynamic metadata, and support for tools like Visual Studio Code.

"},{"location":"blog/2022/10/08/hatch-v160/#build-environments","title":"Build environments","text":"

Originally, the environment interface method for providing builder sub-environments was intended to be used in conjunction with some cleanup logic in order to provide a fresh setup every time. However, this is unnecessary in practice because build dependencies rarely change.

Without caching, repeat build environment use is slow which affects the following scenarios:

Now a new environment interface method build_environment_exists is used by Hatch to determine whether or not it has already been created, for implementations that have a caching mechanism.

The virtual environment type now uses this method to cache build environments.

"},{"location":"blog/2022/10/08/hatch-v160/#project-metadata","title":"Project metadata","text":"

Dynamically defined metadata is now supported everywhere, thanks to the new caching of virtual build environments.

A project metadata command is introduced that displays the fully resolved metadata. The output format is JSON unless a field is specified as an argument.

For example, if you checkout a project that is built by Hatch, like FastAPI, and run:

hatch project metadata readme\n

only the readme text will be displayed. If the content is in Markdown, then Rich will render it directly in your terminal:

"},{"location":"blog/2022/10/08/hatch-v160/#virtual-environment-location","title":"Virtual environment location","text":"

The virtual environment type now uses a flat layout for storage in the configured virtual environment directory if the directory resides somewhere within the project root or if it is set to a .virtualenvs directory within the user's home directory.

For example, if you define the following Hatch configuration:

config.toml
[dirs.env]\nvirtual = \".hatch\"\n

and the following matrix:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\npython = [\"3.7\", \"3.8\", \"3.9\", \"3.10\", \"3.11\"]\n
[[envs.test.matrix]]\npython = [\"3.7\", \"3.8\", \"3.9\", \"3.10\", \"3.11\"]\n

then locating environments with the following command:

hatch env find test\n

will show that the general directory structure is:

.hatch\n\u251c\u2500\u2500 test.py3.7\n\u251c\u2500\u2500 test.py3.8\n\u251c\u2500\u2500 test.py3.9\n\u251c\u2500\u2500 test.py3.10\n\u2514\u2500\u2500 test.py3.11\n

This flat structure is required for detection of virtual environments by tools like Visual Studio Code and PyCharm.

Additionally, the virtual environment type now supports a path option to specify an explicit path that all inherited environments will share, such as the common .venv.

"},{"location":"blog/2022/10/08/hatch-v160/#migration-script-improvements","title":"Migration script improvements","text":"

The script used to migrate existing projects from setuptools has been improved to handle more edge cases that were encountered in the wild and now no longer modifies the formatting of existing pyproject.toml configuration.

"},{"location":"blog/2022/10/08/hatch-v160/#hatchling","title":"Hatchling","text":"

Hatch now depends on Hatchling v1.11.0, which was also just released.

"},{"location":"blog/2022/10/08/hatch-v160/#environment-version-source","title":"Environment version source","text":"

A new env version source is available that allows for the project version to be defined by an environment variable.

"},{"location":"blog/2022/10/08/hatch-v160/#relaxed-version-bumping","title":"Relaxed version bumping","text":"

The standard version scheme now supports a validate-bump option that when set to false will forego the check when updating the version that the desired version is higher than the current version.

This use case comes from Project Jupyter:

A common pattern we use in Jupyter is to bump to a .dev0 minor version bump after making a release. If we have a bug fix that needs to go out in the interim, we'd rather not be forced to create a branch every time.

"},{"location":"cli/about/","title":"About","text":""},{"location":"cli/about/#verbosity","title":"Verbosity","text":"

The amount of displayed output is controlled solely by the -v/--verbose (environment variable HATCH_VERBOSE) and -q/--quiet (environment variable HATCH_QUIET) root options.

The levels are documented here.

"},{"location":"cli/about/#project-awareness","title":"Project awareness","text":"

No matter the mode, Hatch will always change to the project's root directory for entering or running commands in environments.

"},{"location":"cli/about/#tab-completion","title":"Tab completion","text":"

Completion is achieved by saving a script and then executing it as a part of your shell's startup sequence.

Afterward, you'll need to start a new shell in order for the changes to take effect.

BashZ shellfish

Save the script somewhere:

_HATCH_COMPLETE=bash_source hatch > ~/.hatch-complete.bash\n

Source the file in ~/.bashrc (or ~/.bash_profile if on macOS):

. ~/.hatch-complete.bash\n

Save the script somewhere:

_HATCH_COMPLETE=zsh_source hatch > ~/.hatch-complete.zsh\n

Source the file in ~/.zshrc:

. ~/.hatch-complete.zsh\n

Save the script in ~/.config/fish/completions:

_HATCH_COMPLETE=fish_source hatch > ~/.config/fish/completions/hatch.fish\n
"},{"location":"cli/reference/","title":"hatch","text":"

Usage:

hatch [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --env, -e text The name of the environment to use [env var: HATCH_ENV] default --project, -p text The name of the project to work on [env var: HATCH_PROJECT] None --verbose, -v integer range (0 and above) Increase verbosity (can be used additively) [env var: HATCH_VERBOSE] 0 --quiet, -q integer range (0 and above) Decrease verbosity (can be used additively) [env var: HATCH_QUIET] 0 --color / --no-color boolean Whether or not to display colored output (default is auto-detection) [env vars: FORCE_COLOR/NO_COLOR] None --interactive / --no-interactive boolean Whether or not to allow features like prompts and progress bars (default is auto-detection) [env var: HATCH_INTERACTIVE] None --data-dir text The path to a custom directory used to persist data [env var: HATCH_DATA_DIR] None --cache-dir text The path to a custom directory used to cache data [env var: HATCH_CACHE_DIR] None --config text The path to a custom config file to use [env var: HATCH_CONFIG] None --version boolean Show the version and exit. False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-build","title":"hatch build","text":"

Build a project.

Usage:

hatch build [OPTIONS] [LOCATION]\n

Options:

Name Type Description Default --target, -t text The target to build, overriding project defaults. This may be selected multiple times e.g. -t sdist -t wheel None --hooks-only boolean Whether or not to only execute build hooks [env var: HATCH_BUILD_HOOKS_ONLY] False --no-hooks boolean Whether or not to disable build hooks [env var: HATCH_BUILD_NO_HOOKS] False --ext boolean Whether or not to only execute build hooks for distributing binary Python packages, such as compiling extensions. Equivalent to --hooks-only -t wheel False --clean, -c boolean Whether or not existing artifacts should first be removed [env var: HATCH_BUILD_CLEAN] False --clean-hooks-after boolean Whether or not build hook artifacts should be removed after each build [env var: HATCH_BUILD_CLEAN_HOOKS_AFTER] False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-clean","title":"hatch clean","text":"

Remove build artifacts.

Usage:

hatch clean [OPTIONS] [LOCATION]\n

Options:

Name Type Description Default --target, -t text The target with which to remove artifacts, overriding project defaults. This may be selected multiple times e.g. -t sdist -t wheel None --hooks-only boolean Whether or not to only remove artifacts from build hooks [env var: HATCH_BUILD_HOOKS_ONLY] False --no-hooks boolean Whether or not to ignore artifacts from build hooks [env var: HATCH_BUILD_NO_HOOKS] False --ext boolean Whether or not to only remove artifacts from build hooks for distributing binary Python packages, such as compiled extensions. Equivalent to --hooks-only -t wheel False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config","title":"hatch config","text":"

Manage the config file

Usage:

hatch config [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-explore","title":"hatch config explore","text":"

Open the config location in your file manager.

Usage:

hatch config explore [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-find","title":"hatch config find","text":"

Show the location of the config file.

Usage:

hatch config find [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-restore","title":"hatch config restore","text":"

Restore the config file to default settings.

Usage:

hatch config restore [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-set","title":"hatch config set","text":"

Assign values to config file entries. If the value is omitted, you will be prompted, with the input hidden if it is sensitive.

Usage:

hatch config set [OPTIONS] KEY [VALUE]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-show","title":"hatch config show","text":"

Show the contents of the config file.

Usage:

hatch config show [OPTIONS]\n

Options:

Name Type Description Default --all, -a boolean Do not scrub secret fields False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-config-update","title":"hatch config update","text":"

Update the config file with any new fields.

Usage:

hatch config update [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep","title":"hatch dep","text":"

Manage environment dependencies

Usage:

hatch dep [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep-hash","title":"hatch dep hash","text":"

Output a hash of the currently defined dependencies.

Usage:

hatch dep hash [OPTIONS]\n

Options:

Name Type Description Default --project-only, -p boolean Whether or not to exclude environment dependencies False --env-only, -e boolean Whether or not to exclude project dependencies False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep-show","title":"hatch dep show","text":"

Display dependencies in various formats

Usage:

hatch dep show [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep-show-requirements","title":"hatch dep show requirements","text":"

Enumerate dependencies as a list of requirements.

Usage:

hatch dep show requirements [OPTIONS]\n

Options:

Name Type Description Default --project-only, -p boolean Whether or not to exclude environment dependencies False --env-only, -e boolean Whether or not to exclude project dependencies False --feature, -f text Whether or not to only show the dependencies of the specified features None --all boolean Whether or not to include the dependencies of all features False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-dep-show-table","title":"hatch dep show table","text":"

Enumerate dependencies in a tabular format.

Usage:

hatch dep show table [OPTIONS]\n

Options:

Name Type Description Default --project-only, -p boolean Whether or not to exclude environment dependencies False --env-only, -e boolean Whether or not to exclude project dependencies False --lines, -l boolean Whether or not to show lines between table rows False --ascii boolean Whether or not to only use ASCII characters False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env","title":"hatch env","text":"

Manage project environments

Usage:

hatch env [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-create","title":"hatch env create","text":"

Create environments.

Usage:

hatch env create [OPTIONS] [ENV_NAME]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-find","title":"hatch env find","text":"

Locate environments.

Usage:

hatch env find [OPTIONS] [ENV_NAME]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-prune","title":"hatch env prune","text":"

Remove all environments.

Usage:

hatch env prune [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-remove","title":"hatch env remove","text":"

Remove environments.

Usage:

hatch env remove [OPTIONS] [ENV_NAME]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-run","title":"hatch env run","text":"

Run commands within project environments.

The -e/--env option overrides the equivalent root option and the HATCH_ENV environment variable.

If environments provide matrices, then you may use the -i/--include and -x/--exclude options to select or exclude certain variables, optionally followed by specific comma-separated values. For example, if you have the following configuration:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\npython = [\"3.9\", \"3.10\"]\nversion = [\"42\", \"3.14\", \"9000\"]\n
[[envs.test.matrix]]\npython = [\"3.9\", \"3.10\"]\nversion = [\"42\", \"3.14\", \"9000\"]\n

then running:

hatch env run -i py=3.10 -x version=9000 test:pytest\n

would execute pytest in the environments test.py3.10-42 and test.py3.10-3.14. Note that py may be used as an alias for python.

Usage:

hatch env run [OPTIONS] ARGS...\n

Options:

Name Type Description Default --env, -e text The environments to target None --include, -i text The matrix variables to include None --exclude, -x text The matrix variables to exclude None --filter, -f text The JSON data used to select environments None --force-continue boolean Run every command and if there were any errors exit with the first code False --ignore-compat boolean Ignore incompatibility when selecting specific environments False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-env-show","title":"hatch env show","text":"

Show the available environments.

Usage:

hatch env show [OPTIONS] [ENVS]...\n

Options:

Name Type Description Default --ascii boolean Whether or not to only use ASCII characters False --json boolean Whether or not to output in JSON format False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-new","title":"hatch new","text":"

Create or initialize a project.

Usage:

hatch new [OPTIONS] [NAME] [LOCATION]\n

Options:

Name Type Description Default --interactive, -i boolean Interactively choose details about the project False --cli boolean Give the project a command line interface False --init boolean Initialize an existing project False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-project","title":"hatch project","text":"

View project information

Usage:

hatch project [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-project-metadata","title":"hatch project metadata","text":"

Display project metadata.

If you want to view the raw readme file without rendering, you can use a JSON parser like jq:

hatch project metadata | jq -r .readme\n

Usage:

hatch project metadata [OPTIONS] [FIELD]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-publish","title":"hatch publish","text":"

Publish build artifacts.

Usage:

hatch publish [OPTIONS] [ARTIFACTS]...\n

Options:

Name Type Description Default --repo, -r text The repository with which to publish artifacts [env var: HATCH_INDEX_REPO] None --user, -u text The user with which to authenticate [env var: HATCH_INDEX_USER] None --auth, -a text The credentials to use for authentication [env var: HATCH_INDEX_AUTH] None --ca-cert text The path to a CA bundle [env var: HATCH_INDEX_CA_CERT] None --client-cert text The path to a client certificate, optionally containing the private key [env var: HATCH_INDEX_CLIENT_CERT] None --client-key text The path to the client certificate's private key [env var: HATCH_INDEX_CLIENT_KEY] None --no-prompt, -n boolean Disable prompts, such as for missing required fields False --initialize-auth boolean Save first-time authentication information even if nothing was published False --publisher, -p text The publisher plugin to use (default is index) [env var: HATCH_PUBLISHER] index --option, -o text Options to pass to the publisher plugin. This may be selected multiple times e.g. -o foo=bar -o baz=23 [env var: HATCH_PUBLISHER_OPTIONS] None --yes, -y boolean Confirm without prompting when the plugin is disabled False --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python","title":"hatch python","text":"

Manage Python installations

Usage:

hatch python [OPTIONS] COMMAND [ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python-install","title":"hatch python install","text":"

Install Python distributions.

You may select all to install all compatible distributions:

hatch python install all\n

Usage:

hatch python install [OPTIONS] NAMES...\n

Options:

Name Type Description Default --private boolean Do not add distributions to the user PATH False --update, -u boolean Update existing installations False --dir, -d text The directory in which to install distributions, overriding configuration None --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python-remove","title":"hatch python remove","text":"

Remove Python distributions.

You may select all to remove all installed distributions:

hatch python remove all\n

Usage:

hatch python remove [OPTIONS] NAMES...\n

Options:

Name Type Description Default --dir, -d text The directory in which distributions reside None --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python-show","title":"hatch python show","text":"

Show the available Python distributions.

Usage:

hatch python show [OPTIONS]\n

Options:

Name Type Description Default --ascii boolean Whether or not to only use ASCII characters False --dir, -d text The directory in which distributions reside None --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-python-update","title":"hatch python update","text":"

Update Python distributions.

You may select all to update all installed distributions:

hatch python update all\n

Usage:

hatch python update [OPTIONS] NAMES...\n

Options:

Name Type Description Default --dir, -d text The directory in which distributions reside None --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-run","title":"hatch run","text":"

Run commands within project environments. This is a convenience wrapper around the env run command.

If the first argument contains a colon, then the preceding component will be interpreted as the name of the environment to target, overriding the -e/--env root option and the HATCH_ENV environment variable.

If the environment provides matrices, then you may also provide leading arguments starting with a + or - to select or exclude certain variables, optionally followed by specific comma-separated values. For example, if you have the following configuration:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\npython = [\"3.9\", \"3.10\"]\nversion = [\"42\", \"3.14\", \"9000\"]\n
[[envs.test.matrix]]\npython = [\"3.9\", \"3.10\"]\nversion = [\"42\", \"3.14\", \"9000\"]\n

then running:

hatch run +py=3.10 -version=9000 test:pytest\n

would execute pytest in the environments test.py3.10-42 and test.py3.10-3.14. Note that py may be used as an alias for python.

Usage:

hatch run [OPTIONS] [ENV:]ARGS...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-shell","title":"hatch shell","text":"

Enter a shell within a project's environment.

Usage:

hatch shell [OPTIONS] [SHELL_NAME] [SHELL_PATH] [SHELL_ARGS]...\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-status","title":"hatch status","text":"

Show information about the current environment.

Usage:

hatch status [OPTIONS]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"cli/reference/#hatch-version","title":"hatch version","text":"

View or set a project's version.

Usage:

hatch version [OPTIONS] [DESIRED_VERSION]\n

Options:

Name Type Description Default --help boolean Show this message and exit. False"},{"location":"community/highlights/","title":"Highlights","text":""},{"location":"community/users/","title":"Users","text":"

The following is not intended to be a complete enumeration. Be sure to view the development version of this page for an up-to-date listing.

"},{"location":"community/users/#projects","title":"Projects","text":"

argon2-cffi | Black | Colorama | Django Debug Toolbar | Django Wiki | FastAPI | Gradio | HTTPX | iCalendar for Humans | LinkChecker | Material for MkDocs | MkDocs | Nox | pipx | platformdirs | Pydantic | PyHamcrest | PyMdown Extensions | Python JSON Schema | SALib | Spack | Starlette | structlog | tox | Twisted | urllib3 | Uvicorn | Voil\u00e0

"},{"location":"community/users/#industry","title":"Industry","text":""},{"location":"community/users/#organizations","title":"Organizations","text":""},{"location":"community/users/#government","title":"Government","text":""},{"location":"community/users/#academia","title":"Academia","text":""},{"location":"community/users/#research","title":"Research","text":""},{"location":"community/users/#security","title":"Security","text":""},{"location":"community/users/#crypto","title":"Crypto","text":""},{"location":"config/build/","title":"Build configuration","text":"

All build configuration is defined in the tool.hatch.build table.

Build targets are defined as sections within tool.hatch.build.targets:

pyproject.toml hatch.toml
[tool.hatch.build.targets.<TARGET_NAME>]\n
[build.targets.<TARGET_NAME>]\n

For each build target you may override any of the defaults set in the top-level tool.hatch.build table.

"},{"location":"config/build/#build-system","title":"Build system","text":"

To be compatible with the broader Python packaging ecosystem, you must define the build system as follows:

pyproject.toml
[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n

The version of hatchling defined here will be used to build all targets.

Hatchling is a PEP 517/PEP 660 compatible build backend and is a dependency of Hatch itself.

"},{"location":"config/build/#file-selection","title":"File selection","text":""},{"location":"config/build/#vcs","title":"VCS","text":"

By default, Hatch will respect the first .gitignore or .hgignore file found in your project's root directory or parent directories. Set ignore-vcs to true to disable this behavior:

pyproject.toml hatch.toml
[tool.hatch.build]\nignore-vcs = true\n
[build]\nignore-vcs = true\n

Note

For .hgignore files only glob syntax is supported.

"},{"location":"config/build/#patterns","title":"Patterns","text":"

You can set the include and exclude options to select exactly which files will be shipped in each build, with exclude taking precedence. Every entry represents a Git-style glob pattern.

For example, the following configuration:

pyproject.toml hatch.toml
[tool.hatch.build]\ninclude = [\n\"pkg/*.py\",\n\"/tests\",\n]\nexclude = [\n\"*.json\",\n\"pkg/_compat.py\",\n]\n
[build]\ninclude = [\n\"pkg/*.py\",\n\"/tests\",\n]\nexclude = [\n\"*.json\",\n\"pkg/_compat.py\",\n]\n

will exclude every file with a .json extension, and will include everything under a tests directory located at the root and every file with a .py extension that is directly under a pkg directory located at the root except for _compat.py.

"},{"location":"config/build/#artifacts","title":"Artifacts","text":"

If you want to include files that are ignored by your VCS, such as those that might be created by build hooks, you can use the artifacts option. This option is semantically equivalent to include.

Note that artifacts are not affected by the exclude option. Artifacts can be excluded by using more explicit paths or by using the ! negation operator. When using the ! operator, the negated pattern(s) must come after the more generic ones.

pyproject.toml hatch.toml
[tool.hatch.build]\nartifacts = [\n\"*.so\",\n\"*.dll\",\n\"!/foo/*.so\",\n]\n
[build]\nartifacts = [\n\"*.so\",\n\"*.dll\",\n\"!/foo/*.so\",\n]\n
"},{"location":"config/build/#explicit-selection","title":"Explicit selection","text":""},{"location":"config/build/#generic","title":"Generic","text":"

You can use the only-include option to prevent directory traversal starting at the project root and only select specific relative paths to directories or files. Using this option ignores any defined include patterns.

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel]\nonly-include = [\"pkg\", \"tests/unit\"]\n
[build.targets.wheel]\nonly-include = [\"pkg\", \"tests/unit\"]\n
"},{"location":"config/build/#packages","title":"Packages","text":"

The packages option is semantically equivalent to only-include (which takes precedence) except that the shipped path will be collapsed to only include the final component.

So for example, if you want to ship a package foo that is stored in a directory src you would do:

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel]\npackages = [\"src/foo\"]\n
[build.targets.wheel]\npackages = [\"src/foo\"]\n
"},{"location":"config/build/#forced-inclusion","title":"Forced inclusion","text":"

The force-include option allows you to select specific files or directories from anywhere on the file system that should be included and map them to the desired relative distribution path.

For example, if there was a directory alongside the project root named artifacts containing a file named lib.so and a file named lib.h in your home directory, you could ship both files in a pkg directory with the following configuration:

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel.force-include]\n\"../artifacts\" = \"pkg\"\n\"~/lib.h\" = \"pkg/lib.h\"\n
[build.targets.wheel.force-include]\n\"../artifacts\" = \"pkg\"\n\"~/lib.h\" = \"pkg/lib.h\"\n

Note

Warning

Files included using this option will overwrite any file path that was already included by other file selection options.

"},{"location":"config/build/#default-file-selection","title":"Default file selection","text":"

If no file selection options are provided, then what gets included is determined by each build target.

"},{"location":"config/build/#excluding-files-outside-packages","title":"Excluding files outside packages","text":"

If you want to exclude non-artifact files that do not reside within a Python package, set only-packages to true:

pyproject.toml hatch.toml
[tool.hatch.build]\nonly-packages = true\n
[build]\nonly-packages = true\n
"},{"location":"config/build/#rewriting-paths","title":"Rewriting paths","text":"

You can rewrite relative paths to directories with the sources option. For example, the following configuration:

pyproject.toml hatch.toml
[tool.hatch.build.sources]\n\"src/foo\" = \"bar\"\n
[build.sources]\n\"src/foo\" = \"bar\"\n

would distribute the file src/foo/file.ext as bar/file.ext.

If you want to remove path prefixes entirely, rather than setting each to an empty string, you can define sources as an array:

pyproject.toml hatch.toml
[tool.hatch.build]\nsources = [\"src\"]\n
[build]\nsources = [\"src\"]\n

The packages option itself relies on sources. Defining packages = [\"src/foo\"] for the wheel target is equivalent to the following:

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel]\nonly-include = [\"src/foo\"]\nsources = [\"src\"]\n
[build.targets.wheel]\nonly-include = [\"src/foo\"]\nsources = [\"src\"]\n
"},{"location":"config/build/#performance","title":"Performance","text":"

All encountered directories are traversed by default. To skip non-artifact directories that are excluded, set skip-excluded-dirs to true:

pyproject.toml hatch.toml
[tool.hatch.build]\nskip-excluded-dirs = true\n
[build]\nskip-excluded-dirs = true\n

Warning

This may result in not shipping desired files. For example, if you want to include the file a/b/c.txt but your VCS ignores a/b, the file c.txt will not be seen because its parent directory will not be entered. In such cases you can use the force-include option.

"},{"location":"config/build/#reproducible-builds","title":"Reproducible builds","text":"

By default, build targets will build in a reproducible manner provided that they support that behavior. To disable this, set reproducible to false:

pyproject.toml hatch.toml
[tool.hatch.build]\nreproducible = false\n
[build]\nreproducible = false\n

When enabled, the SOURCE_DATE_EPOCH environment variable will be used for all build timestamps. If not set, then Hatch will use an unchanging default value.

"},{"location":"config/build/#output-directory","title":"Output directory","text":"

When the output directory is not provided to the build command, the dist directory will be used by default. You can change the default to a different directory using a relative or absolute path like so:

pyproject.toml hatch.toml
[tool.hatch.build]\ndirectory = \"<PATH>\"\n
[build]\ndirectory = \"<PATH>\"\n
"},{"location":"config/build/#dev-mode","title":"Dev mode","text":"

By default for dev mode environment installations or editable installs, the wheel target will determine which directories should be added to Python's search path based on the selected files.

If you want to override this detection or perhaps instruct other build targets as well, you can use the dev-mode-dirs option:

pyproject.toml hatch.toml
[tool.hatch.build]\ndev-mode-dirs = [\".\"]\n
[build]\ndev-mode-dirs = [\".\"]\n

If you don't want to add entire directories to Python's search path, you can enable a more targeted mechanism with the mutually exclusive dev-mode-exact option:

pyproject.toml hatch.toml
[tool.hatch.build]\ndev-mode-exact = true\n
[build]\ndev-mode-exact = true\n

Warning

The dev-mode-exact mechanism is not supported by static analysis tools & IDEs, therefore functionality such as autocompletion is unlikely to work.

"},{"location":"config/build/#build-targets","title":"Build targets","text":"

A build target can be provided by any builder plugin. There are three built-in build targets: wheel, sdist, and custom.

"},{"location":"config/build/#dependencies","title":"Dependencies","text":"

You can specify additional dependencies that will be installed in each build environment, such as for third party builders:

pyproject.toml hatch.toml
[tool.hatch.build.targets.your-target-name]\ndependencies = [\n\"your-builder-plugin\"\n]\n
[build.targets.your-target-name]\ndependencies = [\n\"your-builder-plugin\"\n]\n

You can also declare dependence on the project's runtime dependencies with the require-runtime-dependencies option:

pyproject.toml hatch.toml
[tool.hatch.build.targets.your-target-name]\nrequire-runtime-dependencies = true\n
[build.targets.your-target-name]\nrequire-runtime-dependencies = true\n

Additionally, you may declare dependence on specific runtime features of the project with the require-runtime-features option:

pyproject.toml hatch.toml
[tool.hatch.build.targets.your-target-name]\nrequire-runtime-features = [\n\"feature1\",\n\"feature2\",\n]\n
[build.targets.your-target-name]\nrequire-runtime-features = [\n\"feature1\",\n\"feature2\",\n]\n
"},{"location":"config/build/#versions","title":"Versions","text":"

If a build target supports multiple build strategies or if there are major changes over time, you can specify exactly which versions you want to build using the versions option:

pyproject.toml hatch.toml
[tool.hatch.build.targets.<TARGET_NAME>]\nversions = [\n\"v1\",\n\"beta-feature\",\n]\n
[build.targets.<TARGET_NAME>]\nversions = [\n\"v1\",\n\"beta-feature\",\n]\n

See the wheel target for a real world example.

"},{"location":"config/build/#build-hooks","title":"Build hooks","text":"

A build hook defines code that will be executed at various stages of the build process and can be provided by any build hook plugin. There is one built-in build hook: custom.

Build hooks can be applied either globally:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.<HOOK_NAME>]\n
[build.hooks.<HOOK_NAME>]\n

or to specific build targets:

pyproject.toml hatch.toml
[tool.hatch.build.targets.<TARGET_NAME>.hooks.<HOOK_NAME>]\n
[build.targets.<TARGET_NAME>.hooks.<HOOK_NAME>]\n
"},{"location":"config/build/#dependencies_1","title":"Dependencies","text":"

You can specify additional dependencies that will be installed in each build environment, such as for third party build hooks:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.your-hook-name]\ndependencies = [\n\"your-build-hook-plugin\"\n]\n
[build.hooks.your-hook-name]\ndependencies = [\n\"your-build-hook-plugin\"\n]\n

You can also declare dependence on the project's runtime dependencies with the require-runtime-dependencies option:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.your-hook-name]\nrequire-runtime-dependencies = true\n
[build.hooks.your-hook-name]\nrequire-runtime-dependencies = true\n

Additionally, you may declare dependence on specific runtime features of the project with the require-runtime-features option:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.your-hook-name]\nrequire-runtime-features = [\n\"feature1\",\n\"feature2\",\n]\n
[build.hooks.your-hook-name]\nrequire-runtime-features = [\n\"feature1\",\n\"feature2\",\n]\n
"},{"location":"config/build/#order-of-execution","title":"Order of execution","text":"

For each build target, build hooks execute in the order in which they are defined, starting with global hooks.

As an example, for the following configuration:

pyproject.toml hatch.toml
[tool.hatch.build.targets.foo.hooks.hook2]\n\n[tool.hatch.build.hooks.hook3]\n[tool.hatch.build.hooks.hook1]\n
[build.targets.foo.hooks.hook2]\n\n[build.hooks.hook3]\n[build.hooks.hook1]\n

When target foo is built, build hook hook3 will be executed first, followed by hook1, and then finally hook2.

"},{"location":"config/build/#conditional-execution","title":"Conditional execution","text":"

If you want to disable a build hook by default and control its use by environment variables, you can do so by setting the enable-by-default option to false:

pyproject.toml hatch.toml
[tool.hatch.build.hooks.<HOOK_NAME>]\nenable-by-default = false\n
[build.hooks.<HOOK_NAME>]\nenable-by-default = false\n
"},{"location":"config/build/#environment-variables","title":"Environment variables","text":"Variable Default Description HATCH_BUILD_CLEAN false Whether or not existing artifacts should first be removed HATCH_BUILD_CLEAN_HOOKS_AFTER false Whether or not build hook artifacts should be removed after each build HATCH_BUILD_HOOKS_ONLY false Whether or not to only execute build hooks HATCH_BUILD_NO_HOOKS false Whether or not to disable all build hooks; this takes precedence over other options HATCH_BUILD_HOOKS_ENABLE false Whether or not to enable all build hooks HATCH_BUILD_HOOK_ENABLE_<HOOK_NAME> false Whether or not to enable the build hook named <HOOK_NAME> HATCH_BUILD_LOCATION dist The location with which to build the targets; only used by the build command"},{"location":"config/context/","title":"Context formatting","text":"

You can populate configuration with the values of certain supported fields using the syntax of Python's format strings. Each field interprets the modifier part after the colon differently, if at all.

"},{"location":"config/context/#global-fields","title":"Global fields","text":"

Any configuration that declares support for context formatting will always support these fields.

"},{"location":"config/context/#paths","title":"Paths","text":"Field Description root The root project directory home The user's home directory

All paths support the following modifiers:

Modifier Description uri The normalized absolute URI path prefixed by file: real The path with all symbolic links resolved"},{"location":"config/context/#system-separators","title":"System separators","text":"Field Description / \\ on Windows, / otherwise ; ; on Windows, : otherwise"},{"location":"config/context/#environment-variables","title":"Environment variables","text":"

The env field and its modifier allow you to select the value of an environment variable. If the environment variable is not set, you must specify a default value as an additional modifier e.g. {env:PATH:DEFAULT}.

"},{"location":"config/context/#field-nesting","title":"Field nesting","text":"

You can insert fields within others. For example, if you wanted a script that displays the value of the environment variable FOO, with a fallback to the environment variable BAR, with its own fallback to the user's home directory, you could do the following:

pyproject.toml hatch.toml
[tool.hatch.envs.test.scripts]\ndisplay = \"echo {env:FOO:{env:BAR:{home}}}\"\n
[envs.test.scripts]\ndisplay = \"echo {env:FOO:{env:BAR:{home}}}\"\n
"},{"location":"config/dependency/","title":"Dependency configuration","text":"

Project dependencies are defined with PEP 508 strings using optional PEP 440 version specifiers.

"},{"location":"config/dependency/#version-specifiers","title":"Version specifiers","text":"

A version specifier consists of a series of version clauses, separated by commas. For example:

pyproject.toml
[project]\n...\ndependencies = [\n\"cryptography\",\n\"click>=7, <9, != 8.0.0\",\n\"python-dateutil==2.8.*\",\n\"numpy~=1.21.4\",\n]\n

The comma is equivalent to a logical AND operator: a candidate version must match all given version clauses in order to match the specifier as a whole.

"},{"location":"config/dependency/#operators","title":"Operators","text":"Operators Function ~= Compatible release == Version matching != Version exclusion <=, >= Inclusive ordered comparison <, > Exclusive ordered comparison === Arbitrary equality"},{"location":"config/dependency/#version-matching","title":"Version matching","text":"

A version matching clause includes the version matching operator == and a version identifier.

By default, the version matching operator is based on a strict equality comparison: the specified version must be exactly the same as the requested version.

Clause Allowed versions ==1 1.0.0 ==1.2 1.2.0

Prefix matching may be requested instead of strict comparison, by appending a trailing .* to the version identifier in the version matching clause. This means that additional trailing segments will be ignored when determining whether or not a version identifier matches the clause.

Clause Allowed versions ==1.* >=1.0.0, <2.0.0 ==1.2.* >=1.2.0, <1.3.0"},{"location":"config/dependency/#compatible-release","title":"Compatible release","text":"

A compatible release clause consists of the compatible release operator ~= and a version identifier. It matches any candidate version that is expected to be compatible with the specified version.

For a given release identifier V.N, the compatible release clause is approximately equivalent to the following pair of comparison clauses:

>= V.N, == V.*\n

This operator cannot be used with a single segment version number such as ~=1.

Clause Allowed versions ~=1.2 >=1.2.0, <2.0.0 ~=1.2.3 >=1.2.3, <1.3.0"},{"location":"config/dependency/#version-exclusion","title":"Version exclusion","text":"

A version exclusion clause includes the version exclusion operator != and a version identifier.

The allowed version identifiers and comparison semantics are the same as those of the Version matching operator, except that the sense of any match is inverted.

"},{"location":"config/dependency/#ordered-comparison","title":"Ordered comparison","text":"

Inclusive comparisons allow for the version identifier part of clauses whereas exclusive comparisons do not. For example, >=1.2 allows for version 1.2.0 while >1.2 does not.

Unlike the inclusive ordered comparisons <= and >=, the exclusive ordered comparisons < and > specifically exclude pre-releases, post-releases, and local versions of the specified version.

"},{"location":"config/dependency/#arbitrary-equality","title":"Arbitrary equality","text":"

Though heavily discouraged, arbitrary equality comparisons allow for simple string matching without any version semantics, for example ===foobar.

"},{"location":"config/dependency/#environment-markers","title":"Environment markers","text":"

Environment markers allow for dependencies to only be installed when certain conditions are met.

For example, if you need to install the latest version of cryptography that is available for a given Python major version you could define the following:

cryptography==3.3.2; python_version < \"3\"\ncryptography>=35.0; python_version > \"3\"\n

Alternatively, if you only need it on Python 3 when running on Windows you could do:

cryptography; python_version ~= \"3.0\" and platform_system == \"Windows\"\n

The available environment markers are as follows.

Marker Python equivalent Examples os_name import osos.name sys_platform import syssys.platform platform_machine import platformplatform.machine() platform_python_implementation import platformplatform.python_implementation() platform_release import platformplatform.release() platform_system import platformplatform.system() platform_version import platformplatform.version() python_version import platform'.'.join(platform.python_version_tuple()[:2]) python_full_version import platformplatform.python_version() implementation_name import syssys.implementation.name implementation_version See here "},{"location":"config/dependency/#features","title":"Features","text":"

You can select groups of optional dependencies to install using the extras syntax. For example, if a dependency named foo defined the following:

pyproject.toml
[project.optional-dependencies]\ncrypto = [\n\"PyJWT\",\n\"cryptography\",\n]\nfastjson = [\n\"orjson\",\n]\ncli = [\n\"prompt-toolkit\",\n\"colorama; platform_system == 'Windows'\",\n]\n

You can select the cli and crypto features like so:

foo[cli,crypto]==1.*\n

Note that the features come immediately after the package name, before any version specifiers.

"},{"location":"config/dependency/#self-referential","title":"Self-referential","text":"

Feature groups can self-referentially extend others. For example, for a project called awesome-project, the dev feature group in the following pyproject.toml file would select everything in the crypto feature group, plus black:

pyproject.toml
[project]\nname = \"awesome-project\"\n\n[project.optional-dependencies]\ncrypto = [\n\"PyJWT\",\n\"cryptography\",\n]\ndev = [\n\"awesome-project[crypto]\",\n\"black\",\n]\n
"},{"location":"config/dependency/#direct-references","title":"Direct references","text":"

Instead of using normal version specifiers and fetching packages from an index like PyPI, you can define exact sources using direct references with an explicit URI.

Direct references are usually not meant to be used for dependencies of a published project but rather are used for defining dependencies for an environment.

All direct reference types are prefixed by the package name like:

<NAME> @ <REFERENCE>\n
"},{"location":"config/dependency/#version-control-systems","title":"Version control systems","text":"

Various version control systems (VCS) are supported as long as the associated executable is available along your PATH.

VCS direct references are defined using one of the following formats:

<NAME> @ <SCHEME>://<PATH>\n<NAME> @ <SCHEME>://<PATH>@<REVISION>\n

You may also append a #subdirectory=<PATH> component for specifying the relative path to the Python package when it is not located at the root e.g. #subdirectory=lib/foo.

For more information, refer to this.

"},{"location":"config/dependency/#supported-vcs","title":"Supported VCS","text":"GitMercurialSubversionBazaar Executable Schemes Revisions Example git proj @ git+https://github.com/org/proj.git@v1 Executable Schemes Revisions Example hg proj @ hg+file:///path/to/proj@v1 Executable Schemes Revisions Example svn proj @ svn+file:///path/to/proj Executable Schemes Revisions Example bzr proj @ bzr+lp:proj@v1"},{"location":"config/dependency/#local","title":"Local","text":"

You can install local packages with the file scheme in the following format:

<NAME> @ file://<HOST>/<PATH>\n

The <HOST> is only used on Windows systems, where it can refer to a network share. If omitted it is assumed to be localhost and the third slash must still be present.

The <PATH> can refer to a source archive, a wheel, or a directory containing a Python package.

Type Unix Windows Source archive proj @ file:///path/to/pkg.tar.gz proj @ file:///c:/path/to/pkg.tar.gz Wheel proj @ file:///path/to/pkg.whl proj @ file:///c:/path/to/pkg.whl Directory proj @ file:///path/to/pkg proj @ file:///c:/path/to/pkg

Tip

You may also specify paths relative to your project's root directory on all platforms by using context formatting:

<NAME> @ {root:uri}/pkg_inside_project\n<NAME> @ {root:uri}/../pkg_alongside_project\n
"},{"location":"config/dependency/#remote","title":"Remote","text":"

You can install source archives and wheels by simply referring to a URL:

black @ https://github.com/psf/black/archive/refs/tags/21.10b0.zip\npytorch @ https://download.pytorch.org/whl/cu102/torch-1.10.0%2Bcu102-cp39-cp39-linux_x86_64.whl\n

An expected hash value may be specified by appending a #<HASH_ALGORITHM>=<EXPECTED_HASH> component:

requests @ https://github.com/psf/requests/archive/refs/tags/v2.26.0.zip#sha256=eb729a757f01c10546ebd179ae2aec852dd0d7f8ada2328ccf4558909d859985\n

If the hash differs from the expected hash, the installation will fail.

It is recommended that only hashes which are unconditionally provided by the latest version of the standard library's hashlib module be used for hashes. As of Python 3.10, that list consists of:

"},{"location":"config/dependency/#complex-syntax","title":"Complex syntax","text":"

The following is an example that uses features and environment markers:

pkg[feature1,feature2] @ <REFERENCE> ; python_version < \"3.7\"\n

Note that the space before the semicolon is required.

"},{"location":"config/hatch/","title":"Hatch configuration","text":"

Configuration for Hatch itself is stored in a config.toml file located by default in one of the following platform-specific directories.

Platform Path macOS ~/Library/Application Support/hatch Windows %USERPROFILE%\\AppData\\Local\\hatch Unix $XDG_CONFIG_HOME/hatch (the XDG_CONFIG_HOME environment variable default is ~/.config)

You can select a custom path to the file using the --config root option or by setting the HATCH_CONFIG environment variable.

The file can be managed by the config command group.

"},{"location":"config/hatch/#mode","title":"Mode","text":"

The mode key controls how Hatch selects the project to work on.

"},{"location":"config/hatch/#local","title":"Local","text":"config.toml
mode = \"local\"\n

By default, Hatch will look for a pyproject.toml file in the current working directory and any parent directories. The directory storing the first found file will be considered the project root.

"},{"location":"config/hatch/#project","title":"Project","text":"config.toml
mode = \"project\"\nproject = \"proj1\"\n\n[projects]\nproj1 = \"/path/to/project1\"\nproj2 = {\"location\": \"/path/to/project2\"}\n\n[dirs]\nproject = [\"/path/to/monorepo1\", \"/path/to/monorepo2\"]\n

In this mode, Hatch will only work on the selected project. The project is located using multiple heuristics:

  1. If the project is defined in the projects table then it must be a string, or an inline table with a location key, that is the full path to the project.
  2. If the project matches a subdirectory in any of the directories listed in dirs.project, then that will be used as the project root.

An error will occur if the project cannot be found.

You can use the config set command to change the project you are working on:

$ hatch config set project proj2\nNew setting:\nproject = \"proj2\"\n

The project can be selected on a per-command basis with the -p/--project (environment variable HATCH_PROJECT) root option.

"},{"location":"config/hatch/#aware","title":"Aware","text":"config.toml
mode = \"aware\"\n

This is essentially the local mode with a fallback to the project mode.

"},{"location":"config/hatch/#shell","title":"Shell","text":"

You can control the shell used to enter environments with the shell key.

If defined as a string, it must be the name of one of the supported shells and be available along your PATH.

config.toml
shell = \"fish\"\n

If the executable name of your shell differs from the supported name, you can define the shell as a table with name and path keys.

config.toml
[shell]\nname = \"bash\"\npath = \"/bin/ash\"\n

You can change the default arguments used to spawn most shells with the args key. The default for such supported shells is usually [\"-i\"].

config.toml
[shell]\nname = \"bash\"\nargs = [\"--login\"]\n
"},{"location":"config/hatch/#supported","title":"Supported","text":"Shell Name Arguments macOS Windows Unix Almquist shell ash [\"-i\"] Bash bash [\"-i\"] Command Prompt cmd C shell csh [\"-i\"] fish fish [\"-i\"] Nushell nu [] PowerShell pwsh, powershell tcsh tcsh [\"-i\"] xonsh xonsh [\"-i\"] Z shell zsh [\"-i\"]"},{"location":"config/hatch/#default","title":"Default","text":"

Hatch will attempt to use the current shell based on parent processes. If the shell cannot be determined, then on Windows systems Hatch will use the SHELL environment variable, if present, followed by the COMSPEC environment variable, defaulting to cmd. On all other platforms only the SHELL environment variable will be used, defaulting to bash.

"},{"location":"config/hatch/#directories","title":"Directories","text":""},{"location":"config/hatch/#data","title":"Data","text":"config.toml
[dirs]\ndata = \"...\"\n

This is the directory that is used to persist data. By default it is set to one of the following platform-specific directories.

Platform Path macOS ~/Library/Application Support/hatch Windows %USERPROFILE%\\AppData\\Local\\hatch Unix $XDG_DATA_HOME/hatch (the XDG_DATA_HOME environment variable default is ~/.local/share)

You can select a custom path to the directory using the --data-dir root option or by setting the HATCH_DATA_DIR environment variable.

"},{"location":"config/hatch/#cache","title":"Cache","text":"config.toml
[dirs]\ncache = \"...\"\n

This is the directory that is used to cache data. By default it is set to one of the following platform-specific directories.

Platform Path macOS ~/Library/Caches/hatch Windows %USERPROFILE%\\AppData\\Local\\hatch\\Cache Unix $XDG_CACHE_HOME/hatch (the XDG_CACHE_HOME environment variable default is ~/.cache)

You can select a custom path to the directory using the --cache-dir root option or by setting the HATCH_CACHE_DIR environment variable.

"},{"location":"config/hatch/#environments","title":"Environments","text":"config.toml
[dirs.env]\n<ENV_TYPE> = \"...\"\n

This determines where to store environments, with every key being the type of environment and the value being the desired storage location.

For example, if you wanted to store virtual environments in a .virtualenvs directory within your home directory, you could specify the following:

config.toml
[dirs.env]\nvirtual = \"~/.virtualenvs\"\n

Any environment variables are also expanded.

If the path is not absolute, then it will be relative to the project root. So if you wanted to use a directory named .hatch in each project directory, you could do:

config.toml
[dirs.env]\nvirtual = \".hatch\"\n

Any type of environment that is not explicitly defined will default to <DATA_DIR>/env/<ENV_TYPE>.

"},{"location":"config/hatch/#python-installations","title":"Python installations","text":"config.toml
[dirs]\npython = \"...\"\n

This determines where to install specific versions of Python.

The following values have special meanings:

Value Path shared (default) ~/.pythons isolated <DATA_DIR>/pythons"},{"location":"config/hatch/#terminal","title":"Terminal","text":"

You can configure how all output is displayed using the terminal.styles table. These settings are also applied to all plugins.

config.toml
[terminal.styles]\nerror = \"...\"\n...\n

Cross-platform terminal capabilities are provided by Rich.

"},{"location":"config/hatch/#output-levels","title":"Output levels","text":"

The levels of output are as follows. Note that the verbosity indicates the minimum level at which the output is displayed.

Level Default Verbosity Description debug bold 1 - 3 Messages that are not useful for most user experiences error bold red -2 Messages indicating some unrecoverable error info bold 0 Messages conveying basic information success bold cyan 0 Messages indicating some positive outcome waiting bold magenta 0 Messages shown before potentially time consuming operations warning bold yellow -1 Messages conveying important information

See the documentation and color reference for guidance on valid values.

"},{"location":"config/hatch/#spinner","title":"Spinner","text":"

You can select the sequence used for waiting animations with the spinner option.

config.toml
[terminal.styles]\nspinner = \"...\"\n
"},{"location":"config/metadata/","title":"Project metadata","text":"

Project metadata is stored in a pyproject.toml file located at the root of a project's tree and is based entirely on PEP 621.

"},{"location":"config/metadata/#name","title":"Name (required)","text":"

The name of the project.

pyproject.toml
[project]\nname = \"your-app\"\n
"},{"location":"config/metadata/#version","title":"Version (required)","text":"pyproject.toml DynamicStatic

See the dedicated versioning section.

[project]\n...\ndynamic = [\"version\"]\n\n[tool.hatch.version]\npath = \"...\"\n
[project]\n...\nversion = \"0.0.1\"\n
"},{"location":"config/metadata/#description","title":"Description","text":"

A brief summary of the project.

pyproject.toml
[project]\n...\ndescription = '...'\n
"},{"location":"config/metadata/#readme","title":"Readme","text":"

The full description of the project.

pyproject.toml SimpleComplex

The file extension must be .md, .rst, or .txt.

[project]\n...\nreadme = \"README.md\"\n

The content-type field must be set to text/markdown, text/x-rst, or text/plain.

FileText

A charset field may also be set to instruct which encoding to use for reading the file, defaulting to utf-8.

[project]\n...\nreadme = {\"file\" = \"README.md\", \"content-type\" = \"text/markdown\"}\n

The content-type field must be set to text/markdown or text/x-rst.

[project]\n...\nreadme = {\"text\" = \"...\", \"content-type\" = \"text/markdown\"}\n

Note

If this is defined as a file, then it will always be included in source distributions for consistent builds.

"},{"location":"config/metadata/#python-support","title":"Python support","text":"

The Python version requirements of the project.

pyproject.toml
[project]\n...\nrequires-python = \">=3.8\"\n
"},{"location":"config/metadata/#license","title":"License","text":"

For more information, see PEP 639.

pyproject.toml SPDX expressionFiles
[project]\n...\nlicense = \"Apache-2.0 OR MIT\"\n
PathsGlobs
[project]\n...\nlicense-files = { paths = [\"LICENSE.txt\"] }\n
[project]\n...\nlicense-files = { globs = [\"LICENSES/*\"] }\n
"},{"location":"config/metadata/#ownership","title":"Ownership","text":"

The people or organizations considered to be the authors or maintainers of the project. The exact meaning is open to interpretation; it may list the original or primary authors, current maintainers, or owners of the package. If the values are the same, prefer only the use of the authors field.

pyproject.toml
[project]\n...\nauthors = [\n{ name = \"...\", email = \"...\" },\n]\nmaintainers = [\n{ name = \"...\", email = \"...\" },\n]\n
"},{"location":"config/metadata/#keywords","title":"Keywords","text":"

The keywords used to assist in the discovery of the project.

pyproject.toml
[project]\n...\nkeywords = [\n\"...\",\n]\n
"},{"location":"config/metadata/#classifiers","title":"Classifiers","text":"

The trove classifiers that apply to the project.

pyproject.toml
[project]\n...\nclassifiers = [\n\"...\",\n]\n
"},{"location":"config/metadata/#urls","title":"URLs","text":"

A table of URLs where the key is the URL label and the value is the URL itself.

pyproject.toml
[project.urls]\nDocumentation = \"...\"\n\"Source code\" = \"...\"\n
"},{"location":"config/metadata/#dependencies","title":"Dependencies","text":"

The format is based on PEP 631. See the dependency specification section for more information.

Entries support context formatting and disallow direct references by default.

"},{"location":"config/metadata/#required","title":"Required","text":"pyproject.toml
[project]\n...\ndependencies = [\n\"...\",\n]\n
"},{"location":"config/metadata/#optional","title":"Optional","text":"pyproject.toml
[project.optional-dependencies]\noption1 = [\n\"...\",\n]\noption2 = [\n\"...\",\n]\n
"},{"location":"config/metadata/#entry-points","title":"Entry points","text":"

Entry points are a mechanism for the project to advertise components it provides to be discovered and used by other code.

"},{"location":"config/metadata/#cli","title":"CLI","text":"

After installing projects that define CLI scripts, each key will be available along your PATH as a command that will call its associated object.

pyproject.toml
[project.scripts]\ncli-name = \"pkg.subpkg:func\"\n

Using the above example, running cli-name would essentially execute the following Python script:

import sys\n\nfrom pkg.subpkg import func\n\nsys.exit(func())\n
"},{"location":"config/metadata/#gui","title":"GUI","text":"

GUI scripts are exactly the same as CLI scripts except on Windows, where they are handled specially so that they can be started without a console.

pyproject.toml
[project.gui-scripts]\ngui-name = \"pkg.subpkg:func\"\n
"},{"location":"config/metadata/#plugins","title":"Plugins","text":"pyproject.toml
[project.entry-points.plugin-namespace]\nplugin-name1 = \"pkg.subpkg1\"\nplugin-name2 = \"pkg.subpkg2:func\"\n
"},{"location":"config/metadata/#dynamic","title":"Dynamic","text":"

If any metadata fields are set dynamically, like the version may be, then they must be listed here.

pyproject.toml
[project]\n...\ndynamic = [\n\"...\",\n]\n
"},{"location":"config/metadata/#metadata-options","title":"Metadata options","text":""},{"location":"config/metadata/#allowing-direct-references","title":"Allowing direct references","text":"

By default, dependencies are not allowed to define direct references. To disable this check, set allow-direct-references to true:

pyproject.toml hatch.toml
[tool.hatch.metadata]\nallow-direct-references = true\n
[metadata]\nallow-direct-references = true\n
"},{"location":"config/metadata/#allowing-ambiguous-features","title":"Allowing ambiguous features","text":"

By default, names of optional dependencies are normalized to prevent ambiguity. To disable this normalization, set allow-ambiguous-features to true:

pyproject.toml hatch.toml
[tool.hatch.metadata]\nallow-ambiguous-features = true\n
[metadata]\nallow-ambiguous-features = true\n

Deprecated

This option temporarily exists to provide better interoperability with tools that do not yet support PEP 685 and will be removed in the first minor release after Jan 1, 2024.

"},{"location":"config/project-templates/","title":"Project templates","text":"

You can control how new projects are created by the new command using Hatch's config file.

"},{"location":"config/project-templates/#author","title":"Author","text":"config.toml
[template]\nname = \"...\"\nemail = \"...\"\n
"},{"location":"config/project-templates/#licenses","title":"Licenses","text":"config.toml
[template.licenses]\nheaders = true\ndefault = [\n\"MIT\",\n]\n

The list of licenses should be composed of SPDX identifiers. If multiple licenses are specified, then they will be placed in a LICENSES directory.

"},{"location":"config/project-templates/#options","title":"Options","text":""},{"location":"config/project-templates/#tests","title":"Tests","text":"

This adds a tests directory with environments for testing and linting.

config.toml
[template.plugins.default]\ntests = true\n
"},{"location":"config/project-templates/#ci","title":"CI","text":"

This adds a GitHub Actions workflow that runs tests on all platforms using modern versions of Python.

config.toml
[template.plugins.default]\nci = false\n
"},{"location":"config/project-templates/#src-layout","title":"src layout","text":"

See this blog post.

config.toml
[template.plugins.default]\nsrc-layout = true\n
"},{"location":"config/project-templates/#feature-flags","title":"Feature flags","text":""},{"location":"config/project-templates/#command-line-interface","title":"Command line interface","text":"

The --cli flag adds a CLI backed by Click that can also be invoked with python -m <PKG_NAME>.

"},{"location":"config/environment/advanced/","title":"Advanced environment configuration","text":""},{"location":"config/environment/advanced/#context-formatting","title":"Context formatting","text":"

All environments support the following extra context formatting fields:

Field Description env_name The name of the environment env_type The type of environment matrix Its modifier selects the value of that matrix variable. If the environment is not part of a matrix or was not generated with the variable, you must specify a default value as an additional modifier e.g. {matrix:version:v1.0.0}. verbosity The integer verbosity value of Hatch. A flag modifier is supported that will render the value as a CLI flag e.g. -2 becomes -qq, 1 becomes -v, and 0 becomes an empty string. An additional flag integer modifier may be used to adjust the verbosity level. For example, if you wanted to make a command quiet by default, you could use {verbosity:flag:-1} within the command. args For executed commands only, any extra command line arguments with an optional default modifier if none were provided"},{"location":"config/environment/advanced/#matrix","title":"Matrix","text":"

Environments can define a series of matrices with the matrix option:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"pytest\"\n]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeature = [\"foo\", \"bar\"]\n
[envs.test]\ndependencies = [\n\"pytest\"\n]\n\n[[envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[envs.test.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeature = [\"foo\", \"bar\"]\n

Doing so will result in the product of each variable combination being its own environment.

"},{"location":"config/environment/advanced/#naming","title":"Naming","text":"

The name of the generated environments will be the variable values of each combination separated by hyphens, altogether prefixed by <ENV_NAME>.. For example, the following configuration:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\nversion = [\"42\"]\nfeature = [\"foo\", \"bar\"]\n
[[envs.test.matrix]]\nversion = [\"42\"]\nfeature = [\"foo\", \"bar\"]\n

would indicate the following unique environments:

test.42-foo\ntest.42-bar\n

The exceptions to this format are described below.

"},{"location":"config/environment/advanced/#python-variables","title":"Python variables","text":"

If the variables py or python are specified, then they will rank first in the product result and will be prefixed by py if the value is not. For example, the following configuration:

pyproject.toml hatch.toml
[[tool.hatch.envs.test.matrix]]\nversion = [\"42\"]\npython = [\"3.9\", \"pypy3\"]\n
[[envs.test.matrix]]\nversion = [\"42\"]\npython = [\"3.9\", \"pypy3\"]\n

would generate the following environments:

test.py3.9-42\ntest.pypy3-42\n

Note

The value of this variable sets the Python version.

"},{"location":"config/environment/advanced/#name-formatting","title":"Name formatting","text":"

You can set the matrix-name-format option to modify how each variable part is formatted which recognizes the placeholders {variable} and {value}. For example, the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\nmatrix-name-format = \"{variable}_{value}\"\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"42\"]\nfeature = [\"foo\", \"bar\"]\n
[envs.test]\nmatrix-name-format = \"{variable}_{value}\"\n\n[[envs.test.matrix]]\nversion = [\"42\"]\nfeature = [\"foo\", \"bar\"]\n

would produce the following environments:

test.version_42-feature_foo\ntest.version_42-feature_bar\n

By default this option is set to {value}.

"},{"location":"config/environment/advanced/#default-environment","title":"Default environment","text":"

If the default environment defines matrices, then the generated names will not be prefixed by the environment name. This can be useful for projects that only need a single series of matrices without any standalone environments.

"},{"location":"config/environment/advanced/#selection","title":"Selection","text":"

Rather than selecting a single generated environment, you can select the root environment to target all of them. For example, if you have the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n]\n\n[tool.hatch.envs.test.scripts]\ncov = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n
[envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n]\n\n[envs.test.scripts]\ncov = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'\n\n[[envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n

you could then run your tests consecutively in all 4 environments with:

hatch run test:cov\n
"},{"location":"config/environment/advanced/#option-overrides","title":"Option overrides","text":"

You can modify options based on the conditions of different sources like matrix variables with the overrides table, using dotted key syntax for each declaration:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>.overrides]\n<SOURCE>.<CONDITION>.<OPTION> = <VALUE>\n
[envs.<ENV_NAME>.overrides]\n<SOURCE>.<CONDITION>.<OPTION> = <VALUE>\n

The type of the selected option determines the types of values.

"},{"location":"config/environment/advanced/#platform-overrides","title":"Platform overrides","text":"

Options can be modified based on the current platform using the platform source.

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nplatform.windows.scripts = [\n'run=pytest -m \"not io_uring\"',\n]\n
[envs.test.overrides]\nplatform.windows.scripts = [\n'run=pytest -m \"not io_uring\"',\n]\n

The following platforms are supported:

"},{"location":"config/environment/advanced/#environment-variable-overrides","title":"Environment variable overrides","text":"

Environment variables can modify options using the env source.

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nenv.GITHUB_ACTIONS.dev-mode = { value = false, if = [\"true\"] }\n
[envs.test.overrides]\nenv.GITHUB_ACTIONS.dev-mode = { value = false, if = [\"true\"] }\n
"},{"location":"config/environment/advanced/#matrix-variable-overrides","title":"Matrix variable overrides","text":"

The matrix variables used to generate each environment can be used to modify options within using the matrix source.

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nmatrix.version.env-vars = \"PRODUCT_VERSION\"\nmatrix.auth.features = [\n{ value = \"oauth\", if = [\"oauth2\"] },\n{ value = \"kerberos\", if = [\"kerberos\"] },\n]\n\n[[tool.hatch.envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"legacy\", \"latest\"]\nauth = [\"oauth2\", \"kerberos\", \"noauth\"]\n
[envs.test.overrides]\nmatrix.version.env-vars = \"PRODUCT_VERSION\"\nmatrix.auth.features = [\n{ value = \"oauth\", if = [\"oauth2\"] },\n{ value = \"kerberos\", if = [\"kerberos\"] },\n]\n\n[[envs.test.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"legacy\", \"latest\"]\nauth = [\"oauth2\", \"kerberos\", \"noauth\"]\n
"},{"location":"config/environment/advanced/#name-overrides","title":"Name overrides","text":"

When a matrix is defined, the name source can be used for regular expression matching on the generated name, minus the prefix for non-default environments.

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nname.\"^0\".env-vars = \"TESTING_UNSTABLE=true\"\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"0.1.0\", \"0.2.0\", \"1.0.0\"]\n
[envs.test.overrides]\nname.\"^0\".env-vars = \"TESTING_UNSTABLE=true\"\n\n[[envs.test.matrix]]\nversion = [\"0.1.0\", \"0.2.0\", \"1.0.0\"]\n
"},{"location":"config/environment/advanced/#types","title":"Types","text":""},{"location":"config/environment/advanced/#overwriting","title":"Overwriting","text":"

Rather than supplementing the values within mapping types or array types, you can overwrite the option as a whole by prefixing the name with set-:

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nmatrix.foo.set-platforms = [\"macos\", \"linux\"]\n
[envs.test.overrides]\nmatrix.foo.set-platforms = [\"macos\", \"linux\"]\n

When overwriting entire options or keys within mappings, override sources are applied in the following order:

  1. platform
  2. environment variables
  3. matrix variables
  4. names
"},{"location":"config/environment/advanced/#conditions","title":"Conditions","text":"

You may specify certain extra keys for any inline table that will determine whether or not to apply that entry. These modifiers may be combined with others and any negative evaluation will immediately cause the entry to be skipped.

"},{"location":"config/environment/advanced/#allowed-values","title":"Allowed values","text":"

The if key represents the allowed values for that condition. If the value of the condition is not listed, then that entry will not be applied:

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nmatrix.version.python = { value = \"pypy\", if = [\"3.14\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
[envs.test.overrides]\nmatrix.version.python = { value = \"pypy\", if = [\"3.14\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
"},{"location":"config/environment/advanced/#specific-platforms","title":"Specific platforms","text":"

The platform key represents the desired platforms. If the current platform is not listed, then that entry will not be applied:

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nenv.EXPERIMENTAL.python = { value = \"pypy\", if = [\"1\"], platform = [\"macos\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"], platform = [\"linux\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
[envs.test.overrides]\nenv.EXPERIMENTAL.python = { value = \"pypy\", if = [\"1\"], platform = [\"macos\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"], platform = [\"linux\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
"},{"location":"config/environment/advanced/#required-environment-variables","title":"Required environment variables","text":"

The env key represents the required environment variables. If any of the listed environment variables are not set or the defined value does not match, then that entry will not be applied:

pyproject.toml hatch.toml
[tool.hatch.envs.test.overrides]\nplatform.windows.python = { value = \"pypy\", env = [\"EXPERIMENTAL\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"], env = [\"FOO\", \"BAR=BAZ\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[tool.hatch.envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
[envs.test.overrides]\nplatform.windows.python = { value = \"pypy\", env = [\"EXPERIMENTAL\"] }\nmatrix.version.env-vars = [\n{ key = \"KEY1\", value = \"VALUE1\", if = [\"42\"], env = [\"FOO\", \"BAR=BAZ\"] },\n{ key = \"KEY2\", value = \"VALUE2\", if = [\"3.14\"] },\n]\n\n[[envs.test.matrix]]\nversion = [\"42\", \"3.14\"]\n
"},{"location":"config/environment/overview/","title":"Environment configuration","text":"

All environments are defined as sections within the tool.hatch.envs table.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\n
[envs.<ENV_NAME>]\n

The storage location for environments is completely configurable.

Unless an environment is explicitly selected on the command line, the default environment will be used. The type of this environment defaults to virtual.

"},{"location":"config/environment/overview/#inheritance","title":"Inheritance","text":"

All environments inherit from the environment defined by its template option, which defaults to default.

So for the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.foo]\ntype = \"baz\"\nskip-install = true\n\n[tool.hatch.envs.bar]\ntemplate = \"foo\"\nskip-install = false\n
[envs.foo]\ntype = \"baz\"\nskip-install = true\n\n[envs.bar]\ntemplate = \"foo\"\nskip-install = false\n

the environment bar will be of type baz with skip-install set to false.

Note

Environments do not inherit matrices.

"},{"location":"config/environment/overview/#self-referential-environments","title":"Self-referential environments","text":"

You can disable inheritance by setting template to the environment's own name:

pyproject.toml hatch.toml
[tool.hatch.envs.foo]\ntemplate = \"foo\"\n
[envs.foo]\ntemplate = \"foo\"\n
"},{"location":"config/environment/overview/#detached-environments","title":"Detached environments","text":"

A common use case is standalone environments that do not require inheritance nor the installation of the project, such as for linting or sometimes building documentation. Enabling the detached option will make the environment self-referential and will skip project installation:

pyproject.toml hatch.toml
[tool.hatch.envs.lint]\ndetached = true\n
[envs.lint]\ndetached = true\n
"},{"location":"config/environment/overview/#dependencies","title":"Dependencies","text":"

You can install dependencies in addition to the ones defined by your project's metadata. Entries support context formatting.

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n\"pytest-mock\",\n]\n
[envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n\"pytest-mock\",\n]\n

If you define environments with dependencies that only slightly differ from their inherited environments, you can use the extra-dependencies option to avoid redeclaring the dependencies option:

pyproject.toml hatch.toml
[tool.hatch.envs.default]\ndependencies = [\n\"foo\",\n\"bar\",\n]\n\n[tool.hatch.envs.experimental]\nextra-dependencies = [\n\"baz\",\n]\n
[envs.default]\ndependencies = [\n\"foo\",\n\"bar\",\n]\n\n[envs.experimental]\nextra-dependencies = [\n\"baz\",\n]\n

Tip

Hatch uses pip to install dependencies so any configuration it supports Hatch does as well. For example, if you wanted to only use a private repository you could set the PIP_INDEX_URL environment variable.

"},{"location":"config/environment/overview/#installation","title":"Installation","text":""},{"location":"config/environment/overview/#features","title":"Features (extras)","text":"

If your project defines optional dependencies, you can select which groups to install using the features option:

pyproject.toml hatch.toml
[tool.hatch.envs.nightly]\nfeatures = [\n\"server\",\n\"grpc\",\n]\n
[envs.nightly]\nfeatures = [\n\"server\",\n\"grpc\",\n]\n

Note

Features/optional dependencies are also known as extras in other tools.

"},{"location":"config/environment/overview/#dev-mode","title":"Dev mode","text":"

By default, environments will always reflect the current state of your project on disk. Set dev-mode to false to disable this behavior:

pyproject.toml hatch.toml
[tool.hatch.envs.static]\ndev-mode = false\n
[envs.static]\ndev-mode = false\n
"},{"location":"config/environment/overview/#skip-install","title":"Skip install","text":"

By default, environments will install your project during creation. To ignore this step, set skip-install to true:

pyproject.toml hatch.toml
[tool.hatch.envs.lint]\nskip-install = true\n
[envs.lint]\nskip-install = true\n
"},{"location":"config/environment/overview/#environment-variables","title":"Environment variables","text":""},{"location":"config/environment/overview/#defined","title":"Defined","text":"

You can define environment variables with the env-vars option:

pyproject.toml hatch.toml
[tool.hatch.envs.docs]\ndependencies = [\n\"mkdocs\"\n]\n[tool.hatch.envs.docs.env-vars]\nSOURCE_DATE_EPOCH = \"1580601600\"\n
[envs.docs]\ndependencies = [\n\"mkdocs\"\n]\n[envs.docs.env-vars]\nSOURCE_DATE_EPOCH = \"1580601600\"\n

Values support context formatting.

"},{"location":"config/environment/overview/#filters","title":"Filters","text":"

By default, environments will have access to all environment variables. You can filter with wildcard patterns using the env-include/env-exclude options:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nenv-include = [\n\"FOO*\",\n]\nenv-exclude = [\n\"BAR\",\n]\n
[envs.<ENV_NAME>]\nenv-include = [\n\"FOO*\",\n]\nenv-exclude = [\n\"BAR\",\n]\n

Exclusion patterns take precedence but will never affect defined environment variables.

"},{"location":"config/environment/overview/#scripts","title":"Scripts","text":"

You can define named scripts that may be executed or referenced at the beginning of other scripts. Context formatting is supported.

For example, in the following configuration:

pyproject.toml hatch.toml
[tool.hatch.envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n\"pytest-mock\",\n]\n[tool.hatch.envs.test.scripts]\nrun-coverage = \"pytest --cov-config=pyproject.toml --cov=pkg --cov=tests\"\nrun = \"run-coverage --no-cov\"\n
[envs.test]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n\"pytest-mock\",\n]\n[envs.test.scripts]\nrun-coverage = \"pytest --cov-config=pyproject.toml --cov=pkg --cov=tests\"\nrun = \"run-coverage --no-cov\"\n

the run script would be expanded to:

pytest --cov-config=pyproject.toml --cov=pkg --cov=tests --no-cov\n

Scripts can also be defined as an array of strings.

pyproject.toml hatch.toml
[tool.hatch.envs.style]\ndetached = true\ndependencies = [\n\"flake8\",\n\"black\",\n\"isort\",\n]\n[tool.hatch.envs.style.scripts]\ncheck = [\n\"flake8 .\",\n\"black --check --diff .\",\n\"isort --check-only --diff .\",\n]\nfmt = [\n\"isort .\",\n\"black .\",\n\"check\",\n]\n
[envs.style]\ndetached = true\ndependencies = [\n\"flake8\",\n\"black\",\n\"isort\",\n]\n[envs.style.scripts]\ncheck = [\n\"flake8 .\",\n\"black --check --diff .\",\n\"isort --check-only --diff .\",\n]\nfmt = [\n\"isort .\",\n\"black .\",\n\"check\",\n]\n

Similar to make, you can ignore the exit code of commands that start with - (a hyphen). For example, the script error defined by the following configuration would halt after the second command with 3 as the exit code:

pyproject.toml hatch.toml
[tool.hatch.envs.test.scripts]\nerror = [\n\"- exit 1\",\n\"exit 3\",\n\"exit 0\",\n]\n
[envs.test.scripts]\nerror = [\n\"- exit 1\",\n\"exit 3\",\n\"exit 0\",\n]\n

Tip

Individual scripts inherit from parent environments just like options.

"},{"location":"config/environment/overview/#commands","title":"Commands","text":"

All commands are able to use any defined scripts. Also like scripts, context formatting is supported and the exit code of commands that start with a hyphen will be ignored.

"},{"location":"config/environment/overview/#pre-install","title":"Pre-install","text":"

You can run commands immediately before environments install your project.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\npre-install-commands = [\n\"...\",\n]\n
[envs.<ENV_NAME>]\npre-install-commands = [\n\"...\",\n]\n
"},{"location":"config/environment/overview/#post-install","title":"Post-install","text":"

You can run commands immediately after environments install your project.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\npost-install-commands = [\n\"...\",\n]\n
[envs.<ENV_NAME>]\npost-install-commands = [\n\"...\",\n]\n
"},{"location":"config/environment/overview/#python-version","title":"Python version","text":"

The python option specifies which version of Python to use, or an absolute path to a Python interpreter:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\npython = \"3.10\"\n
[envs.<ENV_NAME>]\npython = \"3.10\"\n

All environment types should respect this option.

"},{"location":"config/environment/overview/#supported-platforms","title":"Supported platforms","text":"

The platforms option indicates the operating systems with which the environment is compatible:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nplatforms = [\"linux\", \"windows\", \"macos\"]\n
[envs.<ENV_NAME>]\nplatforms = [\"linux\", \"windows\", \"macos\"]\n

The following platforms are supported:

If unspecified, the environment is assumed to be compatible with all platforms.

"},{"location":"config/environment/overview/#description","title":"Description","text":"

The description option is purely informational and is displayed in the output of the env show command:

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\ndescription = \"\"\"\nLorem ipsum ...\n\"\"\"\n
[envs.<ENV_NAME>]\ndescription = \"\"\"\nLorem ipsum ...\n\"\"\"\n
"},{"location":"config/environment/overview/#type","title":"Type","text":"

An environment's type determines which environment plugin will be used for management. The only built-in environment type is virtual, which uses virtual Python environments.

"},{"location":"history/hatch/","title":"Hatch history","text":"

All notable changes to Hatch will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

"},{"location":"history/hatch/#unreleased","title":"Unreleased","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.7.0","title":"1.7.0 - 2023-04-03","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.6.3","title":"1.6.3 - 2022-10-24","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.6.2","title":"1.6.2 - 2022-10-20","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.6.1","title":"1.6.1 - 2022-10-16","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.6.0","title":"1.6.0 - 2022-10-08","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.5.0","title":"1.5.0 - 2022-08-28","text":"

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.4.2","title":"1.4.2 - 2022-08-16","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.4.1","title":"1.4.1 - 2022-08-13","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.4.0","title":"1.4.0 - 2022-08-06","text":"

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.3.1","title":"1.3.1 - 2022-07-11","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.3.0","title":"1.3.0 - 2022-07-10","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.2.1","title":"1.2.1 - 2022-05-30","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.2.0","title":"1.2.0 - 2022-05-22","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatch/#hatch-v1.1.2","title":"1.1.2 - 2022-05-20","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.1.1","title":"1.1.1 - 2022-05-12","text":"

Fixed:

"},{"location":"history/hatch/#hatch-v1.1.0","title":"1.1.0 - 2022-05-12","text":"

Changed:

Added:

"},{"location":"history/hatch/#hatch-v1.0.0","title":"1.0.0 - 2022-04-28","text":"

This is the first stable release of Hatch v1, a complete rewrite. Enjoy!

"},{"location":"history/hatchling/","title":"Hatchling history","text":"

All notable changes to Hatchling will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

"},{"location":"history/hatchling/#unreleased","title":"Unreleased","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.18.0","title":"1.18.0 - 2023-06-12","text":"

Changed:

Added:

"},{"location":"history/hatchling/#hatchling-v1.17.1","title":"1.17.1 - 2023-06-03","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.17.0","title":"1.17.0 - 2023-05-12","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.16.1","title":"1.16.1 - 2023-05-11","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.16.0","title":"1.16.0 - 2023-05-11","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.15.0","title":"1.15.0 - 2023-05-09","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.14.1","title":"1.14.1 - 2023-04-23","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.14.0","title":"1.14.0 - 2023-04-02","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.13.0","title":"1.13.0 - 2023-02-09","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.12.2","title":"1.12.2 - 2023-01-05","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.12.1","title":"1.12.1 - 2022-12-31","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.12.0","title":"1.12.0 - 2022-12-30","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.11.1","title":"1.11.1 - 2022-10-19","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.11.0","title":"1.11.0 - 2022-10-08","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.10.0","title":"1.10.0 - 2022-09-18","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.9.0","title":"1.9.0 - 2022-09-09","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.8.1","title":"1.8.1 - 2022-08-25","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.8.0","title":"1.8.0 - 2022-08-16","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.7.1","title":"1.7.1 - 2022-08-13","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.7.0","title":"1.7.0 - 2022-08-12","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.6.0","title":"1.6.0 - 2022-07-23","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.5.0","title":"1.5.0 - 2022-07-11","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.4.1","title":"1.4.1 - 2022-07-04","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.4.0","title":"1.4.0 - 2022-07-03","text":"

Changed:

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.3.1","title":"1.3.1 - 2022-05-30","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.3.0","title":"1.3.0 - 2022-05-22","text":"

Removed:

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v1.2.0","title":"1.2.0 - 2022-05-20","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.1.0","title":"1.1.0 - 2022-05-19","text":"

Added:

"},{"location":"history/hatchling/#hatchling-v1.0.0","title":"1.0.0 - 2022-05-17","text":"

Changed:

Added:

"},{"location":"history/hatchling/#hatchling-v0.25.1","title":"0.25.1 - 2022-06-14","text":"

Fixed:

"},{"location":"history/hatchling/#hatchling-v0.25.0","title":"0.25.0 - 2022-05-15","text":"

Added:

Fixed:

"},{"location":"history/hatchling/#hatchling-v0.24.0","title":"0.24.0 - 2022-04-28","text":"

This is the initial public release of the Hatchling build system. Support for Python 2 will be dropped in version 1.

"},{"location":"how-to/environment/package-indices/","title":"Package indices","text":"

Most Hatch environment types, like the default virtual, simply use pip to install dependencies. Therefore, you can use the standard environment variables that influence pip's behavior to choose where to search for packages.

Here's an example of setting up the default environment to look at 2 private indices (using context formatting for authentication) before finally falling back to PyPI:

pyproject.toml hatch.toml
[tool.hatch.envs.default.env-vars]\nPIP_INDEX_URL = \"https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group1_path>/-/packages/pypi/simple/\"\nPIP_EXTRA_INDEX_URL = \"https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group2_path>/-/packages/pypi/simple/ https://pypi.org/simple/\"\n
[envs.default.env-vars]\nPIP_INDEX_URL = \"https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group1_path>/-/packages/pypi/simple/\"\nPIP_EXTRA_INDEX_URL = \"https://token:{env:GITLAB_API_TOKEN}@gitlab.com/api/v4/groups/<group2_path>/-/packages/pypi/simple/ https://pypi.org/simple/\"\n
"},{"location":"how-to/plugins/testing-builds/","title":"Testing builds","text":"

For testing Hatchling plugins, you'll usually want to generate a project to execute builds as a real user would. For example, as a minimal pytest fixture:

from pathlib import Path\n\nimport pytest\n\n\n@pytest.fixture\ndef new_project(tmp_path):\n    project_dir = tmp_path / 'my-app'\n    project_dir.mkdir()\n\n    project_file = project_dir / 'pyproject.toml'\n    project_file.write_text(\n        f\"\"\"\\\n[build-system]\nrequires = [\"hatchling\", \"hatch-plugin-name @ {Path.cwd().as_uri()}\"]\nbuild-backend = \"hatchling.build\"\n\n[project]\nname = \"my-app\"\nversion = \"0.1.0\"\n\"\"\",\n        encoding='utf-8',\n    )\n    ...\n

The issue with this is that after the first test session, the project will be forever cached by pip based on the file path. Therefore, subsequent tests runs will never use updated code.

To invalidate the cache, copy your code to a new path for every test session:

import shutil\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nimport pytest\n\n\n@pytest.fixture(scope='session')\ndef plugin_dir():\n    with TemporaryDirectory() as d:\n        directory = Path(d, 'plugin')\n        shutil.copytree(\n            Path.cwd(), directory, ignore=shutil.ignore_patterns('.git')\n        )\n\n        yield directory.resolve()\n\n\n@pytest.fixture\ndef new_project(tmp_path, plugin_dir):\n    project_dir = tmp_path / 'my-app'\n    project_dir.mkdir()\n\n    project_file = project_dir / 'pyproject.toml'\n    project_file.write_text(\n        f\"\"\"\\\n[build-system]\nrequires = [\"hatchling\", \"hatch-plugin-name @ {plugin_dir.as_uri()}\"]\nbuild-backend = \"hatchling.build\"\n\n[project]\nname = \"my-app\"\nversion = \"0.1.0\"\n\"\"\",\n        encoding='utf-8',\n    )\n    ...\n

Note

This example chooses to ignore copying .git for performance reasons. You may want to ignore more patterns, or copy only specific paths like this plugin does.

"},{"location":"meta/authors/","title":"Authors","text":""},{"location":"meta/authors/#maintainers","title":"Maintainers","text":""},{"location":"meta/authors/#contributors","title":"Contributors","text":""},{"location":"meta/faq/","title":"FAQ","text":""},{"location":"meta/faq/#interoperability","title":"Interoperability","text":"

Q: What is the risk of lock-in?

A: Not much! Other than the plugin system, everything uses Python's established standards by default. Project metadata is based entirely on PEP 621/PEP 631, the build system is compatible with PEP 517/PEP 660, versioning uses the scheme specified by PEP 440, dependencies are defined with PEP 508 strings, and environments use virtualenv.

Q: Must one use all features?

A: No, all features are optional! You can use just the build system, publish wheels and source distributions that were built by other tools, only use the environment management, etc.

"},{"location":"meta/faq/#libraries-vs-applications","title":"Libraries vs applications","text":"

Q: Are workflows for both libraries and applications supported?

A: Yes, mostly! Applications can utilize environment management just like libraries, and plugins can be used to build projects in arbitrary formats or publish artifacts to arbitrary destinations.

The only caveat is that currently there is no support for re-creating an environment given a set of dependencies in a reproducible manner. Although a standard lock file format may be far off since PEP 665 was rejected, resolving capabilities are coming to pip. When that is stabilized, Hatch will add locking functionality and dedicated documentation for managing applications.

"},{"location":"meta/faq/#tool-migration","title":"Tool migration","text":"

Q: How to migrate to Hatch?

"},{"location":"meta/faq/#build-system","title":"Build system","text":"SetuptoolsHatch setup.py MANIFEST.in
import os\nfrom io import open\n\nfrom setuptools import find_packages, setup\n\nabout = {}\nwith open(os.path.join('src', 'foo', '__about__.py'), 'r', 'utf-8') as f:\n    exec(f.read(), about)\n\nwith open('README.md', 'r', 'utf-8') as f:\n    readme = f.read()\n\nsetup(\n    # Metadata\n    name='foo',\n    version=about['__version__'],\n    description='...',\n    long_description=readme,\n    long_description_content_type='text/markdown',\n    author='...',\n    author_email='...',\n    project_urls={\n        'Documentation': '...',\n        'Source': '...',\n    },\n    classifiers=[\n        '...',\n    ],\n    keywords=[\n        '...',\n    ],\n    python_requires='>=3.8',\n    install_requires=[\n        '...',\n    ],\n    extras_require={\n        'feature': ['...'],\n    },\n\n    # Packaging\n    packages=find_packages(where='src'),\n    package_dir={'': 'src'},\n    package_data={\n        'foo': ['py.typed'],\n    },\n    zip_safe=False,\n    entry_points={\n        'console_scripts': [\n            'foo = foo.cli:main',\n        ],\n    },\n)\n
graft tests\n\nglobal-exclude *.py[cod] __pycache__\n
pyproject.toml
[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n\n[project]\nname = \"foo\"\ndescription = \"...\"\nreadme = \"README.md\"\nauthors = [\n{ name = \"...\", email = \"...\" },\n]\nclassifiers = [\n\"...\",\n]\nkeywords = [\n\"...\",\n]\nrequires-python = \">=3.8\"\ndependencies = [\n\"...\",\n]\ndynamic = [\"version\"]\n\n[project.urls]\nDocumentation = \"...\"\nSource = \"...\"\n\n[project.optional-dependencies]\nfeature = [\"...\"]\n\n[project.scripts]\nfoo = \"foo.cli:main\"\n\n[tool.hatch.version]\npath = \"src/foo/__about__.py\"\n\n[tool.hatch.build.targets.sdist]\ninclude = [\n\"/src\",\n\"/tests\",\n]\n
"},{"location":"meta/faq/#environments","title":"Environments","text":"ToxHatch

Invocation:

tox\n
tox.ini
[tox]\nenvlist =\npy{27,38}-{42,3.14}\npy{38,39}-{9000}-{foo,bar}\n\n[testenv]\nusedevelop = true\ndeps =\ncoverage[toml]\npytest\npytest-cov\nfoo: cryptography\ncommands =\npytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests {posargs}\nsetenv =\n3.14: PRODUCT_VERSION=3.14\n42: PRODUCT_VERSION=42\n9000: PRODUCT_VERSION=9000\n{foo,bar}: EXPERIMENTAL=true\n

Invocation:

hatch run test\n
pyproject.toml hatch.toml
[tool.hatch.envs.default]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n]\n\n[tool.hatch.envs.default.scripts]\ntest = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'\n\n[tool.hatch.envs.default.overrides]\nmatrix.version.env-vars = \"PRODUCT_VERSION\"\nmatrix.features.env-vars = \"EXPERIMENTAL=true\"\nmatrix.features.dependencies = [\n{ value = \"cryptography\", if = [\"foo\"] },\n]\n\n[[tool.hatch.envs.default.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[tool.hatch.envs.default.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeatures = [\"foo\", \"bar\"]\n
[envs.default]\ndependencies = [\n\"coverage[toml]\",\n\"pytest\",\n\"pytest-cov\",\n]\n\n[envs.default.scripts]\ntest = 'pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=pkg --cov=tests'\n\n[envs.default.overrides]\nmatrix.version.env-vars = \"PRODUCT_VERSION\"\nmatrix.features.env-vars = \"EXPERIMENTAL=true\"\nmatrix.features.dependencies = [\n{ value = \"cryptography\", if = [\"foo\"] },\n]\n\n[[envs.default.matrix]]\npython = [\"2.7\", \"3.8\"]\nversion = [\"42\", \"3.14\"]\n\n[[envs.default.matrix]]\npython = [\"3.8\", \"3.9\"]\nversion = [\"9000\"]\nfeatures = [\"foo\", \"bar\"]\n
"},{"location":"plugins/about/","title":"Plugins","text":"

Hatch utilizes pluggy for its plugin functionality.

"},{"location":"plugins/about/#overview","title":"Overview","text":"

All plugins provide registration hooks that return one or more classes that inherit from a particular type interface.

Each registration hook must be decorated by Hatch's hook marker. For example, if you wanted to create a new kind of environment you could do:

hooks.py
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialEnvironment\n\n\n@hookimpl\ndef hatch_register_environment():\n    return SpecialEnvironment\n

The hooks can return a single class or a list of classes.

Every class must define an attribute called PLUGIN_NAME that users will select when they wish to use the plugin. So in the example above, the class might be defined like:

plugin.py
...\nclass SpecialEnvironment(...):\n    PLUGIN_NAME = 'special'\n    ...\n
"},{"location":"plugins/about/#project-configuration","title":"Project configuration","text":""},{"location":"plugins/about/#naming","title":"Naming","text":"

It is recommended that plugin project names are prefixed with hatch-. For example, if you wanted to make a plugin that provides some functionality for a product named foo you might do:

pyproject.toml
[project]\nname = \"hatch-foo\"\n
"},{"location":"plugins/about/#discovery","title":"Discovery","text":"

You'll need to define your project as a Python plugin for Hatch:

pyproject.toml
[project.entry-points.hatch]\nfoo = \"pkg.hooks\"\n

The name of the plugin should be the project name (excluding any hatch- prefix) and the path should represent the module that contains the registration hooks.

"},{"location":"plugins/about/#classifier","title":"Classifier","text":"

Add Framework :: Hatch to your project's classifiers to make it easy to search for Hatch plugins:

pyproject.toml
[project]\nclassifiers = [\n...\n\"Framework :: Hatch\",\n...\n]\n
"},{"location":"plugins/about/#types","title":"Types","text":""},{"location":"plugins/about/#hatchling","title":"Hatchling","text":"

These are all involved in building projects and therefore any defined dependencies are automatically installed in each build environment.

"},{"location":"plugins/about/#hatch","title":"Hatch","text":"

These must be installed in the same environment as Hatch itself.

"},{"location":"plugins/utilities/","title":"Plugin utilities","text":""},{"location":"plugins/utilities/#hatchling.builders.utils.get_reproducible_timestamp","title":"hatchling.builders.utils.get_reproducible_timestamp() -> int","text":"

Returns an int derived from the SOURCE_DATE_EPOCH environment variable; see https://reproducible-builds.org/specs/source-date-epoch/.

The default value will always be: 1580601600

Source code in backend/src/hatchling/builders/utils.py
def get_reproducible_timestamp() -> int:\n\"\"\"\n    Returns an `int` derived from the `SOURCE_DATE_EPOCH` environment variable; see\n    https://reproducible-builds.org/specs/source-date-epoch/.\n    The default value will always be: `1580601600`\n    \"\"\"\nreturn int(os.environ.get('SOURCE_DATE_EPOCH', '1580601600'))\n
"},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig","title":"BuilderConfig","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.directory","title":"directory: str property","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.ignore_vcs","title":"ignore_vcs: bool property","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.reproducible","title":"reproducible: bool property","text":"

Whether or not the target should be built in a reproducible manner, defaulting to true.

"},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.dev_mode_dirs","title":"dev_mode_dirs: list[str] property","text":"

Directories which must be added to Python's search path in dev mode.

"},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.versions","title":"versions: list[str] property","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.dependencies","title":"dependencies: list[str] property","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.default_include","title":"default_include() -> list","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.default_exclude","title":"default_exclude() -> list","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.default_packages","title":"default_packages() -> list","text":""},{"location":"plugins/utilities/#hatchling.builders.config.BuilderConfig.default_only_include","title":"default_only_include() -> list","text":""},{"location":"plugins/utilities/#hatchling.bridge.app.Application","title":"Application","text":"

The way output is displayed can be configured by users.

Important

Never import this directly; Hatch judiciously decides if a type of plugin requires the capabilities herein and will grant access via an attribute.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.verbosity","title":"verbosity: int property","text":"

The verbosity level of the application, with 0 as the default.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.abort","title":"abort(message: str = '', code: int = 1, **kwargs: Any) -> None","text":"

Terminate the program with the given return code.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_debug","title":"display_debug(message: str = '', level: int = 1, **kwargs: Any) -> None","text":"

Meant to be used for messages that are not useful for most user experiences. The level option must be between 1 and 3 (inclusive).

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_error","title":"display_error(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages indicating some unrecoverable error.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_info","title":"display_info(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages conveying basic information.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_success","title":"display_success(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages indicating some positive outcome.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_waiting","title":"display_waiting(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages shown before potentially time consuming operations.

"},{"location":"plugins/utilities/#hatchling.bridge.app.Application.display_warning","title":"display_warning(message: str = '', **kwargs: Any) -> None","text":"

Meant to be used for messages conveying important information.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform","title":"Platform","text":""},{"location":"plugins/utilities/#hatch.utils.platform.Platform.default_shell","title":"default_shell: str property","text":"

Returns the default shell of the system.

On Windows systems first try the SHELL environment variable, if present, followed by the COMSPEC environment variable, defaulting to cmd. On all other platforms only the SHELL environment variable will be used, defaulting to bash.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.modules","title":"modules: LazilyLoadedModules property","text":"

Accessor for lazily loading modules that either take multiple milliseconds to import (like shutil and subprocess) or are not used on all platforms (like shlex).

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.home","title":"home: Path property","text":"

The user's home directory as a path-like object.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.name","title":"name: str property","text":"

One of the following:

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.windows","title":"windows: bool property","text":"

Indicates whether Hatch is running on Windows.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.macos","title":"macos: bool property","text":"

Indicates whether Hatch is running on macOS.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.linux","title":"linux: bool property","text":"

Indicates whether Hatch is running on neither Windows nor macOS.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.format_for_subprocess","title":"format_for_subprocess(command: str | list[str], *, shell: bool) -> str | list[str]","text":"

Format the given command in a cross-platform manner for immediate consumption by subprocess utilities.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.run_command","title":"run_command(command: str | list[str], *, shell: bool = False, **kwargs: Any) -> CompletedProcess","text":"

Equivalent to the standard library's subprocess.run, with the command first being properly formatted.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.check_command","title":"check_command(command: str | list[str], *, shell: bool = False, **kwargs: Any) -> CompletedProcess","text":"

Equivalent to run_command, but non-zero exit codes will gracefully end program execution.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.check_command_output","title":"check_command_output(command: str | list[str], *, shell: bool = False, **kwargs: Any) -> str","text":"

Equivalent to the output from the process returned by capture_process, but non-zero exit codes will gracefully end program execution.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.capture_process","title":"capture_process(command: str | list[str], *, shell: bool = False, **kwargs: Any) -> Popen","text":"

Equivalent to the standard library's subprocess.Popen, with all output captured by stdout and the command first being properly formatted.

"},{"location":"plugins/utilities/#hatch.utils.platform.Platform.exit_with_command","title":"exit_with_command(command: list[str]) -> None","text":"

Run the given command and exit with its exit code. On non-Windows systems, this uses the standard library's os.execvp.

"},{"location":"plugins/utilities/#hatch.env.context.EnvironmentContextFormatter","title":"EnvironmentContextFormatter","text":""},{"location":"plugins/utilities/#hatch.env.context.EnvironmentContextFormatter.formatters","title":"formatters()","text":"

This returns a mapping of supported field names to their respective formatting functions. Each function accepts 2 arguments:

"},{"location":"plugins/build-hook/custom/","title":"Custom build hook","text":"

This is a custom class in a given Python file that inherits from the BuildHookInterface.

"},{"location":"plugins/build-hook/custom/#configuration","title":"Configuration","text":"

The build hook plugin name is custom.

pyproject.toml hatch.toml
[tool.hatch.build.hooks.custom]\n[tool.hatch.build.targets.<TARGET_NAME>.hooks.custom]\n
[build.hooks.custom]\n[build.targets.<TARGET_NAME>.hooks.custom]\n
"},{"location":"plugins/build-hook/custom/#options","title":"Options","text":"Option Default Description path hatch_build.py The path of the Python file"},{"location":"plugins/build-hook/custom/#example","title":"Example","text":"hatch_build.py
from hatchling.builders.hooks.plugin.interface import BuildHookInterface\n\n\nclass CustomBuildHook(BuildHookInterface):\n    ...\n

If multiple subclasses are found, you must define a function named get_build_hook that returns the desired build hook.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

"},{"location":"plugins/build-hook/reference/","title":"Build hook plugins","text":"

A build hook provides code that will be executed at various stages of the build process. See the documentation for build hook configuration.

"},{"location":"plugins/build-hook/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/build-hook/reference/#overview","title":"Overview","text":"

Build hooks run for every selected version of build targets.

The initialization stage occurs immediately before each build and the finalization stage occurs immediately after. Each stage has the opportunity to view or modify build data.

"},{"location":"plugins/build-hook/reference/#build-data","title":"Build data","text":"

Build data is a simple mapping whose contents can influence the behavior of builds. Which fields exist and are recognized depends on each build target.

The following fields are always present and recognized by the build system itself:

Field Type Description artifacts list[str] This is a list of extra artifact patterns and should generally only be appended to force_include dict[str, str] This is a mapping of extra forced inclusion paths, with this mapping taking precedence in case of conflicts build_hooks tuple[str, ...] This is an immutable sequence of the names of the configured build hooks and matches the order in which they run

Attention

While user-facing TOML options are hyphenated, build data fields should be named with underscores to allow plugins to use them as valid Python identifiers.

"},{"location":"plugins/build-hook/reference/#notes","title":"Notes","text":"

In some cases it may be necessary to use force_include rather than artifacts. For example, say that you want to install a lib.so directly at the root of site-packages and a project defines a package src/foo. If you create src/lib.so, there will never be a match because the directory traversal starts at src/foo rather than src. In that case you must do either:

build_data['force_include']['src/lib.so'] = 'src/lib.so'\n

or

build_data['force_include']['/absolute/path/to/src/lib.so'] = 'src/lib.so'\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface","title":"BuildHookInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.builders.hooks.plugin.interface import BuildHookInterface\n\n\nclass SpecialBuildHook(BuildHookInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialBuildHook\n\n\n@hookimpl\ndef hatch_register_build_hook():\n    return SpecialBuildHook\n
Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
class BuildHookInterface(Generic[BuilderConfigBound]):  # no cov\n\"\"\"\n    Example usage:\n    ```python tab=\"plugin.py\"\n    from hatchling.builders.hooks.plugin.interface import BuildHookInterface\n    class SpecialBuildHook(BuildHookInterface):\n        PLUGIN_NAME = 'special'\n        ...\n    ```\n    ```python tab=\"hooks.py\"\n    from hatchling.plugin import hookimpl\n    from .plugin import SpecialBuildHook\n    @hookimpl\n    def hatch_register_build_hook():\n        return SpecialBuildHook\n    ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(\nself,\nroot: str,\nconfig: dict[str, Any],\nbuild_config: BuilderConfigBound,\nmetadata: ProjectMetadata,\ndirectory: str,\ntarget_name: str,\napp: Application | None = None,\n) -> None:\nself.__root = root\nself.__config = config\nself.__build_config = build_config\nself.__metadata = metadata\nself.__directory = directory\nself.__target_name = target_name\nself.__app = app\n@property\ndef app(self) -> Application:\n\"\"\"\n        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).\n        \"\"\"\nif self.__app is None:\nfrom hatchling.bridge.app import Application\nself.__app = cast(Application, Application().get_safe_application())\nreturn self.__app\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict[str, Any]:\n\"\"\"\n        The cumulative hook configuration.\n        ```toml config-example\n        [tool.hatch.build.hooks.<PLUGIN_NAME>]\n        [tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]\n        ```\n        \"\"\"\nreturn self.__config\n@property\ndef metadata(self) -> ProjectMetadata:\n# Undocumented for now\nreturn self.__metadata\n@property\ndef build_config(self) -> BuilderConfigBound:\n\"\"\"\n        An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).\n        \"\"\"\nreturn self.__build_config\n@property\ndef directory(self) -> str:\n\"\"\"\n        The build directory.\n        \"\"\"\nreturn self.__directory\n@property\ndef target_name(self) -> str:\n\"\"\"\n        The plugin name of the build target.\n        \"\"\"\nreturn self.__target_name\ndef clean(self, versions: list[str]) -> None:\n\"\"\"\n        This occurs before the build process if the `-c`/`--clean` flag was passed to\n        the [`build`](../../cli/reference.md#hatch-build) command, or when invoking\n        the [`clean`](../../cli/reference.md#hatch-clean) command.\n        \"\"\"\ndef initialize(self, version: str, build_data: dict[str, Any]) -> None:\n\"\"\"\n        This occurs immediately before each build.\n        Any modifications to the build data will be seen by the build target.\n        \"\"\"\ndef finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:\n\"\"\"\n        This occurs immediately after each build and will not run if the `--hooks-only` flag\n        was passed to the [`build`](../../cli/reference.md#hatch-build) command.\n        The build data will reflect any modifications done by the target during the build.\n        \"\"\"\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.app","title":"app: Application property","text":"

An instance of Application.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.root","title":"root: str property","text":"

The root of the project tree.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.config","title":"config: dict[str, Any] property","text":"

The cumulative hook configuration.

pyproject.toml hatch.toml
[tool.hatch.build.hooks.<PLUGIN_NAME>]\n[tool.hatch.build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]\n
[build.hooks.<PLUGIN_NAME>]\n[build.targets.<TARGET_NAME>.hooks.<PLUGIN_NAME>]\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.build_config","title":"build_config: BuilderConfigBound property","text":"

An instance of BuilderConfig.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.target_name","title":"target_name: str property","text":"

The plugin name of the build target.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.directory","title":"directory: str property","text":"

The build directory.

"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.clean","title":"clean(versions: list[str]) -> None","text":"

This occurs before the build process if the -c/--clean flag was passed to the build command, or when invoking the clean command.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def clean(self, versions: list[str]) -> None:\n\"\"\"\n    This occurs before the build process if the `-c`/`--clean` flag was passed to\n    the [`build`](../../cli/reference.md#hatch-build) command, or when invoking\n    the [`clean`](../../cli/reference.md#hatch-clean) command.\n    \"\"\"\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.initialize","title":"initialize(version: str, build_data: dict[str, Any]) -> None","text":"

This occurs immediately before each build.

Any modifications to the build data will be seen by the build target.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def initialize(self, version: str, build_data: dict[str, Any]) -> None:\n\"\"\"\n    This occurs immediately before each build.\n    Any modifications to the build data will be seen by the build target.\n    \"\"\"\n
"},{"location":"plugins/build-hook/reference/#hatchling.builders.hooks.plugin.interface.BuildHookInterface.finalize","title":"finalize(version: str, build_data: dict[str, Any], artifact_path: str) -> None","text":"

This occurs immediately after each build and will not run if the --hooks-only flag was passed to the build command.

The build data will reflect any modifications done by the target during the build.

Source code in backend/src/hatchling/builders/hooks/plugin/interface.py
def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:\n\"\"\"\n    This occurs immediately after each build and will not run if the `--hooks-only` flag\n    was passed to the [`build`](../../cli/reference.md#hatch-build) command.\n    The build data will reflect any modifications done by the target during the build.\n    \"\"\"\n
"},{"location":"plugins/build-hook/version/","title":"Version build hook","text":"

This writes the project's version to a file.

"},{"location":"plugins/build-hook/version/#configuration","title":"Configuration","text":"

The build hook plugin name is version.

pyproject.toml hatch.toml
[tool.hatch.build.hooks.version]\n[tool.hatch.build.targets.<TARGET_NAME>.hooks.version]\n
[build.hooks.version]\n[build.targets.<TARGET_NAME>.hooks.version]\n
"},{"location":"plugins/build-hook/version/#options","title":"Options","text":"Option Description path (required) A relative path to the desired file template A string representing the entire contents of path that will be formatted with a version variable pattern Rather than updating the entire file, a regular expression may be used that has a named group called version that represents the version. If set to true, a pattern will be used that looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v."},{"location":"plugins/builder/app/","title":"Application builder","text":"

This uses PyApp to build an application that is able to bootstrap itself at runtime.

Note

This requires an installation of Rust.

"},{"location":"plugins/builder/app/#configuration","title":"Configuration","text":"

The builder plugin name is app.

pyproject.toml hatch.toml
[tool.hatch.build.targets.app]\n
[build.targets.app]\n
"},{"location":"plugins/builder/app/#options","title":"Options","text":"Option Default Description scripts all defined An array of defined script names to limit what gets built python-version latest compatible Python minor version The Python version ID to use pyapp-version The version of PyApp to use"},{"location":"plugins/builder/app/#build-behavior","title":"Build behavior","text":"

If any scripts are defined then each one will be built (limited by the scripts option). Otherwise, a single executable will be built based on the project name assuming there is an equivalently named module with a __main__.py file.

Every executable will be built inside an app directory in the output directory.

If the CARGO environment variable is set then that path will be used as the executable for performing builds.

If the CARGO_BUILD_TARGET environment variable is set then its value will be appended to the file name stems.

If the PYAPP_REPO environment variable is set then a local build will be performed inside that directory rather than installing from crates.io. Note that this is required if the CARGO environment variable refers to cross.

"},{"location":"plugins/builder/custom/","title":"Custom builder","text":"

This is a custom class in a given Python file that inherits from the BuilderInterface.

"},{"location":"plugins/builder/custom/#configuration","title":"Configuration","text":"

The builder plugin name is custom.

pyproject.toml hatch.toml
[tool.hatch.build.targets.custom]\n
[build.targets.custom]\n
"},{"location":"plugins/builder/custom/#options","title":"Options","text":"Option Default Description path hatch_build.py The path of the Python file"},{"location":"plugins/builder/custom/#example","title":"Example","text":"hatch_build.py
from hatchling.builders.plugin.interface import BuilderInterface\n\n\nclass CustomBuilder(BuilderInterface):\n    ...\n

If multiple subclasses are found, you must define a function named get_builder that returns the desired builder.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

"},{"location":"plugins/builder/reference/","title":"Builder plugins","text":"

See the documentation for build configuration.

"},{"location":"plugins/builder/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface","title":"BuilderInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.builders.plugin.interface import BuilderInterface\n\n\nclass SpecialBuilder(BuilderInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialBuilder\n\n\n@hookimpl\ndef hatch_register_builder():\n    return SpecialBuilder\n
Source code in backend/src/hatchling/builders/plugin/interface.py
class BuilderInterface(ABC, Generic[BuilderConfigBound, PluginManagerBound]):\n\"\"\"\n    Example usage:\n    ```python tab=\"plugin.py\"\n    from hatchling.builders.plugin.interface import BuilderInterface\n    class SpecialBuilder(BuilderInterface):\n        PLUGIN_NAME = 'special'\n        ...\n    ```\n    ```python tab=\"hooks.py\"\n    from hatchling.plugin import hookimpl\n    from .plugin import SpecialBuilder\n    @hookimpl\n    def hatch_register_builder():\n        return SpecialBuilder\n    ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(\nself,\nroot: str,\nplugin_manager: PluginManagerBound | None = None,\nconfig: dict[str, Any] | None = None,\nmetadata: ProjectMetadata | None = None,\napp: Application | None = None,\n) -> None:\nself.__root = root\nself.__plugin_manager = cast(PluginManagerBound, plugin_manager)\nself.__raw_config = config\nself.__metadata = metadata\nself.__app = app\nself.__config = cast(BuilderConfigBound, None)\nself.__project_config: dict[str, Any] | None = None\nself.__hatch_config: dict[str, Any] | None = None\nself.__build_config: dict[str, Any] | None = None\nself.__build_targets: list[str] | None = None\nself.__target_config: dict[str, Any] | None = None\n# Metadata\nself.__project_id: str | None = None\ndef build(\nself,\ndirectory: str | None = None,\nversions: list[str] | None = None,\nhooks_only: bool | None = None,\nclean: bool | None = None,\nclean_hooks_after: bool | None = None,\nclean_only: bool | None = False,  # noqa: FBT002\n) -> Generator[str, None, None]:\n# Fail early for invalid project metadata\nself.metadata.validate_fields()\nif directory is None:\ndirectory = (\nself.config.normalize_build_directory(os.environ[BuildEnvVars.LOCATION])\nif BuildEnvVars.LOCATION in os.environ\nelse self.config.directory\n)\nif not os.path.isdir(directory):\nos.makedirs(directory)\nversion_api = self.get_version_api()\nversions = versions or self.config.versions\nif versions:\nunknown_versions = set(versions) - set(version_api)\nif unknown_versions:\nmessage = (\nf'Unknown versions for target `{self.PLUGIN_NAME}`: {\", \".join(map(str, sorted(unknown_versions)))}'\n)\nraise ValueError(message)\nif hooks_only is None:\nhooks_only = env_var_enabled(BuildEnvVars.HOOKS_ONLY)\nconfigured_build_hooks = self.get_build_hooks(directory)\nbuild_hooks = list(configured_build_hooks.values())\nif clean_only:\nclean = True\nelif clean is None:\nclean = env_var_enabled(BuildEnvVars.CLEAN)\nif clean:\nif not hooks_only:\nself.clean(directory, versions)\nfor build_hook in build_hooks:\nbuild_hook.clean(versions)\nif clean_only:\nreturn\nif clean_hooks_after is None:\nclean_hooks_after = env_var_enabled(BuildEnvVars.CLEAN_HOOKS_AFTER)\nfor version in versions:\nself.app.display_debug(f'Building `{self.PLUGIN_NAME}` version `{version}`')\nbuild_data = self.get_default_build_data()\nself.set_build_data_defaults(build_data)\n# Allow inspection of configured build hooks and the order in which they run\nbuild_data['build_hooks'] = tuple(configured_build_hooks)\n# Execute all `initialize` build hooks\nfor build_hook in build_hooks:\nbuild_hook.initialize(version, build_data)\nif hooks_only:\nself.app.display_debug(f'Only ran build hooks for `{self.PLUGIN_NAME}` version `{version}`')\ncontinue\n# Build the artifact\nwith self.config.set_build_data(build_data):\nartifact = version_api[version](directory, **build_data)\n# Execute all `finalize` build hooks\nfor build_hook in build_hooks:\nbuild_hook.finalize(version, build_data, artifact)\nif clean_hooks_after:\nfor build_hook in build_hooks:\nbuild_hook.clean([version])\nyield artifact\ndef recurse_included_files(self) -> Iterable[IncludedFile]:\n\"\"\"\n        Returns a consistently generated series of file objects for every file that should be distributed. Each file\n        object has three `str` attributes:\n        - `path` - the absolute path\n        - `relative_path` - the path relative to the project root; will be an empty string for external files\n        - `distribution_path` - the path to be distributed as\n        \"\"\"\nyield from self.recurse_selected_project_files()\nyield from self.recurse_forced_files(self.config.get_force_include())\ndef recurse_selected_project_files(self) -> Iterable[IncludedFile]:\nif self.config.only_include:\nyield from self.recurse_explicit_files(self.config.only_include)\nelse:\nyield from self.recurse_project_files()\ndef recurse_project_files(self) -> Iterable[IncludedFile]:\nfor root, dirs, files in safe_walk(self.root):\nrelative_path = get_relative_path(root, self.root)\ndirs[:] = sorted(d for d in dirs if not self.config.directory_is_excluded(d, relative_path))\nfiles.sort()\nis_package = '__init__.py' in files\nfor f in files:\nrelative_file_path = os.path.join(relative_path, f)\nif self.config.include_path(relative_file_path, is_package=is_package):\nyield IncludedFile(\nos.path.join(root, f), relative_file_path, self.config.get_distribution_path(relative_file_path)\n)\ndef recurse_forced_files(self, inclusion_map: dict[str, str]) -> Iterable[IncludedFile]:\nfor source, target_path in inclusion_map.items():\nexternal = not source.startswith(self.root)\nif os.path.isfile(source):\nyield IncludedFile(\nsource,\n'' if external else os.path.relpath(source, self.root),\nself.config.get_distribution_path(target_path),\n)\nelif os.path.isdir(source):\nfor root, dirs, files in safe_walk(source):\nrelative_directory = get_relative_path(root, source)\ndirs[:] = sorted(d for d in dirs if d not in EXCLUDED_DIRECTORIES)\nfiles.sort()\nfor f in files:\nrelative_file_path = os.path.join(target_path, relative_directory, f)\nif not self.config.path_is_reserved(relative_file_path):\nyield IncludedFile(\nos.path.join(root, f),\n'' if external else relative_file_path,\nself.config.get_distribution_path(relative_file_path),\n)\ndef recurse_explicit_files(self, inclusion_map: dict[str, str]) -> Iterable[IncludedFile]:\nfor source, target_path in inclusion_map.items():\nexternal = not source.startswith(self.root)\nif os.path.isfile(source):\nyield IncludedFile(\nsource,\n'' if external else os.path.relpath(source, self.root),\nself.config.get_distribution_path(target_path),\n)\nelif os.path.isdir(source):\nfor root, dirs, files in safe_walk(source):\nrelative_directory = get_relative_path(root, source)\ndirs[:] = sorted(d for d in dirs if d not in EXCLUDED_DIRECTORIES)\nfiles.sort()\nis_package = '__init__.py' in files\nfor f in files:\nrelative_file_path = os.path.join(target_path, relative_directory, f)\nif self.config.include_path(relative_file_path, explicit=True, is_package=is_package):\nyield IncludedFile(\nos.path.join(root, f),\n'' if external else relative_file_path,\nself.config.get_distribution_path(relative_file_path),\n)\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree.\n        \"\"\"\nreturn self.__root\n@property\ndef plugin_manager(self) -> PluginManagerBound:\nif self.__plugin_manager is None:\nfrom hatchling.plugin.manager import PluginManager\nself.__plugin_manager = PluginManager()\nreturn self.__plugin_manager\n@property\ndef metadata(self) -> ProjectMetadata:\nif self.__metadata is None:\nfrom hatchling.metadata.core import ProjectMetadata\nself.__metadata = ProjectMetadata(self.root, self.plugin_manager, self.__raw_config)\nreturn self.__metadata\n@property\ndef app(self) -> Application:\n\"\"\"\n        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).\n        \"\"\"\nif self.__app is None:\nfrom hatchling.bridge.app import Application\nself.__app = cast(Application, Application().get_safe_application())\nreturn self.__app\n@property\ndef raw_config(self) -> dict[str, Any]:\nif self.__raw_config is None:\nself.__raw_config = self.metadata.config\nreturn self.__raw_config\n@property\ndef project_config(self) -> dict[str, Any]:\nif self.__project_config is None:\nself.__project_config = self.metadata.core.config\nreturn self.__project_config\n@property\ndef hatch_config(self) -> dict[str, Any]:\nif self.__hatch_config is None:\nself.__hatch_config = self.metadata.hatch.config\nreturn self.__hatch_config\n@property\ndef config(self) -> BuilderConfigBound:\n\"\"\"\n        An instance of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).\n        \"\"\"\nif self.__config is None:\nself.__config = self.get_config_class()(\nself, self.root, self.PLUGIN_NAME, self.build_config, self.target_config\n)\nreturn self.__config\n@property\ndef build_config(self) -> dict[str, Any]:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.build]\n        ```\n        \"\"\"\nif self.__build_config is None:\nself.__build_config = self.metadata.hatch.build_config\nreturn self.__build_config\n@property\ndef target_config(self) -> dict[str, Any]:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.build.targets.<PLUGIN_NAME>]\n        ```\n        \"\"\"\nif self.__target_config is None:\ntarget_config: dict[str, Any] = self.metadata.hatch.build_targets.get(self.PLUGIN_NAME, {})\nif not isinstance(target_config, dict):\nmessage = f'Field `tool.hatch.build.targets.{self.PLUGIN_NAME}` must be a table'\nraise TypeError(message)\nself.__target_config = target_config\nreturn self.__target_config\n@property\ndef project_id(self) -> str:\nif self.__project_id is None:\nself.__project_id = f'{self.normalize_file_name_component(self.metadata.core.name)}-{self.metadata.version}'\nreturn self.__project_id\ndef get_build_hooks(self, directory: str) -> dict[str, BuildHookInterface]:\nconfigured_build_hooks = {}\nfor hook_name, config in self.config.hook_config.items():\nbuild_hook = self.plugin_manager.build_hook.get(hook_name)\nif build_hook is None:\nfrom hatchling.plugin.exceptions import UnknownPluginError\nmessage = f'Unknown build hook: {hook_name}'\nraise UnknownPluginError(message)\nconfigured_build_hooks[hook_name] = build_hook(\nself.root, config, self.config, self.metadata, directory, self.PLUGIN_NAME, self.app\n)\nreturn configured_build_hooks\n@abstractmethod\ndef get_version_api(self) -> dict[str, Callable]:\n\"\"\"\n        A mapping of `str` versions to a callable that is used for building.\n        Each callable must have the following signature:\n        ```python\n        def ...(build_dir: str, build_data: dict) -> str:\n        ```\n        The return value must be the absolute path to the built artifact.\n        \"\"\"\ndef get_default_versions(self) -> list[str]:\n\"\"\"\n        A list of versions to build when users do not specify any, defaulting to all versions.\n        \"\"\"\nreturn list(self.get_version_api())\ndef get_default_build_data(self) -> dict[str, Any]:\n\"\"\"\n        A mapping that can be modified by [build hooks](../build-hook/reference.md) to influence the behavior of builds.\n        \"\"\"\nreturn {}\ndef set_build_data_defaults(self, build_data: dict[str, Any]) -> None:\nbuild_data.setdefault('artifacts', [])\nbuild_data.setdefault('force_include', {})\ndef clean(self, directory: str, versions: list[str]) -> None:\n\"\"\"\n        Called before builds if the `-c`/`--clean` flag was passed to the\n        [`build`](../../cli/reference.md#hatch-build) command.\n        \"\"\"\n@classmethod\ndef get_config_class(cls) -> type[BuilderConfig]:\n\"\"\"\n        Must return a subclass of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).\n        \"\"\"\nreturn BuilderConfig\n@staticmethod\ndef normalize_file_name_component(file_name: str) -> str:\n\"\"\"\n        https://peps.python.org/pep-0427/#escaping-and-unicode\n        \"\"\"\nreturn re.sub(r'[^\\w\\d.]+', '_', file_name, re.UNICODE)\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.app","title":"app: Application property","text":"

An instance of Application.

"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.root","title":"root: str property","text":"

The root of the project tree.

"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.build_config","title":"build_config: dict[str, Any] property","text":"pyproject.toml hatch.toml
[tool.hatch.build]\n
[build]\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.target_config","title":"target_config: dict[str, Any] property","text":"pyproject.toml hatch.toml
[tool.hatch.build.targets.<PLUGIN_NAME>]\n
[build.targets.<PLUGIN_NAME>]\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.config","title":"config: BuilderConfigBound property","text":"

An instance of BuilderConfig.

"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.get_config_class","title":"get_config_class() -> type[BuilderConfig] classmethod","text":"

Must return a subclass of BuilderConfig.

Source code in backend/src/hatchling/builders/plugin/interface.py
@classmethod\ndef get_config_class(cls) -> type[BuilderConfig]:\n\"\"\"\n    Must return a subclass of [BuilderConfig](../utilities.md#hatchling.builders.config.BuilderConfig).\n    \"\"\"\nreturn BuilderConfig\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.get_version_api","title":"get_version_api() -> dict[str, Callable] abstractmethod","text":"

A mapping of str versions to a callable that is used for building. Each callable must have the following signature:

def ...(build_dir: str, build_data: dict) -> str:\n

The return value must be the absolute path to the built artifact.

Source code in backend/src/hatchling/builders/plugin/interface.py
@abstractmethod\ndef get_version_api(self) -> dict[str, Callable]:\n\"\"\"\n    A mapping of `str` versions to a callable that is used for building.\n    Each callable must have the following signature:\n    ```python\n    def ...(build_dir: str, build_data: dict) -> str:\n    ```\n    The return value must be the absolute path to the built artifact.\n    \"\"\"\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.get_default_versions","title":"get_default_versions() -> list[str]","text":"

A list of versions to build when users do not specify any, defaulting to all versions.

Source code in backend/src/hatchling/builders/plugin/interface.py
def get_default_versions(self) -> list[str]:\n\"\"\"\n    A list of versions to build when users do not specify any, defaulting to all versions.\n    \"\"\"\nreturn list(self.get_version_api())\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.clean","title":"clean(directory: str, versions: list[str]) -> None","text":"

Called before builds if the -c/--clean flag was passed to the build command.

Source code in backend/src/hatchling/builders/plugin/interface.py
def clean(self, directory: str, versions: list[str]) -> None:\n\"\"\"\n    Called before builds if the `-c`/`--clean` flag was passed to the\n    [`build`](../../cli/reference.md#hatch-build) command.\n    \"\"\"\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.recurse_included_files","title":"recurse_included_files() -> Iterable[IncludedFile]","text":"

Returns a consistently generated series of file objects for every file that should be distributed. Each file object has three str attributes:

Source code in backend/src/hatchling/builders/plugin/interface.py
def recurse_included_files(self) -> Iterable[IncludedFile]:\n\"\"\"\n    Returns a consistently generated series of file objects for every file that should be distributed. Each file\n    object has three `str` attributes:\n    - `path` - the absolute path\n    - `relative_path` - the path relative to the project root; will be an empty string for external files\n    - `distribution_path` - the path to be distributed as\n    \"\"\"\nyield from self.recurse_selected_project_files()\nyield from self.recurse_forced_files(self.config.get_force_include())\n
"},{"location":"plugins/builder/reference/#hatchling.builders.plugin.interface.BuilderInterface.get_default_build_data","title":"get_default_build_data() -> dict[str, Any]","text":"

A mapping that can be modified by build hooks to influence the behavior of builds.

Source code in backend/src/hatchling/builders/plugin/interface.py
def get_default_build_data(self) -> dict[str, Any]:\n\"\"\"\n    A mapping that can be modified by [build hooks](../build-hook/reference.md) to influence the behavior of builds.\n    \"\"\"\nreturn {}\n
"},{"location":"plugins/builder/sdist/","title":"Source distribution builder","text":"

A source distribution, or sdist, is an archive of Python \"source code\". Although largely unspecified, by convention it should include everything that is required to build a wheel without making network requests.

"},{"location":"plugins/builder/sdist/#configuration","title":"Configuration","text":"

The builder plugin name is sdist.

pyproject.toml hatch.toml
[tool.hatch.build.targets.sdist]\n
[build.targets.sdist]\n
"},{"location":"plugins/builder/sdist/#options","title":"Options","text":"Option Default Description core-metadata-version \"2.1\" The version of core metadata to use strict-naming true Whether or not file names should contain the normalized version of the project name support-legacy false Whether or not to include a setup.py file to support legacy installation mechanisms"},{"location":"plugins/builder/sdist/#versions","title":"Versions","text":"Version Description standard (default) The latest conventional format"},{"location":"plugins/builder/sdist/#default-file-selection","title":"Default file selection","text":"

When the user has not set any file selection options, all files that are not ignored by your VCS will be included.

Note

The following files are always included and cannot be excluded:

"},{"location":"plugins/builder/sdist/#reproducibility","title":"Reproducibility","text":"

Reproducible builds are supported.

"},{"location":"plugins/builder/sdist/#build-data","title":"Build data","text":"

This is data that can be modified by build hooks.

Data Default Description dependencies Extra project dependencies"},{"location":"plugins/builder/wheel/","title":"Wheel builder","text":"

A wheel is a binary distribution of a Python package that can be installed directly into an environment.

"},{"location":"plugins/builder/wheel/#configuration","title":"Configuration","text":"

The builder plugin name is wheel.

pyproject.toml hatch.toml
[tool.hatch.build.targets.wheel]\n
[build.targets.wheel]\n
"},{"location":"plugins/builder/wheel/#options","title":"Options","text":"Option Default Description core-metadata-version \"2.1\" The version of core metadata to use shared-data A mapping similar to the forced inclusion option corresponding to data that will be installed globally in a given Python environment, usually under sys.prefix extra-metadata A mapping similar to the forced inclusion option corresponding to extra metadata that will be shipped in a directory named extra_metadata strict-naming true Whether or not file names should contain the normalized version of the project name macos-max-compat true Whether or not on macOS, when build hooks have set the infer_tag build data, the wheel name should signal broad support rather than specific versions for newer SDK versions.Note: The default will become false, and this option eventually removed, sometime after consumers like pip start supporting these newer SDK versions."},{"location":"plugins/builder/wheel/#versions","title":"Versions","text":"Version Description standard (default) The latest standardized format editable A wheel that only ships .pth files or import hooks for real-time development"},{"location":"plugins/builder/wheel/#default-file-selection","title":"Default file selection","text":"

When the user has not set any file selection options, the project name will be used to determine the package to ship in the following heuristic order:

  1. <NAME>/__init__.py
  2. src/<NAME>/__init__.py
  3. <NAME>.py
  4. <NAMESPACE>/<NAME>/__init__.py
  5. Otherwise, every Python package and file that does not start with the word test will be included
"},{"location":"plugins/builder/wheel/#reproducibility","title":"Reproducibility","text":"

Reproducible builds are supported.

"},{"location":"plugins/builder/wheel/#build-data","title":"Build data","text":"

This is data that can be modified by build hooks.

Data Default Description tag The full tag part of the filename (e.g. py3-none-any), defaulting to a cross-platform wheel with the supported major versions of Python based on project metadata infer_tag False When tag is not set, this may be enabled to use the one most specific to the platform, Python interpreter, and ABI pure_python True Whether or not to write metadata indicating that the package does not contain any platform-specific files dependencies Extra project dependencies extra_metadata Additional extra-metadata entries, which take precedence in case of conflicts force_include_editable Similar to the force_include option but specifically for the editable version and takes precedence"},{"location":"plugins/environment/reference/","title":"Environment plugins","text":"

See the documentation for environment configuration.

"},{"location":"plugins/environment/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/environment/reference/#installation","title":"Installation","text":"

Any required environment types that are not built-in must be manually installed alongside Hatch or listed in the tool.hatch.env.requires array for automatic management:

pyproject.toml hatch.toml
[tool.hatch.env]\nrequires = [\n\"...\",\n]\n
[env]\nrequires = [\n\"...\",\n]\n
"},{"location":"plugins/environment/reference/#life-cycle","title":"Life cycle","text":"

Whenever an environment is used, the following logic is performed:

Source code in src/hatch/cli/application.py
def prepare_environment(self, environment):\nif not environment.exists():\nwith self.status(f'Creating environment: {environment.name}'):\nenvironment.create()\nif not environment.skip_install:\nif environment.pre_install_commands:\nwith self.status('Running pre-installation commands'):\nself.run_shell_commands(environment, environment.pre_install_commands, source='pre-install')\nif environment.dev_mode:\nwith self.status('Installing project in development mode'):\nenvironment.install_project_dev_mode()\nelse:\nwith self.status('Installing project'):\nenvironment.install_project()\nif environment.post_install_commands:\nwith self.status('Running post-installation commands'):\nself.run_shell_commands(environment, environment.post_install_commands, source='post-install')\nwith self.status('Checking dependencies'):\ndependencies_in_sync = environment.dependencies_in_sync()\nif not dependencies_in_sync:\nwith self.status('Syncing dependencies'):\nenvironment.sync_dependencies()\n
"},{"location":"plugins/environment/reference/#build-environments","title":"Build environments","text":"

All environment types should offer support for a special sub-environment in which projects can be built. This environment is used in the following scenarios:

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface","title":"EnvironmentInterface","text":"

Example usage:

plugin.py hooks.py
    from hatch.env.plugin.interface import EnvironmentInterface\n\n\n    class SpecialEnvironment(EnvironmentInterface):\n        PLUGIN_NAME = 'special'\n        ...\n
    from hatchling.plugin import hookimpl\n\n    from .plugin import SpecialEnvironment\n\n\n    @hookimpl\n    def hatch_register_environment():\n        return SpecialEnvironment\n
Source code in src/hatch/env/plugin/interface.py
class EnvironmentInterface(ABC):\n\"\"\"\n    Example usage:\n    ```python tab=\"plugin.py\"\n        from hatch.env.plugin.interface import EnvironmentInterface\n        class SpecialEnvironment(EnvironmentInterface):\n            PLUGIN_NAME = 'special'\n            ...\n    ```\n    ```python tab=\"hooks.py\"\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialEnvironment\n        @hookimpl\n        def hatch_register_environment():\n            return SpecialEnvironment\n    ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(\nself,\nroot,\nmetadata,\nname,\nconfig,\nmatrix_variables,\ndata_directory,\nisolated_data_directory,\nplatform,\nverbosity,\napp=None,\n):\nself.__root = root\nself.__metadata = metadata\nself.__name = name\nself.__config = config\nself.__matrix_variables = matrix_variables\nself.__data_directory = data_directory\nself.__isolated_data_directory = isolated_data_directory\nself.__platform = platform\nself.__verbosity = verbosity\nself.__app = app\nself.__context = None\nself._system_python = None\nself._env_vars = None\nself._env_include = None\nself._env_exclude = None\nself._environment_dependencies_complex = None\nself._environment_dependencies = None\nself._dependencies_complex = None\nself._dependencies = None\nself._platforms = None\nself._skip_install = None\nself._dev_mode = None\nself._features = None\nself._description = None\nself._scripts = None\nself._pre_install_commands = None\nself._post_install_commands = None\n@property\ndef matrix_variables(self):\nreturn self.__matrix_variables\n@property\ndef app(self):\n\"\"\"\n        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).\n        \"\"\"\nif self.__app is None:\nfrom hatchling.bridge.app import Application\nself.__app = Application().get_safe_application()\nreturn self.__app\n@property\ndef context(self):\nif self.__context is None:\nself.__context = self.get_context()\nreturn self.__context\n@property\ndef verbosity(self):\nreturn self.__verbosity\n@property\ndef root(self):\n\"\"\"\n        The root of the project tree as a path-like object.\n        \"\"\"\nreturn self.__root\n@property\ndef metadata(self):\nreturn self.__metadata\n@property\ndef name(self) -> str:\n\"\"\"\n        The name of the environment.\n        \"\"\"\nreturn self.__name\n@property\ndef platform(self):\n\"\"\"\n        An instance of [Platform](../utilities.md#hatch.utils.platform.Platform).\n        \"\"\"\nreturn self.__platform\n@property\ndef data_directory(self):\n\"\"\"\n        The [directory](../../config/hatch.md#environments) this plugin should use for storage as a path-like object.\n        If the user has not configured one then this will be the same as the\n        [isolated data directory](reference.md#hatch.env.plugin.interface.EnvironmentInterface.isolated_data_directory).\n        \"\"\"\nreturn self.__data_directory\n@property\ndef isolated_data_directory(self):\n\"\"\"\n        The default [directory](../../config/hatch.md#environments) reserved exclusively for this plugin as a path-like\n        object.\n        \"\"\"\nreturn self.__isolated_data_directory\n@property\ndef config(self) -> dict:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.envs.<ENV_NAME>]\n        ```\n        \"\"\"\nreturn self.__config\n@property\ndef system_python(self):\nif self._system_python is None:\nsystem_python = os.environ.get(AppEnvVars.PYTHON)\nif system_python == 'self':\nsystem_python = sys.executable\nsystem_python = (\nsystem_python\nor self.platform.modules.shutil.which('python')\nor self.platform.modules.shutil.which('python3')\nor sys.executable\n)\nif not isabs(system_python):\nsystem_python = self.platform.modules.shutil.which(system_python)\nself._system_python = system_python\nreturn self._system_python\n@property\ndef env_vars(self) -> dict:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.envs.<ENV_NAME>.env-vars]\n        ```\n        \"\"\"\nif self._env_vars is None:\nenv_vars = self.config.get('env-vars', {})\nif not isinstance(env_vars, dict):\nmessage = f'Field `tool.hatch.envs.{self.name}.env-vars` must be a mapping'\nraise TypeError(message)\nfor key, value in env_vars.items():\nif not isinstance(value, str):\nmessage = (\nf'Environment variable `{key}` of field `tool.hatch.envs.{self.name}.env-vars` must be a string'\n)\nraise TypeError(message)\nnew_env_vars = {}\nwith self.metadata.context.apply_context(self.context):\nfor key, value in env_vars.items():\nnew_env_vars[key] = self.metadata.context.format(value)\nnew_env_vars[AppEnvVars.ENV_ACTIVE] = self.name\nself._env_vars = new_env_vars\nreturn self._env_vars\n@property\ndef env_include(self) -> list[str]:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.envs.<ENV_NAME>]\n        env-include = [...]\n        ```\n        \"\"\"\nif self._env_include is None:\nenv_include = self.config.get('env-include', [])\nif not isinstance(env_include, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.env-include` must be an array'\nraise TypeError(message)\nfor i, pattern in enumerate(env_include, 1):\nif not isinstance(pattern, str):\nmessage = f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-include` must be a string'\nraise TypeError(message)\nif env_include:\nself._env_include = ['HATCH_BUILD_*', *env_include]\nelse:\nself._env_include = env_include\nreturn self._env_include\n@property\ndef env_exclude(self) -> list[str]:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.envs.<ENV_NAME>]\n        env-exclude = [...]\n        ```\n        \"\"\"\nif self._env_exclude is None:\nenv_exclude = self.config.get('env-exclude', [])\nif not isinstance(env_exclude, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.env-exclude` must be an array'\nraise TypeError(message)\nfor i, pattern in enumerate(env_exclude, 1):\nif not isinstance(pattern, str):\nmessage = f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-exclude` must be a string'\nraise TypeError(message)\nself._env_exclude = env_exclude\nreturn self._env_exclude\n@property\ndef environment_dependencies_complex(self):\nif self._environment_dependencies_complex is None:\nfrom packaging.requirements import InvalidRequirement, Requirement\ndependencies_complex = []\nwith self.apply_context():\nfor option in ('dependencies', 'extra-dependencies'):\ndependencies = self.config.get(option, [])\nif not isinstance(dependencies, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.{option}` must be an array'\nraise TypeError(message)\nfor i, entry in enumerate(dependencies, 1):\nif not isinstance(entry, str):\nmessage = (\nf'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` must be a string'\n)\nraise TypeError(message)\ntry:\ndependencies_complex.append(Requirement(self.metadata.context.format(entry)))\nexcept InvalidRequirement as e:\nmessage = f'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` is invalid: {e}'\nraise ValueError(message) from None\nself._environment_dependencies_complex = dependencies_complex\nreturn self._environment_dependencies_complex\n@property\ndef environment_dependencies(self) -> list[str]:\n\"\"\"\n        The list of all [environment dependencies](../../config/environment/overview.md#dependencies).\n        \"\"\"\nif self._environment_dependencies is None:\nself._environment_dependencies = [str(dependency) for dependency in self.environment_dependencies_complex]\nreturn self._environment_dependencies\n@property\ndef dependencies_complex(self):\nif self._dependencies_complex is None:\nall_dependencies_complex = list(self.environment_dependencies_complex)\n# Ensure these are checked last to speed up initial environment creation since\n# they will already be installed along with the project\nif not self.skip_install and self.dev_mode:\nfrom hatch.utils.dep import get_project_dependencies_complex\ndependencies_complex, optional_dependencies_complex = get_project_dependencies_complex(self)\nall_dependencies_complex.extend(dependencies_complex.values())\nfor feature in self.features:\nif feature not in optional_dependencies_complex:\nmessage = (\nf'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not '\nf'defined in the dynamic field `project.optional-dependencies`'\n)\nraise ValueError(message)\nall_dependencies_complex.extend(optional_dependencies_complex[feature].values())\nself._dependencies_complex = all_dependencies_complex\nreturn self._dependencies_complex\n@property\ndef dependencies(self) -> list[str]:\n\"\"\"\n        The list of all [project dependencies](../../config/metadata.md#dependencies) (if\n        [installed](../../config/environment/overview.md#skip-install) and in\n        [dev mode](../../config/environment/overview.md#dev-mode)) and\n        [environment dependencies](../../config/environment/overview.md#dependencies).\n        \"\"\"\nif self._dependencies is None:\nself._dependencies = [str(dependency) for dependency in self.dependencies_complex]\nreturn self._dependencies\n@property\ndef platforms(self) -> list[str]:\n\"\"\"\n        All names are stored as their lower-cased version.\n        ```toml config-example\n        [tool.hatch.envs.<ENV_NAME>]\n        platforms = [...]\n        ```\n        \"\"\"\nif self._platforms is None:\nplatforms = self.config.get('platforms', [])\nif not isinstance(platforms, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.platforms` must be an array'\nraise TypeError(message)\nfor i, command in enumerate(platforms, 1):\nif not isinstance(command, str):\nmessage = f'Platform #{i} of field `tool.hatch.envs.{self.name}.platforms` must be a string'\nraise TypeError(message)\nself._platforms = [platform.lower() for platform in platforms]\nreturn self._platforms\n@property\ndef skip_install(self) -> bool:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.envs.<ENV_NAME>]\n        skip-install = ...\n        ```\n        \"\"\"\nif self._skip_install is None:\nskip_install = self.config.get('skip-install', not self.metadata.has_project_file())\nif not isinstance(skip_install, bool):\nmessage = f'Field `tool.hatch.envs.{self.name}.skip-install` must be a boolean'\nraise TypeError(message)\nself._skip_install = skip_install\nreturn self._skip_install\n@property\ndef dev_mode(self) -> bool:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.envs.<ENV_NAME>]\n        dev-mode = ...\n        ```\n        \"\"\"\nif self._dev_mode is None:\ndev_mode = self.config.get('dev-mode', True)\nif not isinstance(dev_mode, bool):\nmessage = f'Field `tool.hatch.envs.{self.name}.dev-mode` must be a boolean'\nraise TypeError(message)\nself._dev_mode = dev_mode\nreturn self._dev_mode\n@property\ndef features(self):\nif self._features is None:\nfrom hatchling.metadata.utils import normalize_project_name\nfeatures = self.config.get('features', [])\nif not isinstance(features, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.features` must be an array of strings'\nraise TypeError(message)\nall_features = set()\nfor i, feature in enumerate(features, 1):\nif not isinstance(feature, str):\nmessage = f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` must be a string'\nraise TypeError(message)\nelif not feature:\nmessage = f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` cannot be an empty string'\nraise ValueError(message)\nif not self.metadata.hatch.metadata.allow_ambiguous_features:\nfeature = normalize_project_name(feature)\nif (\nnot self.metadata.hatch.metadata.hook_config\nand feature not in self.metadata.core.optional_dependencies\n):\nmessage = (\nf'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not '\nf'defined in field `project.optional-dependencies`'\n)\nraise ValueError(message)\nall_features.add(feature)\nself._features = sorted(all_features)\nreturn self._features\n@property\ndef description(self) -> str:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.envs.<ENV_NAME>]\n        description = ...\n        ```\n        \"\"\"\nif self._description is None:\ndescription = self.config.get('description', '')\nif not isinstance(description, str):\nmessage = f'Field `tool.hatch.envs.{self.name}.description` must be a string'\nraise TypeError(message)\nself._description = description\nreturn self._description\n@property\ndef scripts(self):\nif self._scripts is None:\nscript_config = self.config.get('scripts', {})\nif not isinstance(script_config, dict):\nmessage = f'Field `tool.hatch.envs.{self.name}.scripts` must be a table'\nraise TypeError(message)\nconfig = {}\nfor name, data in script_config.items():\nif ' ' in name:\nmessage = (\nf'Script name `{name}` in field `tool.hatch.envs.{self.name}.scripts` must not contain spaces'\n)\nraise ValueError(message)\ncommands = []\nif isinstance(data, str):\ncommands.append(data)\nelif isinstance(data, list):\nfor i, command in enumerate(data, 1):\nif not isinstance(command, str):\nmessage = (\nf'Command #{i} in field `tool.hatch.envs.{self.name}.scripts.{name}` must be a string'\n)\nraise TypeError(message)\ncommands.append(command)\nelse:\nmessage = (\nf'Field `tool.hatch.envs.{self.name}.scripts.{name}` must be a string or an array of strings'\n)\nraise TypeError(message)\nconfig[name] = commands\nseen = {}\nactive = []\nfor script_name, commands in config.items():\ncommands[:] = expand_script_commands(self.name, script_name, commands, config, seen, active)\nself._scripts = config\nreturn self._scripts\n@property\ndef pre_install_commands(self):\nif self._pre_install_commands is None:\npre_install_commands = self.config.get('pre-install-commands', [])\nif not isinstance(pre_install_commands, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.pre-install-commands` must be an array'\nraise TypeError(message)\nfor i, command in enumerate(pre_install_commands, 1):\nif not isinstance(command, str):\nmessage = (\nf'Command #{i} of field `tool.hatch.envs.{self.name}.pre-install-commands` must be a string'\n)\nraise TypeError(message)\nself._pre_install_commands = list(pre_install_commands)\nreturn self._pre_install_commands\n@property\ndef post_install_commands(self):\nif self._post_install_commands is None:\npost_install_commands = self.config.get('post-install-commands', [])\nif not isinstance(post_install_commands, list):\nmessage = f'Field `tool.hatch.envs.{self.name}.post-install-commands` must be an array'\nraise TypeError(message)\nfor i, command in enumerate(post_install_commands, 1):\nif not isinstance(command, str):\nmessage = (\nf'Command #{i} of field `tool.hatch.envs.{self.name}.post-install-commands` must be a string'\n)\nraise TypeError(message)\nself._post_install_commands = list(post_install_commands)\nreturn self._post_install_commands\ndef activate(self):\n\"\"\"\n        A convenience method called when using the environment as a context manager:\n        ```python\n        with environment:\n            ...\n        ```\n        \"\"\"\ndef deactivate(self):\n\"\"\"\n        A convenience method called after using the environment as a context manager:\n        ```python\n        with environment:\n            ...\n        ```\n        \"\"\"\n@abstractmethod\ndef find(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should return information about how to locate the environment.\n        \"\"\"\n@abstractmethod\ndef create(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should perform the necessary steps to set up the environment.\n        \"\"\"\n@abstractmethod\ndef remove(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should perform the necessary steps to completely remove the environment from the system and will only\n        be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or\n        [`env prune`](../../cli/reference.md#hatch-env-prune) commands.\n        If the\n        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n        has a caching mechanism, this should remove that as well.\n        \"\"\"\n@abstractmethod\ndef exists(self) -> bool:\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should indicate whether or not the environment has already been created.\n        \"\"\"\n@abstractmethod\ndef install_project(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should install the project in the environment.\n        \"\"\"\n@abstractmethod\ndef install_project_dev_mode(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should install the project in the environment such that the environment\n        always reflects the current state of the project.\n        \"\"\"\n@abstractmethod\ndef dependencies_in_sync(self) -> bool:\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should indicate whether or not the environment is compatible with the current\n        [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies).\n        \"\"\"\n@abstractmethod\ndef sync_dependencies(self):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This should install the\n        [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies)\n        in the environment.\n        \"\"\"\n@contextmanager\ndef build_environment(self, dependencies: list[str]):\n\"\"\"\n        This should set up an isolated environment in which to [`build`](../../cli/reference.md#hatch-build) the project\n        given a set of dependencies and must be a context manager:\n        ```python\n        with environment.build_environment([...]):\n            ...\n        ```\n        The build environment should reflect any\n        [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)\n        the user defined either currently or at the time of\n        [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).\n        \"\"\"\nwith self.get_env_vars():\nyield\ndef get_build_process(self, build_environment, **kwargs):\n\"\"\"\n        This will be called when the\n        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n        is active:\n        ```python\n        with environment.build_environment([...]) as build_environment:\n            build_process = environment.get_build_process(build_environment, ...)\n        ```\n        This should return the standard library's\n        [subprocess.Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)\n        with all output captured by `stdout`. The command is constructed by passing all keyword arguments to\n        [construct_build_command](reference.md#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command).\n        For an example, open the default implementation below:\n        \"\"\"\nreturn self.platform.capture_process(self.construct_build_command(**kwargs))\ndef build_environment_exists(self):\n\"\"\"\n        If the\n        [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n        has a caching mechanism, this should indicate whether or not it has already been created.\n        \"\"\"\nreturn False\ndef enter_shell(self, name: str, path: str, args: Iterable[str]):\n\"\"\"\n        Spawn a [shell](../../config/hatch.md#shell) within the environment.\n        This should either use\n        [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)\n        directly or provide the same guarantee.\n        \"\"\"\nwith self.command_context():\nself.platform.exit_with_command([path, *args])\ndef run_shell_command(self, command: str, **kwargs):\n\"\"\"\n        This should return the standard library's\n        [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess)\n        and will always be called when the\n        [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)\n        is active, with the expectation of providing the same guarantee.\n        \"\"\"\nkwargs.setdefault('shell', True)\nreturn self.platform.run_command(command, **kwargs)\n@contextmanager\ndef command_context(self):\n\"\"\"\n        A context manager that when active should make executed shell commands reflect any\n        [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)\n        the user defined either currently or at the time of\n        [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).\n        For an example, open the default implementation below:\n        \"\"\"\nwith self.get_env_vars():\nyield\ndef resolve_commands(self, commands: list[str]):\n\"\"\"\n        This expands each command into one or more commands based on any\n        [scripts](../../config/environment/overview.md#scripts) that the user defined.\n        \"\"\"\nfor command in commands:\nyield from self.expand_command(command)\ndef expand_command(self, command):\npossible_script, args, ignore_exit_code = parse_script_command(command)\n# Indicate undefined\nif not args:\nargs = None\nwith self.apply_context():\nif possible_script in self.scripts:\nfor cmd in self.scripts[possible_script]:\nyield self.metadata.context.format(cmd, args=args).strip()\nelse:\nyield self.metadata.context.format(command, args=args).strip()\ndef construct_build_command(\nself,\n*,\ndirectory=None,\ntargets=(),\nhooks_only=False,\nno_hooks=False,\nclean=False,\nclean_hooks_after=False,\nclean_only=False,\n):\n\"\"\"\n        This is the canonical way [`build`](../../cli/reference.md#hatch-build) command options are translated to\n        a subprocess command issued to [builders](../builder/reference.md).\n        \"\"\"\ncommand = ['python', '-u', '-m', 'hatchling', 'build', '--app']\nif directory:\ncommand.extend(('--directory', directory))\nif targets:\nfor target in targets:\ncommand.extend(('--target', target))\nif hooks_only:\ncommand.append('--hooks-only')\nif no_hooks:\ncommand.append('--no-hooks')\nif clean:\ncommand.append('--clean')\nif clean_hooks_after:\ncommand.append('--clean-hooks-after')\nif clean_only:\ncommand.append('--clean-only')\nreturn command\ndef construct_pip_install_command(self, args: list[str]):\n\"\"\"\n        A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/)\n        command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.\n        \"\"\"\ncommand = ['python', '-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-python-version-warning']\n# Default to -1 verbosity\nadd_verbosity_flag(command, self.verbosity, adjustment=-1)\ncommand.extend(args)\nreturn command\ndef join_command_args(self, args: list[str]):\n\"\"\"\n        This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string\n        from the received arguments.\n        \"\"\"\nreturn self.platform.join_command_args(args)\ndef apply_features(self, requirement: str):\n\"\"\"\n        A convenience method that applies any user defined [features](../../config/environment/overview.md#features)\n        to the given requirement.\n        \"\"\"\nif self.features:\nfeatures = ','.join(self.features)\nreturn f'{requirement}[{features}]'\nreturn requirement\ndef check_compatibility(self):\n\"\"\"\n        This raises an exception if the environment is not compatible with the user's setup. The default behavior\n        checks for [platform compatibility](../../config/environment/overview.md#supported-platforms)\n        and any method override should keep this check.\n        \"\"\"\nif self.platforms and self.platform.name not in self.platforms:\nmessage = 'unsupported platform'\nraise OSError(message)\ndef get_env_vars(self) -> EnvVars:\n\"\"\"\n        Returns a mapping of environment variables that should be available to the environment. The object can\n        be used as a context manager to temporarily apply the environment variables to the current process.\n        !!! note\n            The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment.\n        \"\"\"\nreturn EnvVars(self.env_vars, self.env_include, self.env_exclude)\ndef get_env_var_option(self, option: str) -> str:\n\"\"\"\n        Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`.\n        \"\"\"\nreturn os.environ.get(f'{AppEnvVars.ENV_OPTION_PREFIX}{self.PLUGIN_NAME}_{option}'.upper(), '')\ndef get_context(self):\n\"\"\"\n        Returns a subclass of\n        [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter).\n        \"\"\"\nfrom hatch.env.context import EnvironmentContextFormatter\nreturn EnvironmentContextFormatter(self)\n@staticmethod\ndef get_option_types() -> dict:\n\"\"\"\n        Returns a mapping of supported options to their respective types so that they can be used by\n        [overrides](../../config/environment/advanced.md#option-overrides).\n        \"\"\"\nreturn {}\n@contextmanager\ndef apply_context(self):\nwith self.get_env_vars(), self.metadata.context.apply_context(self.context):\nyield\ndef __enter__(self):\nself.activate()\nreturn self\ndef __exit__(self, exc_type, exc_value, traceback):\nself.deactivate()\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.app","title":"app property","text":"

An instance of Application.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.root","title":"root property","text":"

The root of the project tree as a path-like object.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.name","title":"name: str property","text":"

The name of the environment.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.data_directory","title":"data_directory property","text":"

The directory this plugin should use for storage as a path-like object. If the user has not configured one then this will be the same as the isolated data directory.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.isolated_data_directory","title":"isolated_data_directory property","text":"

The default directory reserved exclusively for this plugin as a path-like object.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.config","title":"config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\n
[envs.<ENV_NAME>]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.platform","title":"platform property","text":"

An instance of Platform.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.environment_dependencies","title":"environment_dependencies: list[str] property","text":"

The list of all environment dependencies.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.dependencies","title":"dependencies: list[str] property","text":"

The list of all project dependencies (if installed and in dev mode) and environment dependencies.

"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.env_vars","title":"env_vars: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>.env-vars]\n
[envs.<ENV_NAME>.env-vars]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.env_include","title":"env_include: list[str] property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nenv-include = [...]\n
[envs.<ENV_NAME>]\nenv-include = [...]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.env_exclude","title":"env_exclude: list[str] property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nenv-exclude = [...]\n
[envs.<ENV_NAME>]\nenv-exclude = [...]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.platforms","title":"platforms: list[str] property","text":"

All names are stored as their lower-cased version.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nplatforms = [...]\n
[envs.<ENV_NAME>]\nplatforms = [...]\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.skip_install","title":"skip_install: bool property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\nskip-install = ...\n
[envs.<ENV_NAME>]\nskip-install = ...\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.dev_mode","title":"dev_mode: bool property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\ndev-mode = ...\n
[envs.<ENV_NAME>]\ndev-mode = ...\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.description","title":"description: str property","text":"pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\ndescription = ...\n
[envs.<ENV_NAME>]\ndescription = ...\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.activate","title":"activate()","text":"

A convenience method called when using the environment as a context manager:

with environment:\n    ...\n
Source code in src/hatch/env/plugin/interface.py
def activate(self):\n\"\"\"\n    A convenience method called when using the environment as a context manager:\n    ```python\n    with environment:\n        ...\n    ```\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.deactivate","title":"deactivate()","text":"

A convenience method called after using the environment as a context manager:

with environment:\n    ...\n
Source code in src/hatch/env/plugin/interface.py
def deactivate(self):\n\"\"\"\n    A convenience method called after using the environment as a context manager:\n    ```python\n    with environment:\n        ...\n    ```\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.find","title":"find() abstractmethod","text":"

REQUIRED

This should return information about how to locate the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef find(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should return information about how to locate the environment.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.create","title":"create() abstractmethod","text":"

REQUIRED

This should perform the necessary steps to set up the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef create(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should perform the necessary steps to set up the environment.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.remove","title":"remove() abstractmethod","text":"

REQUIRED

This should perform the necessary steps to completely remove the environment from the system and will only be triggered manually by users with the env remove or env prune commands.

If the build environment has a caching mechanism, this should remove that as well.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef remove(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should perform the necessary steps to completely remove the environment from the system and will only\n    be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or\n    [`env prune`](../../cli/reference.md#hatch-env-prune) commands.\n    If the\n    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n    has a caching mechanism, this should remove that as well.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.exists","title":"exists() -> bool abstractmethod","text":"

REQUIRED

This should indicate whether or not the environment has already been created.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef exists(self) -> bool:\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should indicate whether or not the environment has already been created.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.install_project","title":"install_project() abstractmethod","text":"

REQUIRED

This should install the project in the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef install_project(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should install the project in the environment.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.install_project_dev_mode","title":"install_project_dev_mode() abstractmethod","text":"

REQUIRED

This should install the project in the environment such that the environment always reflects the current state of the project.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef install_project_dev_mode(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should install the project in the environment such that the environment\n    always reflects the current state of the project.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.dependencies_in_sync","title":"dependencies_in_sync() -> bool abstractmethod","text":"

REQUIRED

This should indicate whether or not the environment is compatible with the current dependencies.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef dependencies_in_sync(self) -> bool:\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should indicate whether or not the environment is compatible with the current\n    [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies).\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.sync_dependencies","title":"sync_dependencies() abstractmethod","text":"

REQUIRED

This should install the dependencies in the environment.

Source code in src/hatch/env/plugin/interface.py
@abstractmethod\ndef sync_dependencies(self):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This should install the\n    [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies)\n    in the environment.\n    \"\"\"\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.build_environment","title":"build_environment(dependencies: list[str])","text":"

This should set up an isolated environment in which to build the project given a set of dependencies and must be a context manager:

with environment.build_environment([...]):\n    ...\n

The build environment should reflect any environment variables the user defined either currently or at the time of creation.

Source code in src/hatch/env/plugin/interface.py
@contextmanager\ndef build_environment(self, dependencies: list[str]):\n\"\"\"\n    This should set up an isolated environment in which to [`build`](../../cli/reference.md#hatch-build) the project\n    given a set of dependencies and must be a context manager:\n    ```python\n    with environment.build_environment([...]):\n        ...\n    ```\n    The build environment should reflect any\n    [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)\n    the user defined either currently or at the time of\n    [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).\n    \"\"\"\nwith self.get_env_vars():\nyield\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.build_environment_exists","title":"build_environment_exists()","text":"

If the build environment has a caching mechanism, this should indicate whether or not it has already been created.

Source code in src/hatch/env/plugin/interface.py
def build_environment_exists(self):\n\"\"\"\n    If the\n    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n    has a caching mechanism, this should indicate whether or not it has already been created.\n    \"\"\"\nreturn False\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_build_process","title":"get_build_process(build_environment, **kwargs)","text":"

This will be called when the build environment is active:

with environment.build_environment([...]) as build_environment:\n    build_process = environment.get_build_process(build_environment, ...)\n

This should return the standard library's subprocess.Popen with all output captured by stdout. The command is constructed by passing all keyword arguments to construct_build_command.

For an example, open the default implementation below:

Source code in src/hatch/env/plugin/interface.py
def get_build_process(self, build_environment, **kwargs):\n\"\"\"\n    This will be called when the\n    [build environment](reference.md#hatch.env.plugin.interface.EnvironmentInterface.build_environment)\n    is active:\n    ```python\n    with environment.build_environment([...]) as build_environment:\n        build_process = environment.get_build_process(build_environment, ...)\n    ```\n    This should return the standard library's\n    [subprocess.Popen](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)\n    with all output captured by `stdout`. The command is constructed by passing all keyword arguments to\n    [construct_build_command](reference.md#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command).\n    For an example, open the default implementation below:\n    \"\"\"\nreturn self.platform.capture_process(self.construct_build_command(**kwargs))\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.construct_build_command","title":"construct_build_command(*, directory = None, targets = (), hooks_only = False, no_hooks = False, clean = False, clean_hooks_after = False, clean_only = False)","text":"

This is the canonical way build command options are translated to a subprocess command issued to builders.

Source code in src/hatch/env/plugin/interface.py
def construct_build_command(\nself,\n*,\ndirectory=None,\ntargets=(),\nhooks_only=False,\nno_hooks=False,\nclean=False,\nclean_hooks_after=False,\nclean_only=False,\n):\n\"\"\"\n    This is the canonical way [`build`](../../cli/reference.md#hatch-build) command options are translated to\n    a subprocess command issued to [builders](../builder/reference.md).\n    \"\"\"\ncommand = ['python', '-u', '-m', 'hatchling', 'build', '--app']\nif directory:\ncommand.extend(('--directory', directory))\nif targets:\nfor target in targets:\ncommand.extend(('--target', target))\nif hooks_only:\ncommand.append('--hooks-only')\nif no_hooks:\ncommand.append('--no-hooks')\nif clean:\ncommand.append('--clean')\nif clean_hooks_after:\ncommand.append('--clean-hooks-after')\nif clean_only:\ncommand.append('--clean-only')\nreturn command\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.command_context","title":"command_context()","text":"

A context manager that when active should make executed shell commands reflect any environment variables the user defined either currently or at the time of creation.

For an example, open the default implementation below:

Source code in src/hatch/env/plugin/interface.py
@contextmanager\ndef command_context(self):\n\"\"\"\n    A context manager that when active should make executed shell commands reflect any\n    [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars)\n    the user defined either currently or at the time of\n    [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create).\n    For an example, open the default implementation below:\n    \"\"\"\nwith self.get_env_vars():\nyield\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.enter_shell","title":"enter_shell(name: str, path: str, args: Iterable[str])","text":"

Spawn a shell within the environment.

This should either use command_context directly or provide the same guarantee.

Source code in src/hatch/env/plugin/interface.py
def enter_shell(self, name: str, path: str, args: Iterable[str]):\n\"\"\"\n    Spawn a [shell](../../config/hatch.md#shell) within the environment.\n    This should either use\n    [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)\n    directly or provide the same guarantee.\n    \"\"\"\nwith self.command_context():\nself.platform.exit_with_command([path, *args])\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.run_shell_command","title":"run_shell_command(command: str, **kwargs: str)","text":"

This should return the standard library's subprocess.CompletedProcess and will always be called when the command_context is active, with the expectation of providing the same guarantee.

Source code in src/hatch/env/plugin/interface.py
def run_shell_command(self, command: str, **kwargs):\n\"\"\"\n    This should return the standard library's\n    [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess)\n    and will always be called when the\n    [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context)\n    is active, with the expectation of providing the same guarantee.\n    \"\"\"\nkwargs.setdefault('shell', True)\nreturn self.platform.run_command(command, **kwargs)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.resolve_commands","title":"resolve_commands(commands: list[str])","text":"

This expands each command into one or more commands based on any scripts that the user defined.

Source code in src/hatch/env/plugin/interface.py
def resolve_commands(self, commands: list[str]):\n\"\"\"\n    This expands each command into one or more commands based on any\n    [scripts](../../config/environment/overview.md#scripts) that the user defined.\n    \"\"\"\nfor command in commands:\nyield from self.expand_command(command)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars","title":"get_env_vars() -> EnvVars","text":"

Returns a mapping of environment variables that should be available to the environment. The object can be used as a context manager to temporarily apply the environment variables to the current process.

Note

The environment variable HATCH_ENV_ACTIVE will always be set to the name of the environment.

Source code in src/hatch/env/plugin/interface.py
def get_env_vars(self) -> EnvVars:\n\"\"\"\n    Returns a mapping of environment variables that should be available to the environment. The object can\n    be used as a context manager to temporarily apply the environment variables to the current process.\n    !!! note\n        The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment.\n    \"\"\"\nreturn EnvVars(self.env_vars, self.env_include, self.env_exclude)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.apply_features","title":"apply_features(requirement: str)","text":"

A convenience method that applies any user defined features to the given requirement.

Source code in src/hatch/env/plugin/interface.py
def apply_features(self, requirement: str):\n\"\"\"\n    A convenience method that applies any user defined [features](../../config/environment/overview.md#features)\n    to the given requirement.\n    \"\"\"\nif self.features:\nfeatures = ','.join(self.features)\nreturn f'{requirement}[{features}]'\nreturn requirement\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.construct_pip_install_command","title":"construct_pip_install_command(args: list[str])","text":"

A convenience method for constructing a pip install command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.

Source code in src/hatch/env/plugin/interface.py
def construct_pip_install_command(self, args: list[str]):\n\"\"\"\n    A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/)\n    command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.\n    \"\"\"\ncommand = ['python', '-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-python-version-warning']\n# Default to -1 verbosity\nadd_verbosity_flag(command, self.verbosity, adjustment=-1)\ncommand.extend(args)\nreturn command\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.join_command_args","title":"join_command_args(args: list[str])","text":"

This is used by the run command to construct the root command string from the received arguments.

Source code in src/hatch/env/plugin/interface.py
def join_command_args(self, args: list[str]):\n\"\"\"\n    This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string\n    from the received arguments.\n    \"\"\"\nreturn self.platform.join_command_args(args)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.check_compatibility","title":"check_compatibility()","text":"

This raises an exception if the environment is not compatible with the user's setup. The default behavior checks for platform compatibility and any method override should keep this check.

Source code in src/hatch/env/plugin/interface.py
def check_compatibility(self):\n\"\"\"\n    This raises an exception if the environment is not compatible with the user's setup. The default behavior\n    checks for [platform compatibility](../../config/environment/overview.md#supported-platforms)\n    and any method override should keep this check.\n    \"\"\"\nif self.platforms and self.platform.name not in self.platforms:\nmessage = 'unsupported platform'\nraise OSError(message)\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_option_types","title":"get_option_types() -> dict staticmethod","text":"

Returns a mapping of supported options to their respective types so that they can be used by overrides.

Source code in src/hatch/env/plugin/interface.py
@staticmethod\ndef get_option_types() -> dict:\n\"\"\"\n    Returns a mapping of supported options to their respective types so that they can be used by\n    [overrides](../../config/environment/advanced.md#option-overrides).\n    \"\"\"\nreturn {}\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_env_var_option","title":"get_env_var_option(option: str) -> str","text":"

Returns the value of the upper-cased environment variable HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>.

Source code in src/hatch/env/plugin/interface.py
def get_env_var_option(self, option: str) -> str:\n\"\"\"\n    Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`.\n    \"\"\"\nreturn os.environ.get(f'{AppEnvVars.ENV_OPTION_PREFIX}{self.PLUGIN_NAME}_{option}'.upper(), '')\n
"},{"location":"plugins/environment/reference/#hatch.env.plugin.interface.EnvironmentInterface.get_context","title":"get_context()","text":"

Returns a subclass of EnvironmentContextFormatter.

Source code in src/hatch/env/plugin/interface.py
def get_context(self):\n\"\"\"\n    Returns a subclass of\n    [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter).\n    \"\"\"\nfrom hatch.env.context import EnvironmentContextFormatter\nreturn EnvironmentContextFormatter(self)\n
"},{"location":"plugins/environment/virtual/","title":"Virtual environment","text":"

This uses virtual environments backed by the standard virtualenv tool.

"},{"location":"plugins/environment/virtual/#configuration","title":"Configuration","text":"

The environment plugin name is virtual.

pyproject.toml hatch.toml
[tool.hatch.envs.<ENV_NAME>]\ntype = \"virtual\"\n
[envs.<ENV_NAME>]\ntype = \"virtual\"\n
"},{"location":"plugins/environment/virtual/#options","title":"Options","text":"Option Default Description system-packages false Whether or not to give the virtual environment access to the system site-packages directory python The version of Python to find on your system and subsequently use to create the environment, defaulting to the HATCH_PYTHON environment variable, followed by the first Python executable found along your PATH, followed by the Python executable Hatch is running on. Setting the HATCH_PYTHON environment variable to self will force the use of the Python executable Hatch is running on. For more information, see the documentation. path An explicit path to the virtual environment. The path may be absolute or relative to the project root. Any environments that inherit this option will also use this path. The environment variable HATCH_ENV_TYPE_VIRTUAL_PATH may be used, which will take precedence."},{"location":"plugins/environment/virtual/#location","title":"Location","text":"

The location of environments is determined in the following heuristic order:

  1. The path option
  2. A directory named after the environment within the configured virtual environment directory if the directory resides somewhere within the project root or if it is set to a .virtualenvs directory within the user's home directory
  3. Otherwise, environments are stored within the configured virtual environment directory in a deeply nested structure in order to support multiple projects

Additionally, when the path option is not used, the name of the directory for the default environment will be the normalized project name to provide a more meaningful default shell prompt.

"},{"location":"plugins/environment/virtual/#troubleshooting","title":"Troubleshooting","text":""},{"location":"plugins/environment/virtual/#macos-sip","title":"macOS SIP","text":"

If you need to set linker environment variables like those starting with DYLD_ or LD_, any executable secured by System Integrity Protection that is invoked when running commands will not see those environment variable modifications as macOS strips those.

Hatch interprets such commands as shell commands but deliberately ignores such paths to protected shells. This workaround suffices for the majority of use cases but there are 2 situations in which it may not:

  1. There are no unprotected sh, bash, zsh, nor fish executables found along PATH.
  2. The desired executable is a project's script, and the location of environments contains spaces or is longer than 1241 characters. In this case pip and other installers will create such an entry point with a shebang pointing to /bin/sh (which is protected) to avoid shebang limitations. Rather than changing the location, you could invoke the script as e.g. python -m pytest (if the project supports that method of invocation by shipping a __main__.py).
  1. The shebang length limit is usually 127 but 3 characters surround the executable path: #!<EXE_PATH>\\n \u21a9

"},{"location":"plugins/environment-collector/custom/","title":"Custom environment collector","text":"

This is a custom class in a given Python file that inherits from the EnvironmentCollectorInterface.

"},{"location":"plugins/environment-collector/custom/#configuration","title":"Configuration","text":"

The environment collector plugin name is custom.

pyproject.toml hatch.toml
[tool.hatch.env.collectors.custom]\n
[env.collectors.custom]\n
"},{"location":"plugins/environment-collector/custom/#options","title":"Options","text":"Option Default Description path hatch_plugins.py The path of the Python file"},{"location":"plugins/environment-collector/custom/#example","title":"Example","text":"hatch_plugins.py
    from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface\n\n\n    class CustomEnvironmentCollector(EnvironmentCollectorInterface):\n        ...\n

If multiple subclasses are found, you must define a function named get_environment_collector that returns the desired environment collector.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

"},{"location":"plugins/environment-collector/default/","title":"Default environment collector","text":"

This adds the default environment with type set to virtual and will always be applied.

"},{"location":"plugins/environment-collector/default/#configuration","title":"Configuration","text":"

The environment collector plugin name is default.

pyproject.toml hatch.toml
[tool.hatch.env.collectors.default]\n
[env.collectors.default]\n
"},{"location":"plugins/environment-collector/default/#options","title":"Options","text":"

There are no options available currently.

"},{"location":"plugins/environment-collector/reference/","title":"Environment collector plugins","text":"

Environment collectors allow for dynamically modifying environments or adding environments beyond those defined in config. Users can override default values provided by each environment.

"},{"location":"plugins/environment-collector/reference/#installation","title":"Installation","text":"

Any required environment collectors that are not built-in must be manually installed alongside Hatch or listed in the tool.hatch.env.requires array for automatic management:

pyproject.toml hatch.toml
[tool.hatch.env]\nrequires = [\n\"...\",\n]\n
[env]\nrequires = [\n\"...\",\n]\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface","title":"EnvironmentCollectorInterface","text":"

Example usage:

plugin.py hooks.py
    from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface\n\n\n    class SpecialEnvironmentCollector(EnvironmentCollectorInterface):\n        PLUGIN_NAME = 'special'\n        ...\n
    from hatchling.plugin import hookimpl\n\n    from .plugin import SpecialEnvironmentCollector\n\n\n    @hookimpl\n    def hatch_register_environment_collector():\n        return SpecialEnvironmentCollector\n
Source code in src/hatch/env/collectors/plugin/interface.py
class EnvironmentCollectorInterface:\n\"\"\"\n    Example usage:\n    ```python tab=\"plugin.py\"\n        from hatch.env.collectors.plugin.interface import EnvironmentCollectorInterface\n        class SpecialEnvironmentCollector(EnvironmentCollectorInterface):\n            PLUGIN_NAME = 'special'\n            ...\n    ```\n    ```python tab=\"hooks.py\"\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialEnvironmentCollector\n        @hookimpl\n        def hatch_register_environment_collector():\n            return SpecialEnvironmentCollector\n    ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, root, config):\nself.__root = root\nself.__config = config\n@property\ndef root(self):\n\"\"\"\n        The root of the project tree as a path-like object.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.env.collectors.<PLUGIN_NAME>]\n        ```\n        \"\"\"\nreturn self.__config\ndef get_initial_config(self) -> dict[str, dict]:\n\"\"\"\n        Returns configuration for environments keyed by the environment or matrix name.\n        \"\"\"\nreturn {}\ndef finalize_config(self, config: dict[str, dict]):\n\"\"\"\n        Finalizes configuration for environments keyed by the environment or matrix name. This will override\n        any user-defined settings and any collectors that ran before this call.\n        This is called before matrices are turned into concrete environments.\n        \"\"\"\ndef finalize_environments(self, config: dict[str, dict]):\n\"\"\"\n        Finalizes configuration for environments keyed by the environment name. This will override\n        any user-defined settings and any collectors that ran before this call.\n        This is called after matrices are turned into concrete environments.\n        \"\"\"\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.root","title":"root property","text":"

The root of the project tree as a path-like object.

"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.config","title":"config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.env.collectors.<PLUGIN_NAME>]\n
[env.collectors.<PLUGIN_NAME>]\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.get_initial_config","title":"get_initial_config() -> dict[str, dict]","text":"

Returns configuration for environments keyed by the environment or matrix name.

Source code in src/hatch/env/collectors/plugin/interface.py
def get_initial_config(self) -> dict[str, dict]:\n\"\"\"\n    Returns configuration for environments keyed by the environment or matrix name.\n    \"\"\"\nreturn {}\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.finalize_config","title":"finalize_config(config: dict[str, dict])","text":"

Finalizes configuration for environments keyed by the environment or matrix name. This will override any user-defined settings and any collectors that ran before this call.

This is called before matrices are turned into concrete environments.

Source code in src/hatch/env/collectors/plugin/interface.py
def finalize_config(self, config: dict[str, dict]):\n\"\"\"\n    Finalizes configuration for environments keyed by the environment or matrix name. This will override\n    any user-defined settings and any collectors that ran before this call.\n    This is called before matrices are turned into concrete environments.\n    \"\"\"\n
"},{"location":"plugins/environment-collector/reference/#hatch.env.collectors.plugin.interface.EnvironmentCollectorInterface.finalize_environments","title":"finalize_environments(config: dict[str, dict])","text":"

Finalizes configuration for environments keyed by the environment name. This will override any user-defined settings and any collectors that ran before this call.

This is called after matrices are turned into concrete environments.

Source code in src/hatch/env/collectors/plugin/interface.py
def finalize_environments(self, config: dict[str, dict]):\n\"\"\"\n    Finalizes configuration for environments keyed by the environment name. This will override\n    any user-defined settings and any collectors that ran before this call.\n    This is called after matrices are turned into concrete environments.\n    \"\"\"\n
"},{"location":"plugins/metadata-hook/custom/","title":"Custom metadata hook","text":"

This is a custom class in a given Python file that inherits from the MetadataHookInterface.

"},{"location":"plugins/metadata-hook/custom/#configuration","title":"Configuration","text":"

The metadata hook plugin name is custom.

pyproject.toml hatch.toml
[tool.hatch.metadata.hooks.custom]\n
[metadata.hooks.custom]\n
"},{"location":"plugins/metadata-hook/custom/#options","title":"Options","text":"Option Default Description path hatch_build.py The path of the Python file"},{"location":"plugins/metadata-hook/custom/#example","title":"Example","text":"hatch_build.py
    from hatchling.metadata.plugin.interface import MetadataHookInterface\n\n\n    class CustomMetadataHook(MetadataHookInterface):\n        ...\n

If multiple subclasses are found, you must define a function named get_metadata_hook that returns the desired build hook.

Note

Any defined PLUGIN_NAME is ignored and will always be custom.

"},{"location":"plugins/metadata-hook/reference/","title":"Metadata hook plugins","text":"

Metadata hooks allow for the modification of project metadata after it has been loaded.

"},{"location":"plugins/metadata-hook/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface","title":"MetadataHookInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.metadata.plugin.interface import MetadataHookInterface\n\n\nclass SpecialMetadataHook(MetadataHookInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialMetadataHook\n\n\n@hookimpl\ndef hatch_register_metadata_hook():\n    return SpecialMetadataHook\n
Source code in backend/src/hatchling/metadata/plugin/interface.py
class MetadataHookInterface(ABC):  # no cov\n\"\"\"\n    Example usage:\n    ```python tab=\"plugin.py\"\n    from hatchling.metadata.plugin.interface import MetadataHookInterface\n    class SpecialMetadataHook(MetadataHookInterface):\n        PLUGIN_NAME = 'special'\n        ...\n    ```\n    ```python tab=\"hooks.py\"\n    from hatchling.plugin import hookimpl\n    from .plugin import SpecialMetadataHook\n    @hookimpl\n    def hatch_register_metadata_hook():\n        return SpecialMetadataHook\n    ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, root: str, config: dict) -> None:\nself.__root = root\nself.__config = config\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict:\n\"\"\"\n        The hook configuration.\n        ```toml config-example\n        [tool.hatch.metadata.hooks.<PLUGIN_NAME>]\n        ```\n        \"\"\"\nreturn self.__config\n@abstractmethod\ndef update(self, metadata: dict) -> None:\n\"\"\"\n        This updates the metadata mapping of the `project` table in-place.\n        \"\"\"\ndef get_known_classifiers(self) -> list[str]:\n\"\"\"\n        This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.\n        \"\"\"\nreturn []\n
"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.root","title":"root: str property","text":"

The root of the project tree.

"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.config","title":"config: dict property","text":"

The hook configuration.

pyproject.toml hatch.toml
[tool.hatch.metadata.hooks.<PLUGIN_NAME>]\n
[metadata.hooks.<PLUGIN_NAME>]\n
"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.update","title":"update(metadata: dict) -> None abstractmethod","text":"

This updates the metadata mapping of the project table in-place.

Source code in backend/src/hatchling/metadata/plugin/interface.py
@abstractmethod\ndef update(self, metadata: dict) -> None:\n\"\"\"\n    This updates the metadata mapping of the `project` table in-place.\n    \"\"\"\n
"},{"location":"plugins/metadata-hook/reference/#hatchling.metadata.plugin.interface.MetadataHookInterface.get_known_classifiers","title":"get_known_classifiers() -> list[str]","text":"

This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.

Source code in backend/src/hatchling/metadata/plugin/interface.py
def get_known_classifiers(self) -> list[str]:\n\"\"\"\n    This returns extra classifiers that should be considered valid in addition to the ones known to PyPI.\n    \"\"\"\nreturn []\n
"},{"location":"plugins/publisher/package-index/","title":"Index publisher","text":"

See the documentation for publishing.

"},{"location":"plugins/publisher/package-index/#configuration","title":"Configuration","text":"

The publisher plugin name is index.

config.toml
[publish.index]\n
"},{"location":"plugins/publisher/package-index/#options","title":"Options","text":"Flag Config name Description -r/--repo repo The repository with which to publish artifacts -u/--user user The user with which to authenticate -a/--auth auth The credentials to use for authentication --ca-cert ca-cert The path to a CA bundle --client-cert client-cert The path to a client certificate, optionally containing the private key --client-key client-key The path to the client certificate's private key repos A table of named repositories to their respective options"},{"location":"plugins/publisher/package-index/#repositories","title":"Repositories","text":"

All top-level options can be overridden per repository using the repos table with a required url attribute for each repository. The following shows the default configuration:

config.toml
[publish.index.repos.main]\nurl = \"https://upload.pypi.org/legacy/\"\n\n[publish.index.repos.test]\nurl = \"https://test.pypi.org/legacy/\"\n

The repo and repos options have no effect.

"},{"location":"plugins/publisher/reference/","title":"Publisher plugins","text":""},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface","title":"PublisherInterface","text":"

Example usage:

plugin.py hooks.py
    from hatch.publish.plugin.interface import PublisherInterface\n\n\n    class SpecialPublisher(PublisherInterface):\n        PLUGIN_NAME = 'special'\n        ...\n
    from hatchling.plugin import hookimpl\n\n    from .plugin import SpecialPublisher\n\n\n    @hookimpl\n    def hatch_register_publisher():\n        return SpecialPublisher\n
Source code in src/hatch/publish/plugin/interface.py
class PublisherInterface(ABC):\n\"\"\"\n    Example usage:\n    ```python tab=\"plugin.py\"\n        from hatch.publish.plugin.interface import PublisherInterface\n        class SpecialPublisher(PublisherInterface):\n            PLUGIN_NAME = 'special'\n            ...\n    ```\n    ```python tab=\"hooks.py\"\n        from hatchling.plugin import hookimpl\n        from .plugin import SpecialPublisher\n        @hookimpl\n        def hatch_register_publisher():\n            return SpecialPublisher\n    ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, app, root, cache_dir, project_config, plugin_config):\nself.__app = app\nself.__root = root\nself.__cache_dir = cache_dir\nself.__project_config = project_config\nself.__plugin_config = plugin_config\nself.__disable = None\n@property\ndef app(self):\n\"\"\"\n        An instance of [Application](../utilities.md#hatchling.bridge.app.Application).\n        \"\"\"\nreturn self.__app\n@property\ndef root(self):\n\"\"\"\n        The root of the project tree as a path-like object.\n        \"\"\"\nreturn self.__root\n@property\ndef cache_dir(self):\n\"\"\"\n        The directory reserved exclusively for this plugin as a path-like object.\n        \"\"\"\nreturn self.__cache_dir\n@property\ndef project_config(self) -> dict:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.publish.<PLUGIN_NAME>]\n        ```\n        \"\"\"\nreturn self.__project_config\n@property\ndef plugin_config(self) -> dict:\n\"\"\"\n        This is defined in Hatch's [config file](../../config/hatch.md).\n        ```toml tab=\"config.toml\"\n        [publish.<PLUGIN_NAME>]\n        ```\n        \"\"\"\nreturn self.__plugin_config\n@property\ndef disable(self):\n\"\"\"\n        Whether this plugin is disabled, thus requiring confirmation when publishing. Local\n        [project configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.project_config)\n        takes precedence over global\n        [plugin configuration](reference.md#hatch.publish.plugin.interface.PublisherInterface.plugin_config).\n        \"\"\"\nif self.__disable is None:\nif 'disable' in self.project_config:\ndisable = self.project_config['disable']\nif not isinstance(disable, bool):\nmessage = f'Field `tool.hatch.publish.{self.PLUGIN_NAME}.disable` must be a boolean'\nraise TypeError(message)\nelse:\ndisable = self.plugin_config.get('disable', False)\nif not isinstance(disable, bool):\nmessage = f'Global plugin configuration `publish.{self.PLUGIN_NAME}.disable` must be a boolean'\nraise TypeError(message)\nself.__disable = disable\nreturn self.__disable\n@abstractmethod\ndef publish(self, artifacts: list[str], options: dict):\n\"\"\"\n        :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n        This is called directly by the [`publish`](../../cli/reference.md#hatch-publish) command\n        with the arguments and options it receives.\n        \"\"\"\n
"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.app","title":"app property","text":"

An instance of Application.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.root","title":"root property","text":"

The root of the project tree as a path-like object.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.cache_dir","title":"cache_dir property","text":"

The directory reserved exclusively for this plugin as a path-like object.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.project_config","title":"project_config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.publish.<PLUGIN_NAME>]\n
[publish.<PLUGIN_NAME>]\n
"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.plugin_config","title":"plugin_config: dict property","text":"

This is defined in Hatch's config file.

config.toml
[publish.<PLUGIN_NAME>]\n
"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.disable","title":"disable property","text":"

Whether this plugin is disabled, thus requiring confirmation when publishing. Local project configuration takes precedence over global plugin configuration.

"},{"location":"plugins/publisher/reference/#hatch.publish.plugin.interface.PublisherInterface.publish","title":"publish(artifacts: list[str], options: dict) abstractmethod","text":"

REQUIRED

This is called directly by the publish command with the arguments and options it receives.

Source code in src/hatch/publish/plugin/interface.py
@abstractmethod\ndef publish(self, artifacts: list[str], options: dict):\n\"\"\"\n    :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right:\n    This is called directly by the [`publish`](../../cli/reference.md#hatch-publish) command\n    with the arguments and options it receives.\n    \"\"\"\n
"},{"location":"plugins/version-scheme/reference/","title":"Version scheme plugins","text":""},{"location":"plugins/version-scheme/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface","title":"VersionSchemeInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.version.scheme.plugin.interface import VersionSchemeInterface\n\n\nclass SpecialVersionScheme(VersionSchemeInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialVersionScheme\n\n\n@hookimpl\ndef hatch_register_version_scheme():\n    return SpecialVersionScheme\n
Source code in backend/src/hatchling/version/scheme/plugin/interface.py
class VersionSchemeInterface(ABC):  # no cov\n\"\"\"\n    Example usage:\n    ```python tab=\"plugin.py\"\n    from hatchling.version.scheme.plugin.interface import VersionSchemeInterface\n    class SpecialVersionScheme(VersionSchemeInterface):\n        PLUGIN_NAME = 'special'\n        ...\n    ```\n    ```python tab=\"hooks.py\"\n    from hatchling.plugin import hookimpl\n    from .plugin import SpecialVersionScheme\n    @hookimpl\n    def hatch_register_version_scheme():\n        return SpecialVersionScheme\n    ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, root: str, config: dict) -> None:\nself.__root = root\nself.__config = config\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree as a string.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.version]\n        ```\n        \"\"\"\nreturn self.__config\n@abstractmethod\ndef update(self, desired_version: str, original_version: str, version_data: dict) -> str:\n\"\"\"\n        This should return a normalized form of the desired version and verify that it\n        is higher than the original version.\n        \"\"\"\n
"},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.root","title":"root: str property","text":"

The root of the project tree as a string.

"},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.config","title":"config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.version]\n
[version]\n
"},{"location":"plugins/version-scheme/reference/#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.update","title":"update(desired_version: str, original_version: str, version_data: dict) -> str abstractmethod","text":"

This should return a normalized form of the desired version and verify that it is higher than the original version.

Source code in backend/src/hatchling/version/scheme/plugin/interface.py
@abstractmethod\ndef update(self, desired_version: str, original_version: str, version_data: dict) -> str:\n\"\"\"\n    This should return a normalized form of the desired version and verify that it\n    is higher than the original version.\n    \"\"\"\n
"},{"location":"plugins/version-scheme/standard/","title":"Standard version scheme","text":"

See the documentation for versioning.

"},{"location":"plugins/version-scheme/standard/#configuration","title":"Configuration","text":"

The version scheme plugin name is standard.

pyproject.toml hatch.toml
[tool.hatch.version]\nscheme = \"standard\"\n
[version]\nscheme = \"standard\"\n
"},{"location":"plugins/version-scheme/standard/#options","title":"Options","text":"Option Description validate-bump When setting a specific version, this determines whether to check that the new version is higher than the original. The default is true."},{"location":"plugins/version-source/code/","title":"Code version source","text":""},{"location":"plugins/version-source/code/#updates","title":"Updates","text":"

Setting the version is not supported.

"},{"location":"plugins/version-source/code/#configuration","title":"Configuration","text":"

The version source plugin name is code.

pyproject.toml hatch.toml
[tool.hatch.version]\nsource = \"code\"\n
[version]\nsource = \"code\"\n
"},{"location":"plugins/version-source/code/#options","title":"Options","text":"Option Description path (required) A relative path to a Python file or extension module that will be loaded expression A Python expression that when evaluated in the context of the loaded file returns the version. The default expression is simply __version__. search-paths A list of relative paths to directories that will be prepended to Python's search path"},{"location":"plugins/version-source/code/#missing-imports","title":"Missing imports","text":"

If the chosen path imports another module in your project, then you'll need to use absolute imports coupled with the search-paths option. For example, say you need to load the following file:

src/pkg/__init__.py
    from ._version import get_version\n\n    __version__ = get_version()\n

You should change it to:

src/pkg/__init__.py
    from pkg._version import get_version\n\n    __version__ = get_version()\n

and the configuration would become:

pyproject.toml hatch.toml
[tool.hatch.version]\nsource = \"code\"\npath = \"src/pkg/__init__.py\"\nsearch-paths = [\"src\"]\n
[version]\nsource = \"code\"\npath = \"src/pkg/__init__.py\"\nsearch-paths = [\"src\"]\n
"},{"location":"plugins/version-source/env/","title":"Environment version source","text":"

Retrieves the version from an environment variable. This can be useful in build pipelines where the version is set by an external trigger.

"},{"location":"plugins/version-source/env/#updates","title":"Updates","text":"

Setting the version is not supported.

"},{"location":"plugins/version-source/env/#configuration","title":"Configuration","text":"

The version source plugin name is env.

pyproject.toml hatch.toml
[tool.hatch.version]\nsource = \"env\"\n
[version]\nsource = \"env\"\n
"},{"location":"plugins/version-source/env/#options","title":"Options","text":"Option Description variable (required) The name of the environment variable"},{"location":"plugins/version-source/reference/","title":"Version source plugins","text":""},{"location":"plugins/version-source/reference/#known-third-party","title":"Known third-party","text":""},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface","title":"VersionSourceInterface","text":"

Example usage:

plugin.py hooks.py
from hatchling.version.source.plugin.interface import VersionSourceInterface\n\n\nclass SpecialVersionSource(VersionSourceInterface):\n    PLUGIN_NAME = 'special'\n    ...\n
from hatchling.plugin import hookimpl\n\nfrom .plugin import SpecialVersionSource\n\n\n@hookimpl\ndef hatch_register_version_source():\n    return SpecialVersionSource\n
Source code in backend/src/hatchling/version/source/plugin/interface.py
class VersionSourceInterface(ABC):  # no cov\n\"\"\"\n    Example usage:\n    ```python tab=\"plugin.py\"\n    from hatchling.version.source.plugin.interface import VersionSourceInterface\n    class SpecialVersionSource(VersionSourceInterface):\n        PLUGIN_NAME = 'special'\n        ...\n    ```\n    ```python tab=\"hooks.py\"\n    from hatchling.plugin import hookimpl\n    from .plugin import SpecialVersionSource\n    @hookimpl\n    def hatch_register_version_source():\n        return SpecialVersionSource\n    ```\n    \"\"\"\nPLUGIN_NAME = ''\n\"\"\"The name used for selection.\"\"\"\ndef __init__(self, root: str, config: dict) -> None:\nself.__root = root\nself.__config = config\n@property\ndef root(self) -> str:\n\"\"\"\n        The root of the project tree as a string.\n        \"\"\"\nreturn self.__root\n@property\ndef config(self) -> dict:\n\"\"\"\n        ```toml config-example\n        [tool.hatch.version]\n        ```\n        \"\"\"\nreturn self.__config\n@abstractmethod\ndef get_version_data(self) -> dict:\n\"\"\"\n        This should return a mapping with a `version` key representing the current version of the project and will be\n        displayed when invoking the [`version`](../../cli/reference.md#hatch-version) command without any arguments.\n        The mapping can contain anything else and will be passed to\n        [set_version](reference.md#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version)\n        when updating the version.\n        \"\"\"\ndef set_version(self, version: str, version_data: dict) -> None:\n\"\"\"\n        This should update the version to the first argument with the data provided during retrieval.\n        \"\"\"\nraise NotImplementedError\n
"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.PLUGIN_NAME","title":"PLUGIN_NAME = '' class-attribute instance-attribute","text":"

The name used for selection.

"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.root","title":"root: str property","text":"

The root of the project tree as a string.

"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.config","title":"config: dict property","text":"pyproject.toml hatch.toml
[tool.hatch.version]\n
[version]\n
"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.get_version_data","title":"get_version_data() -> dict abstractmethod","text":"

This should return a mapping with a version key representing the current version of the project and will be displayed when invoking the version command without any arguments.

The mapping can contain anything else and will be passed to set_version when updating the version.

Source code in backend/src/hatchling/version/source/plugin/interface.py
@abstractmethod\ndef get_version_data(self) -> dict:\n\"\"\"\n    This should return a mapping with a `version` key representing the current version of the project and will be\n    displayed when invoking the [`version`](../../cli/reference.md#hatch-version) command without any arguments.\n    The mapping can contain anything else and will be passed to\n    [set_version](reference.md#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version)\n    when updating the version.\n    \"\"\"\n
"},{"location":"plugins/version-source/reference/#hatchling.version.source.plugin.interface.VersionSourceInterface.set_version","title":"set_version(version: str, version_data: dict) -> None","text":"

This should update the version to the first argument with the data provided during retrieval.

Source code in backend/src/hatchling/version/source/plugin/interface.py
def set_version(self, version: str, version_data: dict) -> None:\n\"\"\"\n    This should update the version to the first argument with the data provided during retrieval.\n    \"\"\"\nraise NotImplementedError\n
"},{"location":"plugins/version-source/regex/","title":"Regex version source","text":"

See the documentation for versioning.

"},{"location":"plugins/version-source/regex/#updates","title":"Updates","text":"

Setting the version is supported.

"},{"location":"plugins/version-source/regex/#configuration","title":"Configuration","text":"

The version source plugin name is regex.

pyproject.toml hatch.toml
[tool.hatch.version]\nsource = \"regex\"\n
[version]\nsource = \"regex\"\n
"},{"location":"plugins/version-source/regex/#options","title":"Options","text":"Option Description path (required) A relative path to a file containing the project's version pattern A regular expression that has a named group called version that represents the version. The default pattern looks for a variable named __version__ or VERSION that is set to a string containing the version, optionally prefixed with the lowercase letter v."}]} \ No newline at end of file diff --git a/dev/version/index.html b/dev/version/index.html index bae859248..e37b4a93a 100644 --- a/dev/version/index.html +++ b/dev/version/index.html @@ -33,4 +33,4 @@

When you want to release the final version, you would do:

$ hatch version release
 Old: 1.0.0rc0
 New: 1.0.0
-

Supported segments

Here are the supported segments and how they would influence an existing version of 1.0.0:

Segments New version
release 1.0.0
major 2.0.0
minor 1.1.0
micro
patch
fix
1.0.1
a
alpha
1.0.0a0
b
beta
1.0.0b0
c
rc
pre
preview
1.0.0rc0
r
rev
post
1.0.0.post0
dev 1.0.0.dev0
\ No newline at end of file +

Supported segments

Here are the supported segments and how they would influence an existing version of 1.0.0:

Segments New version
release 1.0.0
major 2.0.0
minor 1.1.0
micro
patch
fix
1.0.1
a
alpha
1.0.0a0
b
beta
1.0.0b0
c
rc
pre
preview
1.0.0rc0
r
rev
post
1.0.0.post0
dev 1.0.0.dev0
\ No newline at end of file