pydepinject


Namepydepinject JSON
Version 0.0.3.dev0 PyPI version JSON
download
home_pageNone
SummaryA package to dynamically inject requirements into a virtual environment.
upload_time2025-08-11 03:59:53
maintainerNone
docs_urlNone
authorpydepinject
requires_python>=3.10
licenseNone
keywords virtualenv requirements dependency management
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Requirement Manager

This project provides a `RequirementManager` (`requires` is an alias) class to manage Python package requirements using virtual environments. It can be used as a decorator or context manager to ensure specific packages are installed and available during the execution of a function or code block.

## Features

- Automatically creates and manages virtual environments.
- Checks if the required packages are already installed.
- Installs packages if they are not already available.
- Supports ephemeral virtual environments that are deleted after use.
- Can be used as a decorator or context manager.

## Installation

`pip install pydepinject`

To use the `uv` backend for faster environment and package management, ensure `uv` is installed separately. You can find installation instructions at [https://github.com/astral-sh/uv](https://github.com/astral-sh/uv).


## Usage

### Decorator

To use the `requires` as a decorator, simply decorate your function with the required packages:

```python
from pydepinject import requires


@requires("requests", "numpy")
def my_function():
    import requests
    import numpy as np
    print(requests.__version__)
    print(np.__version__)

my_function()
```

### Context Manager

You can also use the `requires` as a context manager:

```python
from pydepinject import requires


with requires("requests", "numpy"):
    import requests
    import numpy as np
    print(requests.__version__)
    print(np.__version__)
```

### Virtual Environment with specific name

The `requires` can create a virtual environment with a specific name:

```python
@requires("requests", venv_name="myenv")
def my_function():
    import requests
    print(requests.__version__)


with requires("pylint", "requests", venv_name="myenv"):
    import pylint
    print(pylint.__version__)
    import requests  # This is also available here because it was installed in the same virtual environment
    print(requests.__version__)


# The virtual environment name can also be set as PYDEPINJECT_VENV_NAME environment variable
import os
os.environ["PYDEPINJECT_VENV_NAME"] = "myenv"

@requires("requests")
def my_function():
    import requests
    print(requests.__version__)


with requires("pylint", "requests"):
    import pylint
    print(pylint.__version__)
    import requests  # This is also available here because it was installed in the same virtual environment
    print(requests.__version__)
```



### Reusable Virtual Environments

The `requires` can create named virtual environments and reuse them across multiple functions or code blocks:

```python
@requires("requests", venv_name="myenv", ephemeral=False)
def my_function():
    import requests
    print(requests.__version__)


with requires("pylint", "requests", venv_name="myenv", ephemeral=False):
    import pylint
    print(pylint.__version__)
    import requests  # This is also available here because it was installed in the same virtual environment
    print(requests.__version__)
```

### Managing Virtual Environments

The `requires` can automatically delete ephemeral virtual environments after use. This is useful when you want to ensure that the virtual environment is clean and does not persist after the function or code block completes:

```python
@requires("requests", venv_name="myenv", ephemeral=True)
def my_function():
    import requests
    print(requests.__version__)

my_function()
```

### Forcing Virtual Environment Recreation

If you need to ensure a completely clean environment, you can force its recreation using the `recreate=True` parameter. This will delete and rebuild the virtual environment even if it already exists.

```python
from pydepinject import requires

# This will delete the "my-clean-env" venv if it exists and create it from scratch
@requires("requests", venv_name="my-clean-env", recreate=True)
def my_function():
    import requests
    print(requests.__version__)

my_function()
```

## Logging

This library uses Python's standard logging but does not configure handlers or levels by default. Configure logging in your application to see debug output:

```python
import logging

logging.basicConfig(level=logging.INFO)  # or DEBUG for verbose output
logging.getLogger("pydepinject").setLevel(logging.DEBUG)
```

You can also integrate with your application's logging setup (structlog, rich logging, etc.) by attaching handlers as you normally would.
## Backend selection

By default, backends are tried in priority order "uv|venv". If uv is installed on your system, it will be preferred for faster environment creation and installs; otherwise the standard library venv backend is used.

You can control backend selection:
- Environment variable: set PYDEPINJECT_VENV_BACKEND, e.g. `PYDEPINJECT_VENV_BACKEND=venv` or `PYDEPINJECT_VENV_BACKEND=uv|venv`.
- API param: pass `venv_backend="uv"`, `"venv"`, or a pipe-separated list like `"uv|venv"` to requires/RequirementManager.

On Windows, paths (Scripts, Lib/site-packages) are handled automatically.

## Advanced options

### Additional installer arguments
You can forward extra arguments to the underlying installer (pip or uv pip) via `install_args`. This is useful for custom indexes, constraints files, proxies, etc.

```python
from pydepinject import requires

@requires(
    "requests",
    install_args=(
        "--index-url", "https://pypi.myorg/simple",
        "--upgrade-strategy", "eager",
    ),
    venv_backend="venv",
)
def my_function():
    import requests
    print(requests.__version__)
```

These arguments are appended to the installer command.

### Virtual environment identity
For unnamed environments, a unique directory is generated based on a stable identity key. This key is derived from:
- The set of requirements, which are normalized, canonicalized (e.g., `PyYAML` becomes `pyyaml`), and sorted alphabetically to ensure a consistent order.
- The active Python version tag (e.g., `py3.11`).
- The selected backend (`uv` or `venv`).
- A short hash of the current Python interpreter's path to distinguish between different Python installations.

This process guarantees that identical dependency sets produce the same virtual environment, while any change in requirements, Python version, or backend results in a new, distinct environment. Named environments (created using the `venv_name` parameter) are not affected by this hashing mechanism.

### Venv metadata
After successful installs, a metadata file `.pydepinject-{timestamp}.json` is written into the venv directory. It records:
- pydepinject version, backend, Python version, interpreter path
- Target platform, requested packages, forwarded install args
- An ISO 8601 timestamp (UTC)

There might be multiple metadata files if the venv is reused across different runs with different requirements or install args. Each file is timestamped to avoid collisions.

This helps with debugging and reproducibility.

## Configuration with Environment Variables

`pydepinject` can be configured using the following environment variables:

- **`PYDEPINJECT_VENV_ROOT`**: Specifies the root directory where virtual environments are stored. If not set, a default temporary directory is used.
- **`PYDEPINJECT_VENV_NAME`**: Sets a default name for the virtual environment, which can be useful for creating persistent, reusable environments across different runs.
- **`PYDEPINJECT_VENV_BACKEND`**: Defines the virtual environment backend to use. Supported values are `uv` and `venv`. `uv` is preferred for its speed.

These variables provide a convenient way to standardize behavior in CI/CD pipelines or development environments.

## Unit Tests

Unit tests are provided to verify the functionality of the `requires`. The tests use `pytest` and cover various scenarios including decorator usage, context manager usage, ephemeral environments, and more.

### Running Tests

To run the unit tests, ensure you have `pytest` installed, and then execute the following command:

```bash
pytest
```

## License

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "pydepinject",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "virtualenv, requirements, dependency management",
    "author": "pydepinject",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/8d/f8/81ecf180a64bd2edc5195b554c0eaa146c47aa71ea74eac0e691ca8b8ed4/pydepinject-0.0.3.dev0.tar.gz",
    "platform": null,
    "description": "# Requirement Manager\n\nThis project provides a `RequirementManager` (`requires` is an alias) class to manage Python package requirements using virtual environments. It can be used as a decorator or context manager to ensure specific packages are installed and available during the execution of a function or code block.\n\n## Features\n\n- Automatically creates and manages virtual environments.\n- Checks if the required packages are already installed.\n- Installs packages if they are not already available.\n- Supports ephemeral virtual environments that are deleted after use.\n- Can be used as a decorator or context manager.\n\n## Installation\n\n`pip install pydepinject`\n\nTo use the `uv` backend for faster environment and package management, ensure `uv` is installed separately. You can find installation instructions at [https://github.com/astral-sh/uv](https://github.com/astral-sh/uv).\n\n\n## Usage\n\n### Decorator\n\nTo use the `requires` as a decorator, simply decorate your function with the required packages:\n\n```python\nfrom pydepinject import requires\n\n\n@requires(\"requests\", \"numpy\")\ndef my_function():\n    import requests\n    import numpy as np\n    print(requests.__version__)\n    print(np.__version__)\n\nmy_function()\n```\n\n### Context Manager\n\nYou can also use the `requires` as a context manager:\n\n```python\nfrom pydepinject import requires\n\n\nwith requires(\"requests\", \"numpy\"):\n    import requests\n    import numpy as np\n    print(requests.__version__)\n    print(np.__version__)\n```\n\n### Virtual Environment with specific name\n\nThe `requires` can create a virtual environment with a specific name:\n\n```python\n@requires(\"requests\", venv_name=\"myenv\")\ndef my_function():\n    import requests\n    print(requests.__version__)\n\n\nwith requires(\"pylint\", \"requests\", venv_name=\"myenv\"):\n    import pylint\n    print(pylint.__version__)\n    import requests  # This is also available here because it was installed in the same virtual environment\n    print(requests.__version__)\n\n\n# The virtual environment name can also be set as PYDEPINJECT_VENV_NAME environment variable\nimport os\nos.environ[\"PYDEPINJECT_VENV_NAME\"] = \"myenv\"\n\n@requires(\"requests\")\ndef my_function():\n    import requests\n    print(requests.__version__)\n\n\nwith requires(\"pylint\", \"requests\"):\n    import pylint\n    print(pylint.__version__)\n    import requests  # This is also available here because it was installed in the same virtual environment\n    print(requests.__version__)\n```\n\n\n\n### Reusable Virtual Environments\n\nThe `requires` can create named virtual environments and reuse them across multiple functions or code blocks:\n\n```python\n@requires(\"requests\", venv_name=\"myenv\", ephemeral=False)\ndef my_function():\n    import requests\n    print(requests.__version__)\n\n\nwith requires(\"pylint\", \"requests\", venv_name=\"myenv\", ephemeral=False):\n    import pylint\n    print(pylint.__version__)\n    import requests  # This is also available here because it was installed in the same virtual environment\n    print(requests.__version__)\n```\n\n### Managing Virtual Environments\n\nThe `requires` can automatically delete ephemeral virtual environments after use. This is useful when you want to ensure that the virtual environment is clean and does not persist after the function or code block completes:\n\n```python\n@requires(\"requests\", venv_name=\"myenv\", ephemeral=True)\ndef my_function():\n    import requests\n    print(requests.__version__)\n\nmy_function()\n```\n\n### Forcing Virtual Environment Recreation\n\nIf you need to ensure a completely clean environment, you can force its recreation using the `recreate=True` parameter. This will delete and rebuild the virtual environment even if it already exists.\n\n```python\nfrom pydepinject import requires\n\n# This will delete the \"my-clean-env\" venv if it exists and create it from scratch\n@requires(\"requests\", venv_name=\"my-clean-env\", recreate=True)\ndef my_function():\n    import requests\n    print(requests.__version__)\n\nmy_function()\n```\n\n## Logging\n\nThis library uses Python's standard logging but does not configure handlers or levels by default. Configure logging in your application to see debug output:\n\n```python\nimport logging\n\nlogging.basicConfig(level=logging.INFO)  # or DEBUG for verbose output\nlogging.getLogger(\"pydepinject\").setLevel(logging.DEBUG)\n```\n\nYou can also integrate with your application's logging setup (structlog, rich logging, etc.) by attaching handlers as you normally would.\n## Backend selection\n\nBy default, backends are tried in priority order \"uv|venv\". If uv is installed on your system, it will be preferred for faster environment creation and installs; otherwise the standard library venv backend is used.\n\nYou can control backend selection:\n- Environment variable: set PYDEPINJECT_VENV_BACKEND, e.g. `PYDEPINJECT_VENV_BACKEND=venv` or `PYDEPINJECT_VENV_BACKEND=uv|venv`.\n- API param: pass `venv_backend=\"uv\"`, `\"venv\"`, or a pipe-separated list like `\"uv|venv\"` to requires/RequirementManager.\n\nOn Windows, paths (Scripts, Lib/site-packages) are handled automatically.\n\n## Advanced options\n\n### Additional installer arguments\nYou can forward extra arguments to the underlying installer (pip or uv pip) via `install_args`. This is useful for custom indexes, constraints files, proxies, etc.\n\n```python\nfrom pydepinject import requires\n\n@requires(\n    \"requests\",\n    install_args=(\n        \"--index-url\", \"https://pypi.myorg/simple\",\n        \"--upgrade-strategy\", \"eager\",\n    ),\n    venv_backend=\"venv\",\n)\ndef my_function():\n    import requests\n    print(requests.__version__)\n```\n\nThese arguments are appended to the installer command.\n\n### Virtual environment identity\nFor unnamed environments, a unique directory is generated based on a stable identity key. This key is derived from:\n- The set of requirements, which are normalized, canonicalized (e.g., `PyYAML` becomes `pyyaml`), and sorted alphabetically to ensure a consistent order.\n- The active Python version tag (e.g., `py3.11`).\n- The selected backend (`uv` or `venv`).\n- A short hash of the current Python interpreter's path to distinguish between different Python installations.\n\nThis process guarantees that identical dependency sets produce the same virtual environment, while any change in requirements, Python version, or backend results in a new, distinct environment. Named environments (created using the `venv_name` parameter) are not affected by this hashing mechanism.\n\n### Venv metadata\nAfter successful installs, a metadata file `.pydepinject-{timestamp}.json` is written into the venv directory. It records:\n- pydepinject version, backend, Python version, interpreter path\n- Target platform, requested packages, forwarded install args\n- An ISO 8601 timestamp (UTC)\n\nThere might be multiple metadata files if the venv is reused across different runs with different requirements or install args. Each file is timestamped to avoid collisions.\n\nThis helps with debugging and reproducibility.\n\n## Configuration with Environment Variables\n\n`pydepinject` can be configured using the following environment variables:\n\n- **`PYDEPINJECT_VENV_ROOT`**: Specifies the root directory where virtual environments are stored. If not set, a default temporary directory is used.\n- **`PYDEPINJECT_VENV_NAME`**: Sets a default name for the virtual environment, which can be useful for creating persistent, reusable environments across different runs.\n- **`PYDEPINJECT_VENV_BACKEND`**: Defines the virtual environment backend to use. Supported values are `uv` and `venv`. `uv` is preferred for its speed.\n\nThese variables provide a convenient way to standardize behavior in CI/CD pipelines or development environments.\n\n## Unit Tests\n\nUnit tests are provided to verify the functionality of the `requires`. The tests use `pytest` and cover various scenarios including decorator usage, context manager usage, ephemeral environments, and more.\n\n### Running Tests\n\nTo run the unit tests, ensure you have `pytest` installed, and then execute the following command:\n\n```bash\npytest\n```\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A package to dynamically inject requirements into a virtual environment.",
    "version": "0.0.3.dev0",
    "project_urls": {
        "documentation": "https://github.com/pydepinject/pydepinject",
        "homepage": "https://github.com/pydepinject/pydepinject",
        "repository": "https://github.com/pydepinject/pydepinject"
    },
    "split_keywords": [
        "virtualenv",
        " requirements",
        " dependency management"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "391e1b068ae7141787e962943d485a908dcd569b9891f18766049206581512f1",
                "md5": "d9b41cb7dddd4068d477797bc5a50732",
                "sha256": "16a00bd1b60573645e87e96d2eb66a98d4125e824251ffaae79f3eec20a953ba"
            },
            "downloads": -1,
            "filename": "pydepinject-0.0.3.dev0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d9b41cb7dddd4068d477797bc5a50732",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 10816,
            "upload_time": "2025-08-11T03:59:52",
            "upload_time_iso_8601": "2025-08-11T03:59:52.184132Z",
            "url": "https://files.pythonhosted.org/packages/39/1e/1b068ae7141787e962943d485a908dcd569b9891f18766049206581512f1/pydepinject-0.0.3.dev0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8df881ecf180a64bd2edc5195b554c0eaa146c47aa71ea74eac0e691ca8b8ed4",
                "md5": "bb1def9d0d499b36078737178c35653d",
                "sha256": "20efe2201bb491e16dd397bbfeeab7abf96feecb16aeba3fe36549c9b367c346"
            },
            "downloads": -1,
            "filename": "pydepinject-0.0.3.dev0.tar.gz",
            "has_sig": false,
            "md5_digest": "bb1def9d0d499b36078737178c35653d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 27463,
            "upload_time": "2025-08-11T03:59:53",
            "upload_time_iso_8601": "2025-08-11T03:59:53.097153Z",
            "url": "https://files.pythonhosted.org/packages/8d/f8/81ecf180a64bd2edc5195b554c0eaa146c47aa71ea74eac0e691ca8b8ed4/pydepinject-0.0.3.dev0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-11 03:59:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pydepinject",
    "github_project": "pydepinject",
    "github_not_found": true,
    "lcname": "pydepinject"
}
        
Elapsed time: 2.60335s