Skip to content

requires

requires ⚓︎

requires ~ dependency utils

Classes⚓︎

requires.Requirement(_import: str, _from: Optional[str] = None, _as: Optional[str] = None, pip: Optional[Union[str, bool]] = None, conda: Optional[Union[str, bool]] = None, conda_forge: Optional[Union[str, bool]] = None, details: Optional[Union[str, List[str]]] = None, lazy: bool = True) dataclass ⚓︎

Functions⚓︎
requires.Requirement.import_requirement() -> Any ⚓︎

Import and return the requirement

Source code in libs/requires/src/requires/core.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def import_requirement(self) -> Any:
    """Import and return the requirement"""
    try:
        if self._from is None:
            return import_module(self._import)
        req = import_module(self._from)
        # Import ok BUT the attr/thing imported from the module does not exist
        try:
            return getattr(req, self._import)
        except AttributeError as ae:
            raise RequirementAttributeError(
                "\n".join(
                    [
                        f"Module/Package(s) import AttributeError: `{self.import_string}`",
                        f"    AttributeError: {str(ae)}",
                    ]
                )
            ) from ae
    except ModuleNotFoundError:
        return RequirementProxy(req=self)

requires.RequirementAttributeError ⚓︎

Bases: AttributeError

Requirement attribute error

requires.RequirementDict ⚓︎

Bases: TypedDict

Requirement dict

requires.RequirementError ⚓︎

Bases: ModuleNotFoundError

Exception for requires

requires.RequirementProxy(req: Requirement) ⚓︎

Source code in libs/requires/src/requires/core.py
358
359
360
def __init__(self, req: Requirement) -> None:
    """Create a proxy for a requirement"""
    self.req = req
Functions⚓︎
requires.RequirementProxy.__bool__() -> bool ⚓︎

Prevent the proxy from being used in boolean contexts

Source code in libs/requires/src/requires/core.py
387
388
389
def __bool__(self) -> bool:
    """Prevent the proxy from being used in boolean contexts"""
    raise self.req.err()
requires.RequirementProxy.__call__(*args: Any, **kwargs: Any) -> Any ⚓︎

Raise the error when the proxy is called as a function

Source code in libs/requires/src/requires/core.py
362
363
364
def __call__(self, *args: Any, **kwargs: Any) -> Any:
    """Raise the error when the proxy is called as a function"""
    raise self.req.err()
requires.RequirementProxy.__getattr__(item: str) -> Any ⚓︎

Raise the error when any attribute is accessed

Source code in libs/requires/src/requires/core.py
366
367
368
def __getattr__(self, item: str) -> Any:
    """Raise the error when any attribute is accessed"""
    raise self.req.err()
requires.RequirementProxy.__getitem__(key: Any) -> Any ⚓︎

Raise the error when attempting to access items (e.g., proxy[key])

Source code in libs/requires/src/requires/core.py
376
377
378
def __getitem__(self, key: Any) -> Any:
    """Raise the error when attempting to access items (e.g., proxy[key])"""
    raise self.req.err()
requires.RequirementProxy.__setattr__(key: str, value: Any) -> None ⚓︎

Prevent the proxy from being used in attribute assignment

Source code in libs/requires/src/requires/core.py
380
381
382
383
384
385
def __setattr__(self, key: str, value: Any) -> None:
    """Prevent the proxy from being used in attribute assignment"""
    if key == "req":
        object.__setattr__(self, key, value)
    else:
        raise self.req.err()

requires.RequirementWarning ⚓︎

Bases: UserWarning

Warning for requires

requires.RequirementsMeta(requirements: Set[Requirement] = set()) dataclass ⚓︎

Functions⚓︎
requires.RequirementsMeta.preflight_check(*, warn: bool = False, on_missing: Optional[Callable[[Set[Requirement]], None]]) -> Set[Requirement] ⚓︎

Check if requirements are met

Parameters:

Name Type Description Default
warn bool

If True, issues warnings for missing requirements.

False
on_missing Optional[Callable[[Set[Requirement]], None]]

Callback to do something on missing requirements.

required

Returns:

Type Description
Set[Requirement]

Set[Requirement]: A set of missing requirements

Source code in libs/requires/src/requires/core.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def preflight_check(
    self,
    *,
    warn: bool = False,
    on_missing: Optional[Callable[[Set[Requirement]], None]],
) -> Set[Requirement]:
    """Check if requirements are met

    Args:
        warn (bool): If True, issues warnings for missing requirements.
        on_missing (Optional[Callable[[Set[Requirement]], None]]): Callback to do something on missing requirements.

    Returns:
        Set[Requirement]: A set of missing requirements

    """
    missing_requirements = {
        prox.req
        for prox in (req.import_requirement() for req in self.requirements)
        if isinstance(prox, RequirementProxy)
    }

    if missing_requirements and on_missing:
        on_missing(missing_requirements)

    if warn and missing_requirements:
        for req in missing_requirements:
            warnings.warn(req.warning(), RequirementWarning, stacklevel=2)

    return missing_requirements

Functions⚓︎

requires.preflight_check(*, warn: bool = False, on_missing: Optional[Callable[[Set[Requirement]], None]] = None) -> RequirementsMeta ⚓︎

Scan and check calling module scope for objs/fns wrapped with requirements.

Parameters:

Name Type Description Default
warn bool

If True, issues warnings for missing requirements.

False
on_missing Optional[Callable[[Set[Requirement]], None]]

Callback to do something on missing requirements.

None

Returns:

Name Type Description
RequirementsMeta RequirementsMeta

A RequirementsMeta instance with the requirements found during the check.

Source code in libs/requires/src/requires/core.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def preflight_check(
    *,
    warn: bool = False,
    on_missing: Optional[Callable[[Set[Requirement]], None]] = None,
) -> RequirementsMeta:
    """Scan and check calling module scope for objs/fns wrapped with requirements.

    Args:
        warn (bool): If True, issues warnings for missing requirements.
        on_missing (Optional[Callable[[Set[Requirement]], None]]): Callback to do something on missing requirements.

    Returns:
        RequirementsMeta: A RequirementsMeta instance with the requirements found during the check.

    """
    scope_reqs = scope_requirements()
    scope_reqs.preflight_check(warn=warn, on_missing=on_missing)
    return scope_reqs

requires.requires(*requirements: Union[str, TRequirementDict, Requirement], _import: Optional[str] = None, _as: Optional[str] = None, _from: Optional[str] = None, pip: Optional[Union[str, bool]] = None, conda: Optional[Union[str, bool]] = None, conda_forge: Optional[Union[str, bool]] = None, details: Optional[str] = None, lazy: Optional[bool] = None) -> Callable[[Callable[P, R]], Callable[P, R]] ⚓︎

Decorator to specify the packages a function or class requires

The decorator will not do anything unless a NameError is thrown. If a NameError is thrown then the required package is likely not installed and a RequirementError will be thrown with instructions on how to install the required packages.

Parameters:

Name Type Description Default
*requirements Union[str, TRequirementDict, Requirement]

Any number of required package names as strings

()
_import 'str'

IMPORT part of from {FROM} import {IMPORT} as {AS}

None
_as 'str'

AS part of from {FROM} import {IMPORT} as {AS}

None
_from 'str'

FROM part of from {FROM} import {IMPORT} as {AS}

None
pip Optional[Union[str, bool]]

pip install name

None
conda Optional[Union[str, bool]]

conda install name

None
conda_forge Optional[Union[str, bool]]

conda-forge install name

None
details str

details to be displayed in the error message

None
lazy bool

If True, the requirement is loaded lazily

None

Returns:

Type Description
Callable[[Callable[P, R]], Callable[P, R]]

Function wrapped such that in the event of a NameError a helpful

Callable[[Callable[P, R]], Callable[P, R]]

error is raised.

Raises:

Type Description
ValueError

If requirements or kwargs are given

Source code in libs/requires/src/requires/core.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def requires(
    *requirements: Union[str, TRequirementDict, Requirement],
    _import: Optional[str] = None,
    _as: Optional[str] = None,
    _from: Optional[str] = None,
    pip: Optional[Union[str, bool]] = None,
    conda: Optional[Union[str, bool]] = None,
    conda_forge: Optional[Union[str, bool]] = None,
    details: Optional[str] = None,
    lazy: Optional[bool] = None,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
    """Decorator to specify the packages a function or class requires

    The decorator will not do anything unless a NameError is thrown. If a
    NameError is thrown then the required package is likely not installed and
    a `RequirementError` will be thrown with instructions on how to install
    the required packages.


    Args:
        *requirements: Any number of required package names as strings
        _import ('str'): `IMPORT` part of `from {FROM} import {IMPORT} as {AS}`
        _as ('str'): `AS` part of `from {FROM} import {IMPORT} as {AS}`
        _from ('str'): `FROM` part of `from {FROM} import {IMPORT} as {AS}`
        pip (Optional[Union[str, bool]]): pip install name
        conda (Optional[Union[str, bool]]): conda install name
        conda_forge (Optional[Union[str, bool]]): conda-forge install name
        details (str): details to be displayed in the error message
        lazy (bool): If True, the requirement is loaded lazily

    Returns:
        Function wrapped such that in the event of a `NameError` a helpful
        error is raised.

    Raises:
        ValueError: If requirements or kwargs are given

    """
    _kwargs = (_import, _from, _as, pip, conda, conda_forge, details, lazy)
    if any(kw for kw in _kwargs):
        if requirements:
            raise ValueError("*requirements and **kwargs are mutually exclusive")
        _requirements = [
            Requirement(
                _import=str(_import),
                _from=_from,
                _as=_as,
                pip=pip,
                conda=conda,
                conda_forge=conda_forge,
                details=details,
                lazy=lazy if lazy is not None else True,
            )
        ]
    else:
        if not requirements:
            raise ValueError("No requirements specified in 'requires' decorator.")
        _requirements = make_requirements(list(requirements))

    def _requires_dec(f: Callable[P, R]) -> Callable[P, R]:
        _wrapped_fn = f
        requirements_meta = RequirementsMeta(requirements=set())
        for el in _requirements:
            _wrapped_fn = el(_wrapped_fn)
            requirements_meta.add(el)
        _wrapped_fn.__requires__ = requirements_meta  # type: ignore[attr-defined]
        wraps(f)(_wrapped_fn)
        return _wrapped_fn

    return _requires_dec

requires.requires_python(version: str) -> None ⚓︎

Decorator to specify the python version a function or class requires

Source code in libs/requires/src/requires/core.py
596
597
598
def requires_python(version: str) -> None:
    """Decorator to specify the python version a function or class requires"""
    raise NotImplementedError("Not yet implemented (TODO)")

requires.scope_requirements(debug: bool = False) -> RequirementsMeta ⚓︎

Scan and check calling module scope for objs/fns wrapped with requirements.

Parameters:

Name Type Description Default
debug bool

If True, log debug info.

False

Returns:

Name Type Description
RequirementsMeta RequirementsMeta

A RequirementsMeta instance with the requirements found during the check.

Source code in libs/requires/src/requires/core.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
def scope_requirements(debug: bool = False) -> RequirementsMeta:
    """Scan and check calling module scope for objs/fns wrapped with requirements.

    Args:
        debug (bool): If True, log debug info.

    Returns:
        RequirementsMeta: A RequirementsMeta instance with the requirements found during the check.

    """
    calling_frame = sys._getframe(2)
    _f_globals = calling_frame.f_globals
    if debug:
        log.debug(f"calling_frame: {calling_frame}")
        log.debug(f"_f_globals: {_f_globals}")
    scope_reqs = RequirementsMeta(requirements=set())

    for name, obj in _f_globals.items():
        if hasattr(obj, "__requires__"):
            log.debug(f"Found obj with requirements: {name} -> {obj}")
            requirements_meta = obj.__requires__
            if not isinstance(requirements_meta, RequirementsMeta):
                raise RequirementError(
                    f"Expected a RequirementsMeta instance, got {type(requirements_meta)}"
                )
            scope_reqs.update(requirements_meta.requirements)
    return scope_reqs

Modules⚓︎

requires.__about__ ⚓︎

Package metadata/info

requires.__main__ ⚓︎

pkg entry ~ python -m requires

Functions⚓︎
requires.__main__.main() -> None ⚓︎

Print package metadata

Source code in libs/requires/src/requires/__main__.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def main() -> None:
    """Print package metadata"""
    import json

    sys.stdout.write(
        json.dumps(
            {
                "package": __title__,
                "version": __version__,
                "pkgroot": __pkgroot__,
            },
            indent=2,
        )
    )

requires.core ⚓︎

Core for requires

Classes⚓︎
requires.core.Requirement(_import: str, _from: Optional[str] = None, _as: Optional[str] = None, pip: Optional[Union[str, bool]] = None, conda: Optional[Union[str, bool]] = None, conda_forge: Optional[Union[str, bool]] = None, details: Optional[Union[str, List[str]]] = None, lazy: bool = True) dataclass ⚓︎
Functions⚓︎
requires.core.Requirement.import_requirement() -> Any ⚓︎

Import and return the requirement

Source code in libs/requires/src/requires/core.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def import_requirement(self) -> Any:
    """Import and return the requirement"""
    try:
        if self._from is None:
            return import_module(self._import)
        req = import_module(self._from)
        # Import ok BUT the attr/thing imported from the module does not exist
        try:
            return getattr(req, self._import)
        except AttributeError as ae:
            raise RequirementAttributeError(
                "\n".join(
                    [
                        f"Module/Package(s) import AttributeError: `{self.import_string}`",
                        f"    AttributeError: {str(ae)}",
                    ]
                )
            ) from ae
    except ModuleNotFoundError:
        return RequirementProxy(req=self)
requires.core.RequirementAttributeError ⚓︎

Bases: AttributeError

Requirement attribute error

requires.core.RequirementDict ⚓︎

Bases: TypedDict

Requirement dict

requires.core.RequirementError ⚓︎

Bases: ModuleNotFoundError

Exception for requires

requires.core.RequirementProxy(req: Requirement) ⚓︎
Source code in libs/requires/src/requires/core.py
358
359
360
def __init__(self, req: Requirement) -> None:
    """Create a proxy for a requirement"""
    self.req = req
Functions⚓︎
requires.core.RequirementProxy.__bool__() -> bool ⚓︎

Prevent the proxy from being used in boolean contexts

Source code in libs/requires/src/requires/core.py
387
388
389
def __bool__(self) -> bool:
    """Prevent the proxy from being used in boolean contexts"""
    raise self.req.err()
requires.core.RequirementProxy.__call__(*args: Any, **kwargs: Any) -> Any ⚓︎

Raise the error when the proxy is called as a function

Source code in libs/requires/src/requires/core.py
362
363
364
def __call__(self, *args: Any, **kwargs: Any) -> Any:
    """Raise the error when the proxy is called as a function"""
    raise self.req.err()
requires.core.RequirementProxy.__getattr__(item: str) -> Any ⚓︎

Raise the error when any attribute is accessed

Source code in libs/requires/src/requires/core.py
366
367
368
def __getattr__(self, item: str) -> Any:
    """Raise the error when any attribute is accessed"""
    raise self.req.err()
requires.core.RequirementProxy.__getitem__(key: Any) -> Any ⚓︎

Raise the error when attempting to access items (e.g., proxy[key])

Source code in libs/requires/src/requires/core.py
376
377
378
def __getitem__(self, key: Any) -> Any:
    """Raise the error when attempting to access items (e.g., proxy[key])"""
    raise self.req.err()
requires.core.RequirementProxy.__setattr__(key: str, value: Any) -> None ⚓︎

Prevent the proxy from being used in attribute assignment

Source code in libs/requires/src/requires/core.py
380
381
382
383
384
385
def __setattr__(self, key: str, value: Any) -> None:
    """Prevent the proxy from being used in attribute assignment"""
    if key == "req":
        object.__setattr__(self, key, value)
    else:
        raise self.req.err()
requires.core.RequirementWarning ⚓︎

Bases: UserWarning

Warning for requires

requires.core.RequirementsError ⚓︎

Bases: ModuleNotFoundError

Exception for multiple requirements

requires.core.RequirementsMeta(requirements: Set[Requirement] = set()) dataclass ⚓︎
Functions⚓︎
requires.core.RequirementsMeta.preflight_check(*, warn: bool = False, on_missing: Optional[Callable[[Set[Requirement]], None]]) -> Set[Requirement] ⚓︎

Check if requirements are met

Parameters:

Name Type Description Default
warn bool

If True, issues warnings for missing requirements.

False
on_missing Optional[Callable[[Set[Requirement]], None]]

Callback to do something on missing requirements.

required

Returns:

Type Description
Set[Requirement]

Set[Requirement]: A set of missing requirements

Source code in libs/requires/src/requires/core.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def preflight_check(
    self,
    *,
    warn: bool = False,
    on_missing: Optional[Callable[[Set[Requirement]], None]],
) -> Set[Requirement]:
    """Check if requirements are met

    Args:
        warn (bool): If True, issues warnings for missing requirements.
        on_missing (Optional[Callable[[Set[Requirement]], None]]): Callback to do something on missing requirements.

    Returns:
        Set[Requirement]: A set of missing requirements

    """
    missing_requirements = {
        prox.req
        for prox in (req.import_requirement() for req in self.requirements)
        if isinstance(prox, RequirementProxy)
    }

    if missing_requirements and on_missing:
        on_missing(missing_requirements)

    if warn and missing_requirements:
        for req in missing_requirements:
            warnings.warn(req.warning(), RequirementWarning, stacklevel=2)

    return missing_requirements
Functions⚓︎
requires.core.parse_name_error(ne: NameError) -> List[str] ⚓︎

Return a list of the missing items specified in a NameError

Parameters:

Name Type Description Default
ne NameError

NameError object

required

Returns:

Name Type Description
str List[str]

name of the missing thing/pkg/module/function

Examples:

>>> args = ("name 'path' is not defined",)
>>> ne = NameError(*args)
>>> parse_name_error(ne)
['path']
Source code in libs/requires/src/requires/core.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def parse_name_error(ne: NameError) -> List[str]:
    """Return a list of the missing items specified in a `NameError`

    Args:
        ne (NameError): NameError object

    Returns:
        str: name of the missing thing/pkg/module/function

    Examples:
        >>> args = ("name 'path' is not defined",)
        >>> ne = NameError(*args)
        >>> parse_name_error(ne)
        ['path']

    """
    return [el.split(" ")[1].strip("'") for el in ne.args]
requires.core.preflight_check(*, warn: bool = False, on_missing: Optional[Callable[[Set[Requirement]], None]] = None) -> RequirementsMeta ⚓︎

Scan and check calling module scope for objs/fns wrapped with requirements.

Parameters:

Name Type Description Default
warn bool

If True, issues warnings for missing requirements.

False
on_missing Optional[Callable[[Set[Requirement]], None]]

Callback to do something on missing requirements.

None

Returns:

Name Type Description
RequirementsMeta RequirementsMeta

A RequirementsMeta instance with the requirements found during the check.

Source code in libs/requires/src/requires/core.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def preflight_check(
    *,
    warn: bool = False,
    on_missing: Optional[Callable[[Set[Requirement]], None]] = None,
) -> RequirementsMeta:
    """Scan and check calling module scope for objs/fns wrapped with requirements.

    Args:
        warn (bool): If True, issues warnings for missing requirements.
        on_missing (Optional[Callable[[Set[Requirement]], None]]): Callback to do something on missing requirements.

    Returns:
        RequirementsMeta: A RequirementsMeta instance with the requirements found during the check.

    """
    scope_reqs = scope_requirements()
    scope_reqs.preflight_check(warn=warn, on_missing=on_missing)
    return scope_reqs
requires.core.requires(*requirements: Union[str, TRequirementDict, Requirement], _import: Optional[str] = None, _as: Optional[str] = None, _from: Optional[str] = None, pip: Optional[Union[str, bool]] = None, conda: Optional[Union[str, bool]] = None, conda_forge: Optional[Union[str, bool]] = None, details: Optional[str] = None, lazy: Optional[bool] = None) -> Callable[[Callable[P, R]], Callable[P, R]] ⚓︎

Decorator to specify the packages a function or class requires

The decorator will not do anything unless a NameError is thrown. If a NameError is thrown then the required package is likely not installed and a RequirementError will be thrown with instructions on how to install the required packages.

Parameters:

Name Type Description Default
*requirements Union[str, TRequirementDict, Requirement]

Any number of required package names as strings

()
_import 'str'

IMPORT part of from {FROM} import {IMPORT} as {AS}

None
_as 'str'

AS part of from {FROM} import {IMPORT} as {AS}

None
_from 'str'

FROM part of from {FROM} import {IMPORT} as {AS}

None
pip Optional[Union[str, bool]]

pip install name

None
conda Optional[Union[str, bool]]

conda install name

None
conda_forge Optional[Union[str, bool]]

conda-forge install name

None
details str

details to be displayed in the error message

None
lazy bool

If True, the requirement is loaded lazily

None

Returns:

Type Description
Callable[[Callable[P, R]], Callable[P, R]]

Function wrapped such that in the event of a NameError a helpful

Callable[[Callable[P, R]], Callable[P, R]]

error is raised.

Raises:

Type Description
ValueError

If requirements or kwargs are given

Source code in libs/requires/src/requires/core.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def requires(
    *requirements: Union[str, TRequirementDict, Requirement],
    _import: Optional[str] = None,
    _as: Optional[str] = None,
    _from: Optional[str] = None,
    pip: Optional[Union[str, bool]] = None,
    conda: Optional[Union[str, bool]] = None,
    conda_forge: Optional[Union[str, bool]] = None,
    details: Optional[str] = None,
    lazy: Optional[bool] = None,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
    """Decorator to specify the packages a function or class requires

    The decorator will not do anything unless a NameError is thrown. If a
    NameError is thrown then the required package is likely not installed and
    a `RequirementError` will be thrown with instructions on how to install
    the required packages.


    Args:
        *requirements: Any number of required package names as strings
        _import ('str'): `IMPORT` part of `from {FROM} import {IMPORT} as {AS}`
        _as ('str'): `AS` part of `from {FROM} import {IMPORT} as {AS}`
        _from ('str'): `FROM` part of `from {FROM} import {IMPORT} as {AS}`
        pip (Optional[Union[str, bool]]): pip install name
        conda (Optional[Union[str, bool]]): conda install name
        conda_forge (Optional[Union[str, bool]]): conda-forge install name
        details (str): details to be displayed in the error message
        lazy (bool): If True, the requirement is loaded lazily

    Returns:
        Function wrapped such that in the event of a `NameError` a helpful
        error is raised.

    Raises:
        ValueError: If requirements or kwargs are given

    """
    _kwargs = (_import, _from, _as, pip, conda, conda_forge, details, lazy)
    if any(kw for kw in _kwargs):
        if requirements:
            raise ValueError("*requirements and **kwargs are mutually exclusive")
        _requirements = [
            Requirement(
                _import=str(_import),
                _from=_from,
                _as=_as,
                pip=pip,
                conda=conda,
                conda_forge=conda_forge,
                details=details,
                lazy=lazy if lazy is not None else True,
            )
        ]
    else:
        if not requirements:
            raise ValueError("No requirements specified in 'requires' decorator.")
        _requirements = make_requirements(list(requirements))

    def _requires_dec(f: Callable[P, R]) -> Callable[P, R]:
        _wrapped_fn = f
        requirements_meta = RequirementsMeta(requirements=set())
        for el in _requirements:
            _wrapped_fn = el(_wrapped_fn)
            requirements_meta.add(el)
        _wrapped_fn.__requires__ = requirements_meta  # type: ignore[attr-defined]
        wraps(f)(_wrapped_fn)
        return _wrapped_fn

    return _requires_dec
requires.core.requires_python(version: str) -> None ⚓︎

Decorator to specify the python version a function or class requires

Source code in libs/requires/src/requires/core.py
596
597
598
def requires_python(version: str) -> None:
    """Decorator to specify the python version a function or class requires"""
    raise NotImplementedError("Not yet implemented (TODO)")
requires.core.scope_requirements(debug: bool = False) -> RequirementsMeta ⚓︎

Scan and check calling module scope for objs/fns wrapped with requirements.

Parameters:

Name Type Description Default
debug bool

If True, log debug info.

False

Returns:

Name Type Description
RequirementsMeta RequirementsMeta

A RequirementsMeta instance with the requirements found during the check.

Source code in libs/requires/src/requires/core.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
def scope_requirements(debug: bool = False) -> RequirementsMeta:
    """Scan and check calling module scope for objs/fns wrapped with requirements.

    Args:
        debug (bool): If True, log debug info.

    Returns:
        RequirementsMeta: A RequirementsMeta instance with the requirements found during the check.

    """
    calling_frame = sys._getframe(2)
    _f_globals = calling_frame.f_globals
    if debug:
        log.debug(f"calling_frame: {calling_frame}")
        log.debug(f"_f_globals: {_f_globals}")
    scope_reqs = RequirementsMeta(requirements=set())

    for name, obj in _f_globals.items():
        if hasattr(obj, "__requires__"):
            log.debug(f"Found obj with requirements: {name} -> {obj}")
            requirements_meta = obj.__requires__
            if not isinstance(requirements_meta, RequirementsMeta):
                raise RequirementError(
                    f"Expected a RequirementsMeta instance, got {type(requirements_meta)}"
                )
            scope_reqs.update(requirements_meta.requirements)
    return scope_reqs

requires.shed ⚓︎

Pre-fab requirements

Classes⚓︎