python_code
stringlengths 0
108k
|
---|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **PEP-agnostic type hint tester utilities** (i.e., callables
validating arbitrary objects to be type hints supported by :mod:`beartype`,
regardless of whether those hints comply with PEP standards or not).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._data.hint.pep.datapeprepr import HINTS_REPR_IGNORABLE_SHALLOW
from beartype._util.cache.utilcachecall import callable_cached
from beartype._util.hint.nonpep.utilnonpeptest import (
die_unless_hint_nonpep,
is_hint_nonpep,
)
from beartype._util.hint.pep.utilpeptest import (
die_if_hint_pep_unsupported,
is_hint_pep,
is_hint_pep_supported,
)
# ....................{ VALIDATORS }....................
def die_unless_hint(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is a **supported type hint**
(i.e., object supported by the :func:`beartype.beartype` decorator as a
valid type hint annotating callable parameters and return values).
Specifically, this function raises an exception if this object is neither:
* A **supported PEP-compliant type hint** (i.e., :mod:`beartype`-agnostic
annotation compliant with annotation-centric PEPs currently supported
by the :func:`beartype.beartype` decorator).
* A **PEP-noncompliant type hint** (i.e., :mod:`beartype`-specific
annotation intentionally *not* compliant with annotation-centric PEPs).
Efficiency
----------
This validator is effectively (but technically *not*) memoized. The passed
``exception_prefix`` parameter is usually unique to each call to this
validator; memoizing this validator would uselessly consume excess space
*without* improving time efficiency. Instead, this validator first calls the
memoized :func:`is_hint_pep` tester. If that tester returns ``True``, this
validator immediately returns ``True`` and is thus effectively memoized;
else, this validator inefficiently raises a human-readable exception without
memoization. Since efficiency is mostly irrelevant in exception handling,
this validator remains effectively memoized.
Parameters
----------
hint : object
Object to be validated.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintPepUnsupportedException
If this object is a PEP-compliant type hint currently unsupported by
the :func:`beartype.beartype` decorator.
BeartypeDecorHintNonpepException
If this object is neither a:
* Supported PEP-compliant type hint.
* Supported PEP-noncompliant type hint.
'''
# If this object is a supported type hint, reduce to a noop.
if is_hint(hint):
return
# Else, this object is *NOT* a supported type hint. In this case,
# subsequent logic raises an exception specific to the passed parameters.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# BEGIN: Synchronize changes here with is_hint() below.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# If this hint is PEP-compliant, raise an exception only if this hint is
# currently unsupported by @beartype.
if is_hint_pep(hint):
die_if_hint_pep_unsupported(
hint=hint, exception_prefix=exception_prefix)
# Else, this hint is *NOT* PEP-compliant. In this case...
# Raise an exception only if this hint is also *NOT* PEP-noncompliant. By
# definition, all PEP-noncompliant type hints are supported by @beartype.
die_unless_hint_nonpep(hint=hint, exception_prefix=exception_prefix)
# ....................{ TESTERS }....................
@callable_cached
def is_hint(hint: object) -> bool:
'''
``True`` only if the passed object is a **supported type hint** (i.e.,
object supported by the :func:`beartype.beartype` decorator as a valid type
hint annotating callable parameters and return values).
This tester function is memoized for efficiency.
Parameters
----------
hint : object
Object to be validated.
Returns
----------
bool
``True`` only if this object is either:
* A **PEP-compliant type hint** (i.e., :mod:`beartype`-agnostic
annotation compliant with annotation-centric PEPs).
* A **PEP-noncompliant type hint** (i.e., :mod:`beartype`-specific
annotation intentionally *not* compliant with annotation-centric
PEPs).
Raises
----------
TypeError
If this object is **unhashable** (i.e., *not* hashable by the builtin
:func:`hash` function and thus unusable in hash-based containers like
dictionaries and sets). All supported type hints are hashable.
'''
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# BEGIN: Synchronize changes here with die_unless_hint() above.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Return true only if...
return (
# This is a PEP-compliant type hint supported by @beartype *OR*...
is_hint_pep_supported(hint) if is_hint_pep(hint) else
# This is a PEP-noncompliant type hint, which by definition is
# necessarily supported by @beartype.
is_hint_nonpep(hint=hint, is_str_valid=True)
)
# ....................{ TESTERS ~ caching }....................
#FIXME: Unit test us up, please.
def is_hint_uncached(hint: object) -> bool:
'''
``True`` only if the passed type hint is **uncached** (i.e., hint *not*
already internally cached by its parent class or module).
Caveats
----------
This function *cannot* be meaningfully memoized, since the passed type hint
is *not* guaranteed to be cached somewhere. Only functions passed cached
type hints can be meaningfully memoized. Since this high-level function
internally defers to unmemoized low-level functions that are ``O(n)`` for
``n`` the size of the inheritance hierarchy of this hint, this function
should be called sparingly.
Parameters
----------
hint : object
Type hint to be inspected.
Returns
----------
bool
``True`` only if this type hint is uncached.
See Also
----------
:func:`beartype._check.conv.convcoerce.coerce_hint_any`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.utilpep585 import (
is_hint_pep585_builtin)
from beartype._util.hint.pep.proposal.utilpep604 import is_hint_pep604
# Return true only if this hint is either...
return (
# PEP 585-compliant (e.g., "list[str]"), this hint is *NOT* self-caching
# (e.g., "list[str] is not list[str]").
is_hint_pep585_builtin(hint) or
# PEP 604-compliant (e.g., "int | str"), this hint is *NOT* self-caching
# (e.g., "int | str is not int | str").
#
# Note that this hint could also be implicitly cached by coercing this
# non-self-caching PEP 604-compliant union into a self-caching PEP
# 484-compliant union (e.g., from "int | str" to "Union[int, str]").
# Since doing so would consume substantially more time for *NO* tangible
# gain, we strongly prefer the current trivial and efficient approach.
is_hint_pep604(hint)
)
# ....................{ TESTERS ~ ignorable }....................
@callable_cached
def is_hint_ignorable(hint: object) -> bool:
'''
``True`` only if the passed type hint is **ignorable** (i.e., conveys *no*
meaningful semantics despite superficially appearing to do so).
This tester function is memoized for efficiency.
Parameters
----------
hint : object
Type hint to be inspected.
Returns
----------
bool
``True`` only if this type hint is ignorable.
'''
# If this hint is shallowly ignorable, return true.
if repr(hint) in HINTS_REPR_IGNORABLE_SHALLOW:
return True
# Else, this hint is *NOT* shallowly ignorable.
# If this hint is PEP-compliant...
if is_hint_pep(hint):
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpeptest import (
is_hint_pep_ignorable)
# Defer to the function testing whether this hint is an ignorable
# PEP-compliant type hint.
return is_hint_pep_ignorable(hint)
# Else, this hint is PEP-noncompliant and thus *NOT* deeply ignorable.
# Since this hint is also *NOT* shallowly ignorable, this hint is
# unignorable. In this case, return false.
return False
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **type hint factories** (i.e., low-level classes and callables
dynamically creating and returning PEP-compliant type hints, typically as a
runtime fallback when the currently installed versions of the standard
:mod:`typing` module and third-party :mod:`typing_extensions` modules do *not*
officially support those factories).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.typing import (
Generic,
Type,
TypeVar,
)
from beartype._util.cache.utilcachecall import callable_cached
# ....................{ PRIVATE ~ hints }....................
_T = TypeVar('_T')
'''
PEP-compliant type variable matching any arbitrary object.
'''
# ....................{ METACLASSES }....................
class _TypeHintTypeFactoryMeta(type):
'''
**Type hint type factory metaclass** (i.e., the root :class:`type` metaclass
augmented with caching to memoize singleton instances of the
:class:`TypeHintTypeFactory` class declared below).
This metaclass is superior to the usual approach of implementing the
singleton design pattern: overriding the :meth:`__new__` method of a
singleton class to conditionally create a new instance of that class only if
an instance has *not* already been created. Why? Because that approach
unavoidably re-calls the :meth:`__init__` method of a previously initialized
singleton instance on each instantiation of that class. Doing so is
generally considered harmful.
This metaclass instead guarantees that the :meth:`__init__` method of a
singleton instance is only called exactly once on the first instantiation of
that class.
'''
# ..................{ INITIALIZERS }..................
@callable_cached
def __call__(cls, type_factory: type) -> 'TypeHintTypeFactory': # type: ignore[override]
'''
Instantiate the passed singleton class with the passed arbitrary type.
Parameters
----------
cls : Type['TypeHintTypeFactory']
:class:`TypeHintTypeFactory` class to be instantiated.
type_factory : type
Arbitrary type to instantiate that class with.
'''
# Create and return a new memoized singleton instance of the
# "TypeHintTypeFactory" class specific to this arbitrary type.
return super().__call__(type_factory)
# ....................{ CLASSES }....................
class TypeHintTypeFactory(Generic[_T], metaclass=_TypeHintTypeFactoryMeta):
'''
**Type hint type factory** (i.e., high-level object unconditionally
returning an arbitrary type when subscripted by any arbitrary object).
This factory is principally intended to serve as a graceful runtime fallback
when the currently installed versions of the standard :mod:`typing` module
and third-party :mod:`typing_extensions` modules do *not* declare the
desired PEP-compliant type hint factory. See the examples below.
Instances of this class are implicitly memoized as singletons as a
negligible space and time optimization that costs us nothing and gains us a
negligible something.
Examples
----------
For example, the :pep:`647`-compliant :attr:`typing.TypeGuard` type hint
factory is only available from :mod:`typing` under Python >= 3.10 or from
:mod:`typing_extensions` if optionally installed; if neither of those two
conditions apply, this factory may be trivially used as a fake ``TypeGuard``
stand-in returning the builtin :class:`bool` type when subscripted --
exactly as advised by :pep:`647` itself: e.g.,
.. code-block:
from beartype.typing import TYPE_CHECKING
from beartype._util.hint.utilhintfactory import TypeHintTypeFactory
from beartype._util.mod.lib.utiltyping import (
import_typing_attr_or_fallback)
if TYPE_CHECKING:
from typing_extensions import TypeGuard
else:
TypeGuard = import_typing_attr_or_fallback(
'TypeGuard', TypeHintTypeFactory(bool))
# This signature gracefully reduces to the following at runtime under
# Python <= 3.10 if "typing_extensions" is *NOT* installed:
# def is_obj_list(obj: object) -> bool:
def is_obj_list(obj: object) -> TypeGuard[list]:
return isinstance(obj, list)
Attributes
----------
_type_factory : Type[_T]
Arbitrary type to be returned from the :meth:`__getitem__` method.
'''
# ..................{ CLASS VARIABLES }..................
# Slot all instance variables defined on this object to minimize the time
# complexity of both reading and writing variables across frequently called
# @beartype decorations. Slotting has been shown to reduce read and write
# costs by approximately ~10%, which is non-trivial.
__slots__ = (
'_type_factory',
)
# ..................{ INITIALIZERS }..................
def __init__(self, type_factory: Type[_T]) -> None:
'''
Initialize this type hint type factory.
Parameters
----------
type_factory : Type[_T]
Arbitrary type to be returned from the :meth:`__getitem__` method.
'''
assert isinstance(type_factory, type), f'{repr(type_factory)} not type.'
# Classify all passed parameters.
self._type_factory = type_factory
# ..................{ DUNDERS }..................
def __getitem__(self, index: object) -> Type[_T]:
'''
Return the arbitrary type against which this type hint type factory was
originally initialized when subscripted by the passed arbitrary object.
Parameters
----------
index : object
Arbitrary object. Although this is typically a PEP-compliant type
hint, this factory imposes *no* constraints on this object.
Parameters
----------
Type[_T]
Arbitrary type previously passed to the :meth:`__init__` method.
'''
# Return this type, silently ignoring the passed object entirely. Hah!
return self._type_factory
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **EP-compliant type hint tester utilities** (i.e., callables
validating arbitrary objects to be PEP-compliant type hints).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import (
BeartypeDecorHintPepException,
BeartypeDecorHintPepUnsupportedException,
BeartypeDecorHintPep484Exception,
BeartypeDecorHintPep585DeprecationWarning,
)
from beartype.typing import NoReturn
from beartype._data.datatyping import TypeException
from beartype._data.hint.pep.datapeprepr import (
HINTS_PEP484_REPR_PREFIX_DEPRECATED)
from beartype._data.hint.pep.sign.datapepsignset import (
HINT_SIGNS_SUPPORTED,
HINT_SIGNS_TYPE_MIMIC,
)
from beartype._data.mod.datamodtyping import TYPING_MODULE_NAMES
from beartype._util.cache.utilcachecall import callable_cached
from beartype._util.hint.pep.proposal.pep484.utilpep484 import (
is_hint_pep484_ignorable_or_none)
from beartype._util.hint.pep.proposal.utilpep544 import (
is_hint_pep544_ignorable_or_none)
from beartype._util.hint.pep.proposal.utilpep593 import (
is_hint_pep593_ignorable_or_none)
from beartype._util.mod.utilmodget import get_object_module_name_or_none
from beartype._util.utilobject import get_object_type_unless_type
from warnings import warn
# ....................{ CONSTANTS }....................
_IS_HINT_PEP_IGNORABLE_TESTERS = (
is_hint_pep484_ignorable_or_none,
is_hint_pep544_ignorable_or_none,
is_hint_pep593_ignorable_or_none,
)
'''
Tuple of all PEP-specific functions testing whether the passed object is an
ignorable type hint fully compliant with a specific PEP.
Each such function is expected to have a signature resembling:
.. code-block:: python
def is_hint_pep{PEP_NUMBER}_ignorable_or_none(
hint: object, hint_sign: HintSign) -> Optional[bool]:
...
Each such function is expected to return either:
* If the passed object is fully compliant with that PEP:
* If this object is ignorable, ``True``.
* Else, ``False``.
* If this object is *not* fully compliant with that PEP, ``None``.
'''
# ....................{ EXCEPTIONS }....................
def die_if_hint_pep(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPepException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception if the passed object is a **PEP-compliant type
hint** (i.e., :mod:`beartype`-agnostic annotation compliant with
annotation-centric PEPs).
This validator is effectively (but technically *not*) memoized. See the
:func:`beartype._util.hint.utilhinttest.die_unless_hint` validator.
Parameters
----------
hint : object
Object to be validated.
exception_cls : Type[Exception], optional
Type of the exception to be raised by this function. Defaults to
:class:`BeartypeDecorHintPepException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this object is a PEP-compliant type hint.
'''
# If this hint is PEP-compliant...
if is_hint_pep(hint):
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not type.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Raise an exception of this class.
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} is PEP-compliant '
f'(e.g., rather than isinstanceable class).'
)
def die_unless_hint_pep(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPepException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is a **PEP-compliant type
hint** (i.e., :mod:`beartype`-agnostic annotation compliant with
annotation-centric PEPs).
This validator is effectively (but technically *not*) memoized. See the
:func:`beartype._util.hint.utilhinttest.die_unless_hint` validator.
Parameters
----------
hint : object
Object to be validated.
exception_cls : Type[Exception], optional
Type of the exception to be raised by this function. Defaults to
:class:`BeartypeDecorHintPepException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this object is *not* a PEP-compliant type hint.
'''
# If this hint is *NOT* PEP-compliant, raise an exception.
if not is_hint_pep(hint):
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not type.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} not PEP-compliant.')
# ....................{ EXCEPTIONS ~ supported }....................
#FIXME: *DANGER.* This function makes beartype more fragile. Instead, refactor
#all or most calls to this function into calls to the
#warn_if_hint_pep_unsupported() function; then, consider excising this as well
#as exception classes (e.g., "BeartypeDecorHintPepUnsupportedException").
def die_if_hint_pep_unsupported(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_prefix: str = '',
) -> None:
'''
Raise an exception if the passed object is a **PEP-compliant unsupported
type hint** (i.e., :mod:`beartype`-agnostic annotation compliant with
annotation-centric PEPs currently *not* supported by the
:func:`beartype.beartype` decorator).
This validator is effectively (but technically *not*) memoized. See the
:func:`beartype._util.hint.utilhinttest.die_unless_hint` validator.
Caveats
----------
**This validator only shallowly validates this object.** If this object is
a subscripted PEP-compliant type hint (e.g., ``Union[str, List[int]]``),
this validator ignores all subscripted arguments (e.g., ``List[int]``) on
this hint and may thus return false positives for hints that are directly
supported but whose subscripted arguments are not. To deeply validate this
object, iteratively call this validator during a recursive traversal (such
as a breadth-first search) over each subscripted argument of this object.
Parameters
----------
hint : object
Object to be validated.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintPepException
If this object is *not* a PEP-compliant type hint.
BeartypeDecorHintPepUnsupportedException
If this object is a PEP-compliant type hint but is currently
unsupported by the :func:`beartype.beartype` decorator.
BeartypeDecorHintPep484Exception
If this object is the PEP-compliant :attr:`typing.NoReturn` type hint,
which is contextually valid in only a single use case and thus
supported externally by the :mod:`beartype._decor._wrapper.wrappermain`
submodule rather than with general-purpose automation.
'''
# If this object is a supported PEP-compliant type hint, reduce to a noop.
#
# Note that this memoized call is intentionally passed positional rather
# than keyword parameters to maximize efficiency.
if is_hint_pep_supported(hint):
return
# Else, this object is *NOT* a supported PEP-compliant type hint. In this
# case, subsequent logic raises an exception specific to the passed
# parameters.
# If this hint is *NOT* PEP-compliant, raise an exception.
die_unless_hint_pep(hint=hint, exception_prefix=exception_prefix)
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Else, this hint is PEP-compliant.
#
# If this is the PEP 484-compliant "typing.NoReturn" type hint permitted
# *ONLY* as a return annotation, raise an exception specific to this hint.
if hint is NoReturn:
raise BeartypeDecorHintPep484Exception(
f'{exception_prefix}return type hint "{repr(hint)}" invalid (i.e., '
f'"typing.NoReturn" valid only as non-nested return annotation).'
)
# Else, this is any PEP-compliant type hint other than "typing.NoReturn".
# In this case, raise a general-purpose exception.
#
# Note that, by definition, the sign uniquely identifying this hint *SHOULD*
# be in the "HINT_SIGNS_SUPPORTED" set. Regardless of whether it is or not,
# we raise a similar exception in either case. Ergo, there is *NO* practical
# benefit to validating that expectation here.
raise BeartypeDecorHintPepUnsupportedException(
f'{exception_prefix}type hint {repr(hint)} '
f'currently unsupported by @beartype.'
)
# ....................{ WARNINGS }....................
#FIXME: Resurrect support for the passed "warning_prefix" parameter. We've
#currently disabled this parameter as it's typically just a non-human-readable
#placeholder substring *NOT* intended to be exposed to end users (e.g.,
#"$%ROOT_PITH_LABEL/~"). For exceptions, we simply catch raised exceptions and
#replace such substrings with human-readable equivalents. Can we perform a
#similar replacement for warnings?
def warn_if_hint_pep_deprecated(
# Mandatory parameters.
hint: object,
# Optional parameters.
warning_prefix: str = '',
) -> None:
'''
Emit a non-fatal warning if the passed PEP-compliant type hint is
**deprecated** (i.e., obsoleted by an equivalent type hint or set of type
hints standardized under one or more recent PEPs).
This validator is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
PEP-compliant type hint to be inspected.
warning_prefix : str, optional
Human-readable label prefixing the representation of this object in the
warning message. Defaults to the empty string.
Warns
----------
BeartypeDecorHintPep585DeprecationWarning
If this hint is a :pep:`484`-compliant type hint deprecated by
:pep:`585` *and* the active Python interpreter targets Python >= 3.9.
'''
# Substring of the machine-readable representation of this hint preceding
# the first "[" delimiter if this representation contains that delimiter
# *OR* this representation as is otherwise.
#
# Note that the str.partition() method has been profiled to be the
# optimally efficient means of parsing trivial prefixes.
hint_bare_repr, _, _ = repr(hint).partition('[')
#FIXME: Uncomment *AFTER* resolving the "FIXME:" above.
#FIXME: Unit test that this string contains *NO* non-human-readable
#placeholder substrings. Note that the existing
#"beartype_test.a00_unit.decor.code.test_codemain" submodule contains
#relevant logic currently disabled for reasons that hopefully no longer
#apply. *Urgh!*
# assert isinstance(exception_prefix, str), f'{repr(exception_prefix)} not string.'
# If this hint is a PEP 484-compliant type hint originating from an origin
# type (e.g., "typing.List[int]"), this hint has been deprecated by the
# equivalent PEP 585-compliant type hint (e.g., "list[int]"). In this case,
# emit a non-fatal PEP 585-specific deprecation warning.
if hint_bare_repr in HINTS_PEP484_REPR_PREFIX_DEPRECATED:
#FIXME: Resolve issue #73 by additionally passing the "stacklevel"
#keyword parameter. Doing so will probably require:
#* Refactoring this function to accept an *OPTIONAL*
# "warning_stack_level" parameter. Why optional? Because this
# parameter is only reliably decidable under Python interpreters
# defining the implementation-specific sys._getframe() function, which
# is admittedly all of them everyone cares about. Nonetheless, do this
# right. If non-"None", conditionally pass this level below as:
# stacklevel=(
# warning_stack_level
# if warning_stack_level is not None else
# 1 # <-- the official default value for this parameter
# ),
#* Refactoring all callers of this function to pass that parameter.
# Here's where things get dicey, however. Passing this parameter
# reliably (so, *NOT* just hard-coding a magic number somewhere and
# praying devoutly for the best) will require computing the distance
# between the current function and the first external third-party
# non-@beartype scope on the call stack. So, maybe we want to actually
# *NOT* refactor this function to accept an *OPTIONAL*
# "warning_stack_level" parameter but instead locally define
# "warning_stack_level" based on an iterative O(n) search up the
# stack? That's obviously non-ideal -- but still absolutely preferable
# to the current untenable situation of emitting unreadable warnings.
#
#Okay. So, scrap everything above. Let's instead:
#* Define a new warn_safe() wrapper function (somewhere in
# "beartype._util", clearly) that automatically decides the
# appropriate "stacklevel" by iterating up the call stack to compute
# the distance between the current function and the first external
# third-party non-@beartype scope. We perform similar iteration when
# resolving PEP 563-based deferred annotations, so that would probably
# be the first place to clean inspiration. That code is rock solid and
# well-tested. Things get non-trivial fast here, sadly. *sigh*
#
#See also: https://docs.python.org/3/library/warnings.html#warnings.warn
warn(
(
f'PEP 484 type hint {repr(hint)} deprecated by PEP 585 '
f'scheduled for removal in the first Python version '
f'released after October 5th, 2025. To resolve this, import '
f'this hint from "beartype.typing" rather than "typing". '
f'See this discussion for further details and alternatives:\n'
f' https://github.com/beartype/beartype#pep-585-deprecations'
),
BeartypeDecorHintPep585DeprecationWarning,
)
# Else, this hint is *NOT* deprecated. In this case, reduce to a noop.
#FIXME: Unit test us up.
#FIXME: Actually use us in place of die_if_hint_pep_unsupported().
#FIXME: Actually, it's unclear whether we still require or desire this. See
#"_pephint" commentary for further details.
# def warn_if_hint_pep_unsupported(
# # Mandatory parameters.
# hint: object,
#
# # Optional parameters.
# exception_prefix: str = 'Annotated',
# ) -> bool:
# '''
# Return ``True`` and emit a non-fatal warning only if the passed object is a
# **PEP-compliant unsupported type hint** (i.e., :mod:`beartype`-agnostic
# annotation compliant with annotation-centric PEPs currently *not* supported
# by the :func:`beartype.beartype` decorator).
#
# This validator is effectively (but technically *not*) memoized. See the
# :func:`beartype._util.hint.utilhinttest.die_unless_hint` validator.
#
# Parameters
# ----------
# hint : object
# Object to be validated.
# exception_prefix : Optional[str]
# Human-readable label prefixing this object's representation in the
# warning message emitted by this function. Defaults to the empty string.
#
# Returns
# ----------
# bool
# ``True`` only if this PEP-compliant type hint is currently supported by
# that decorator.
#
# Raises
# ----------
# BeartypeDecorHintPepException
# If this object is *not* a PEP-compliant type hint.
#
# Warnings
# ----------
# BeartypeDecorHintPepUnsupportedWarning
# If this object is a PEP-compliant type hint currently unsupported by
# that decorator.
# '''
#
# # True only if this object is a supported PEP-compliant type hint.
# #
# # Note that this memoized call is intentionally passed positional rather
# # than keyword parameters to maximize efficiency.
# is_hint_pep_supported_test = is_hint_pep_supported(hint)
#
# # If this object is an unsupported PEP-compliant type hint...
# if not is_hint_pep_supported_test:
# assert isinstance(exception_prefix, str), f'{repr(exception_prefix)} not string.'
#
# # If this hint is *NOT* PEP-compliant, raise an exception.
# die_unless_hint_pep(hint=hint, exception_prefix=exception_prefix)
#
# # Else, this hint is PEP-compliant. In this case, emit a warning.
# warn(
# (
# f'{exception_prefix}PEP type hint {repr(hint)} '
# f'currently unsupported by @beartype.'
# ),
# BeartypeDecorHintPepUnsupportedWarning
# )
#
# # Return true only if this object is a supported PEP-compliant type hint.
# return is_hint_pep_supported_test
# ....................{ TESTERS }....................
def is_hint_pep(hint: object) -> bool:
'''
``True`` only if the passed object is a **PEP-compliant type hint** (i.e.,
object either directly defined by the :mod:`typing` module *or* whose type
subclasses one or more classes directly defined by the :mod:`typing`
module).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Motivation
----------
Standard Python types allow callers to test for compliance with protocols,
interfaces, and abstract base classes by calling either the
:func:`isinstance` or :func:`issubclass` builtins. This is the
well-established Pythonic standard for deciding conformance to an API.
Insanely, :pep:`484` *and* the :mod:`typing` module implementing :pep:`484`
reject community standards by explicitly preventing callers from calling
either the :func:`isinstance` or :func:`issubclass` builtins on most but
*not* all :pep:`484` objects and types. Moreover, neither :pep:`484` nor
:mod:`typing` implement public APIs for testing whether arbitrary objects
comply with :pep:`484` or :mod:`typing`.
Thus this function, which "fills in the gaps" by implementing this
laughably critical oversight.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a PEP-compliant type hint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import (
get_hint_pep_sign_or_none)
# Return true only if this object is uniquely identified by a sign and thus
# a PEP-compliant type hint.
return get_hint_pep_sign_or_none(hint) is not None
# ....................{ TESTERS ~ ignorable }....................
def is_hint_pep_ignorable(hint: object) -> bool:
'''
``True`` only if the passed object is a **deeply ignorable PEP-compliant
type hint** (i.e., PEP-compliant type hint shown to be ignorable only after
recursively inspecting the contents of this hint).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as this tester is only safely callable
by the memoized parent
:func:`beartype._util.hint.utilhinttest.is_hint_ignorable` tester.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a deeply ignorable PEP-compliant type
hint.
Warnings
----------
BeartypeDecorHintPepIgnorableDeepWarning
If this object is a deeply ignorable PEP-compliant type hint. Why?
Because deeply ignorable PEP-compliant type hints convey *no*
meaningful semantics but superficially appear to do so. Consider
``Union[str, List[int], NewType('MetaType', Annotated[object, 53])]``,
for example; this PEP-compliant type hint effectively reduces to
``typing.Any`` and thus conveys *no* meaningful semantics despite
superficially appearing to do so.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign
# print(f'Testing PEP hint {repr(hint)} deep ignorability...')
# Sign uniquely identifying this hint.
hint_sign = get_hint_pep_sign(hint)
# For each PEP-specific function testing whether this hint is an ignorable
# type hint fully compliant with that PEP...
for is_hint_pep_ignorable_tester in _IS_HINT_PEP_IGNORABLE_TESTERS:
# True only if this hint is a ignorable under this PEP, False only if
# this hint is unignorable under this PEP, and None if this hint is
# *NOT* compliant with this PEP.
is_hint_pep_ignorable_or_none = is_hint_pep_ignorable_tester(
hint, hint_sign)
# If this hint is compliant with this PEP...
# print(f'{is_hint_pep_ignorable_or_none} = {is_hint_pep_ignorable_tester}({hint}, {hint_sign})')
if is_hint_pep_ignorable_or_none is not None:
#FIXME: Uncomment *AFTER* we properly support type variables. Since
#we currently ignore type variables, uncommenting this now would
#raise spurious warnings for otherwise unignorable and absolutely
#unsuspicious generics and protocols parametrized by type
#variables, which would be worse than the existing situation.
# # If this hint is ignorable under this PEP, warn the user this hint
# # is deeply ignorable. (See the docstring for justification.)
# if is_hint_pep_ignorable_or_none:
# warn(
# (
# f'Ignorable PEP type hint {repr(hint)} '
# f'typically not intended to be ignored.'
# ),
# BeartypeDecorHintPepIgnorableDeepWarning,
# )
# Return this boolean.
return is_hint_pep_ignorable_or_none
# Else, this hint is *NOT* compliant with this PEP. In this case,
# silently continue to the next such tester.
# Else, this hint is *NOT* deeply ignorable. In this case, return false.
return False
# ....................{ TESTERS ~ supported }....................
@callable_cached
def is_hint_pep_supported(hint: object) -> bool:
'''
``True`` only if the passed object is a **PEP-compliant supported type
hint** (i.e., :mod:`beartype`-agnostic annotation compliant with
annotation-centric PEPs currently supported by the
:func:`beartype.beartype` decorator).
This tester is memoized for efficiency.
Caveats
----------
**This tester only shallowly inspects this object.** If this object is a
subscripted PEP-compliant type hint (e.g., ``Union[str, List[int]]``), this
tester ignores all subscripted arguments (e.g., ``List[int]``) on this hint
and may thus return false positives for hints that are directly supported
but whose subscripted arguments are not.
To deeply inspect this object, iteratively call this tester during a
recursive traversal over each subscripted argument of this object.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a supported PEP-compliant type hint.
'''
# If this hint is *NOT* PEP-compliant, immediately return false.
if not is_hint_pep(hint):
return False
# Else, this hint is PEP-compliant.
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign
# Sign uniquely identifying this hint.
hint_sign = get_hint_pep_sign(hint)
# Return true only if this sign is supported.
return hint_sign in HINT_SIGNS_SUPPORTED
# ....................{ TESTERS ~ typing }....................
#FIXME: Replace all hardcoded "'typing" strings throughout the codebase with
#access of "TYPING_MODULE_NAMES" instead. We only see one remaining in:
#* beartype._util.hint.pep.proposal.pep484.utilpep484.py
#Thankfully, nobody really cares about generalizing this one edge case to
#"testing_extensions", so it's mostly fine for various definitions of fine.
@callable_cached
def is_hint_pep_typing(hint: object) -> bool:
'''
``True`` only if the passed object is an attribute of a **typing module**
(i.e., module officially declaring attributes usable for creating
PEP-compliant type hints accepted by both static and runtime type
checkers).
This tester is memoized for efficiency.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is an attribute of a typing module.
'''
# print(f'is_hint_pep_typing({repr(hint)}')
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import (
get_hint_pep_sign_or_none)
# Return true only if this hint is either...
return (
# Any PEP-compliant type hint defined by a typing module (except those
# maliciously masquerading as another type entirely) *OR*...
get_object_module_name_or_none(hint) in TYPING_MODULE_NAMES or
# Any PEP-compliant type hint defined by a typing module maliciously
# masquerading as another type entirely.
get_hint_pep_sign_or_none(hint) in HINT_SIGNS_TYPE_MIMIC
)
def is_hint_pep_type_typing(hint: object) -> bool:
'''
``True`` only if either the passed object is defined by a **typing module**
(i.e., module officially declaring attributes usable for creating
PEP-compliant type hints accepted by both static and runtime type checkers)
if this object is a class *or* the class of this object is defined by a
typing module otherwise (i.e., if this object is *not* a class).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if either:
* If this object is a class, this class is defined by a typing module.
* Else, the class of this object is defined by a typing module.
'''
# This hint if this hint is a class *OR* this hint's class otherwise.
hint_type = get_object_type_unless_type(hint)
# print(f'pep_type_typing({repr(hint)}): {get_object_module_name(hint_type)}')
# Return true only if this type is defined by a typing module.
#
# Note that this implementation could probably be reduced to the
# leading portion of the body of the get_hint_pep_sign_or_none()
# function testing this object's representation. While certainly more
# compact and convenient than the current approach, that refactored
# approach would also be considerably more fragile, failure-prone, and
# subject to whimsical "improvements" in the already overly hostile
# "typing" API. Why? Because the get_hint_pep_sign_or_none() function:
# * Parses the machine-readable string returned by the __repr__()
# dunder method of "typing" types. Since that string is *NOT*
# standardized by PEP 484 or any other PEP, "typing" authors remain
# free to violate this pseudo-standard in any manner and at any time
# of their choosing.
# * Suffers common edge cases for "typing" types whose __repr__()
# dunder methods fail to comply with the non-standard implemented by
# their sibling types. This includes the common "TypeVar" type.
# * Calls this tester function to decide whether the passed object is a
# PEP-compliant type hint or not before subjecting that object to
# further introspection, which would clearly complicate implementing
# this tester function in terms of that getter function.
#
# In contrast, the current approach only tests the standard
# "__module__" dunder attribute and is thus significantly more robust
# against whimsical destruction by "typing" authors. Note that there
# might exist an alternate means of deciding this boolean, documented
# here merely for completeness:
# try:
# isinstance(obj, object)
# return False
# except TypeError as type_error:
# return str(type_error).endswith(
# 'cannot be used with isinstance()')
#
# The above effectively implements an Aikido throw by using the fact
# that "typing" types prohibit isinstance() calls against those types.
# While clever (and deliciously obnoxious), the above logic:
# * Requires catching exceptions in the common case and is thus *MUCH*
# less efficient than the preferable approach implemented here.
# * Assumes that *ALL* "typing" types prohibit such calls. Sadly, only
# a proper subset of these types prohibit such calls.
# * Assumes that those "typing" types that do prohibit such calls raise
# exceptions with reliable messages across *ALL* Python versions.
#
# In short, there is no general-purpose clever solution. *sigh*
return hint_type.__module__ in TYPING_MODULE_NAMES
# ....................{ TESTERS ~ args }....................
#FIXME: Overkill. Replace directly with a simple test, please.
#
#Note that the corresponding unit test should be preserved, as that test is
#essential to ensuring sanity across type hints and Python versions.
def is_hint_pep_args(hint: object) -> bool:
'''
``True`` only if the passed object is a **subscripted PEP-compliant type
hint** (i.e., PEP-compliant type hint directly indexed by one or more
objects).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**Callers should not assume that the objects originally subscripting this
hint are still accessible.** Although *most* hints preserve their
subscripted objects over their lifetimes, a small subset of edge-case hints
erase those objects at subscription time. This includes:
* :pep:`585`-compliant empty tuple type hints (i.e., ``tuple[()]``), which
despite being explicitly subscripted erroneously erase that subscription
at subscription time. This does *not* extend to :pep:`484`-compliant
empty tuple type hints (i.e., ``typing.Tuple[()]``), which correctly
preserve that subscripted empty tuple.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a subscripted PEP-compliant type hint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_args
# Return true only if this hint is subscripted by one or more arguments.
return bool(get_hint_pep_args(hint))
# ....................{ TESTERS ~ typevars }....................
#FIXME: Overkill. Replace directly with a simple test, please.
#
#Note that the corresponding unit test should be preserved, as that test is
#essential to ensuring sanity across type hints and Python versions.
def is_hint_pep_typevars(hint: object) -> bool:
'''
``True`` only if the passed object is a PEP-compliant type hint
parametrized by one or more **type variables** (i.e., instances of the
:class:`TypeVar` class).
This tester detects both:
* **Direct parametrizations** (i.e., cases in which this object itself is
directly parametrized by type variables).
* **Superclass parametrizations** (i.e., cases in which this object is
indirectly parametrized by one or more superclasses of its class being
directly parametrized by type variables).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Semantics
----------
**Generics** (i.e., PEP-compliant type hints whose classes subclass one or
more public :mod:`typing` pseudo-superclasses) are often but *not* always
typevared. For example, consider the untypevared generic:
>>> from typing import List
>>> class UntypevaredGeneric(List[int]): pass
>>> UntypevaredGeneric.__mro__
(__main__.UntypevaredGeneric, list, typing.Generic, object)
>>> UntypevaredGeneric.__parameters__
()
Likewise, typevared hints are often but *not* always generic. For example,
consider the typevared non-generic:
>>> from typing import List, TypeVar
>>> TypevaredNongeneric = List[TypeVar('T')]
>>> type(TypevaredNongeneric).__mro__
(typing._GenericAlias, typing._Final, object)
>>> TypevaredNongeneric.__parameters__
(~T,)
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a PEP-compliant type hint parametrized
by one or more type variables.
Examples
----------
>>> import typing
>>> from beartype._util.hint.pep.utilpeptest import (
... is_hint_pep_typevars)
>>> T = typing.TypeVar('T')
>>> class UserList(typing.List[T]): pass
# Unparametrized type hint.
>>> is_hint_pep_typevars(typing.List[int])
False
# Directly parametrized type hint.
>>> is_hint_pep_typevars(typing.List[T])
True
# Superclass-parametrized type hint.
>>> is_hint_pep_typevars(UserList)
True
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_typevars
# Return true only if this hint is parametrized by one or more type
# variables, trivially detected by testing whether the tuple of all type
# variables parametrizing this hint is non-empty.
return bool(get_hint_pep_typevars(hint))
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **PEP-compliant type hint getter utilities** (i.e., callables
querying arbitrary objects for attributes specific to PEP-compliant type
hints).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.meta import URL_ISSUES
from beartype.roar import (
BeartypeDecorHintPepException,
BeartypeDecorHintPepSignException,
)
from beartype.typing import (
Any,
Optional,
)
from beartype._cave._cavefast import HintGenericSubscriptedType
from beartype._data.datatyping import TypeException
from beartype._data.hint.pep.datapeprepr import (
HINT_REPR_PREFIX_ARGS_0_OR_MORE_TO_SIGN,
HINT_REPR_PREFIX_ARGS_1_OR_MORE_TO_SIGN,
HINT_TYPE_NAME_TO_SIGN,
)
from beartype._data.hint.pep.sign.datapepsigncls import HintSign
from beartype._data.hint.pep.sign.datapepsigns import (
HintSignGeneric,
HintSignNewType,
HintSignTypedDict,
)
from beartype._data.hint.pep.sign.datapepsignset import (
HINT_SIGNS_ORIGIN_ISINSTANCEABLE,
)
from beartype._util.cache.utilcachecall import callable_cached
from beartype._util.hint.pep.proposal.pep484.utilpep484newtype import (
is_hint_pep484_newtype_pre_python310)
from beartype._util.hint.pep.proposal.utilpep585 import (
get_hint_pep585_generic_typevars,
is_hint_pep585_generic,
)
from beartype._util.py.utilpyversion import (
IS_PYTHON_AT_LEAST_3_11,
IS_PYTHON_AT_MOST_3_9,
IS_PYTHON_AT_LEAST_3_9,
)
from beartype._data.datatyping import TupleTypes
# ....................{ GETTERS ~ args }....................
# If the active Python interpreter targets Python >= 3.9, implement this
# getter to directly access the "__args__" dunder attribute.
if IS_PYTHON_AT_LEAST_3_9:
def get_hint_pep_args(hint: object) -> tuple:
# Return the value of the "__args__" dunder attribute if this hint
# defines this attribute *OR* "None" otherwise.
hint_args = getattr(hint, '__args__', None)
# If this hint does *NOT* define this attribute, return the empty tuple.
if hint_args is None:
return ()
# Else, this hint defines this attribute.
#
# If this hint appears to be unsubscripted, then this hint *WAS*
# actually subscripted by the empty tuple (e.g., "tuple[()]",
# "typing.Tuple[()]"). Why? Because:
# * Python 3.11 made the unfortunate decision of ambiguously conflating
# unsubscripted type hints (e.g., "tuple", "typing.Tuple") with type
# hints subscripted by the empty tuple, preventing downstream
# consumers from reliably distinguishing these two orthogonal cases.
# * Python 3.9 made a similar decision but constrained to only PEP
# 585-compliant empty tuple type hints (i.e., "tuple[()]"). PEP
# 484-compliant empty tuple type hints (i.e., "typing.Tuple[()]")
# continued to correctly declare an "__args__" dunder attribute of
# "((),)" until Python 3.11.
#
# Disambiguate these two cases on behalf of callers by returning a tuple
# containing only the empty tuple rather than returning the empty tuple.
elif not hint_args:
return _HINT_ARGS_EMPTY_TUPLE
# Else, this hint is either subscripted *OR* is unsubscripted but not
# PEP 585-compliant.
# In this case, return this tuple as is.
return hint_args
# Else, the active Python interpreter targets Python < 3.9. In this case,
# implement this getter to directly access the "__args__" dunder attribute.
else:
def get_hint_pep_args(hint: object) -> tuple:
# Under python < 3.9, unparametrized generics have the attribute
# "_special" set to True despite the actual "__args__" typically being a
# "TypeVar" instance. Because we want to differentiate between
# unparametrized and parametrized generics, check whether the hint is
# "_special" and if so, we return the empty tuple instead of that
# "TypeVar" instance.
if getattr(hint, '_special', False):
return ()
# Return the value of the "__args__" dunder attribute if this hint
# defines this attribute *OR* the empty tuple otherwise.
return getattr(hint, '__args__', ())
# Document this function regardless of implementation details above.
get_hint_pep_args.__doc__ = '''
Tuple of all **typing arguments** (i.e., subscripted objects of the passed
PEP-compliant type hint listed by the caller at hint declaration time)
if any *or* the empty tuple otherwise.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This getter should always be called in lieu of attempting to directly
access the low-level** ``__args__`` **dunder attribute.** Various
singleton objects defined by the :mod:`typing` module (e.g.,
:attr:`typing.Any`, :attr:`typing.NoReturn`) fail to define this attribute,
guaranteeing :class:`AttributeError` exceptions from all general-purpose
logic attempting to directly access this attribute. Thus this function,
which "fills in the gaps" by implementing this oversight.
**This getter never lies, unlike the comparable**
:func:`get_hint_pep_typevars` **getter.** Whereas
:func:`get_hint_pep_typevars` synthetically propagates type variables from
child to parent type hints (rather than preserving the literal type
variables subscripting this type hint), this getter preserves the literal
arguments subscripting this type hint if any. Notable cases where the two
differ include:
* Generic classes subclassing pseudo-superclasses subscripted by one or
more type variables (e.g., ``class MuhGeneric(Generic[S, T])``).
* Unions subscripted by one or more child type hints subscripted by one or
more type variables (e.g., ``Union[str, Iterable[Tuple[S, T]]]``).
Parameters
----------
hint : object
PEP-compliant type hint to be inspected.
Returns
----------
tuple
Either:
* If this hint defines an ``__args__`` dunder attribute, the value of
that attribute.
* Else, the empty tuple.
Examples
----------
>>> import typing
>>> from beartype._util.hint.pep.utilpepget import (
... get_hint_pep_args)
>>> get_hint_pep_args(typing.Any)
()
>>> get_hint_pep_args(typing.List[int, str, typing.Dict[str, str]])
(int, str, typing.Dict[str, str])
'''
# ....................{ GETTERS ~ typevars }....................
# If the active Python interpreter targets Python >= 3.9, implement this
# function to either directly access the "__parameters__" dunder attribute for
# type hints that are not PEP 585-compliant generics *OR* to synthetically
# reconstruct that attribute for PEP 585-compliant generics. *sigh*
if IS_PYTHON_AT_LEAST_3_9:
def get_hint_pep_typevars(hint: object) -> TupleTypes:
# Value of the "__parameters__" dunder attribute on this object if this
# object defines this attribute *OR* "None" otherwise.
hint_pep_typevars = getattr(hint, '__parameters__', None)
# If this object defines *NO* such attribute...
if hint_pep_typevars is None:
# Return either...
return (
# If this hint is a PEP 585-compliant generic, the tuple of all
# typevars declared on pseudo-superclasses of this generic.
get_hint_pep585_generic_typevars(hint)
if is_hint_pep585_generic(hint) else
# Else, the empty tuple.
()
)
# Else, this object defines this attribute.
# Return this attribute.
return hint_pep_typevars
# Else, the active Python interpreter targets Python < 3.9. In this case,
# implement this function to directly access the "__parameters__" dunder
# attribute.
else:
def get_hint_pep_typevars(hint: object) -> TupleTypes:
# Value of the "__parameters__" dunder attribute on this object if this
# object defines this attribute *OR* the empty tuple otherwise. Note:
# * The "typing._GenericAlias.__parameters__" dunder attribute tested
# here is defined by the typing._collect_type_vars() function at
# subscription time. Yes, this is insane. Yes, this is PEP 484.
# * This trivial test implicitly handles superclass parametrizations.
# Thankfully, the "typing" module percolates the "__parameters__"
# dunder attribute from "typing" pseudo-superclasses to user-defined
# subclasses during PEP 560-style type erasure. Finally: they did
# something slightly right.
return getattr(hint, '__parameters__', ())
# Document this function regardless of implementation details above.
get_hint_pep_typevars.__doc__ = '''
Tuple of all **unique type variables** (i.e., subscripted :class:`TypeVar`
instances of the passed PEP-compliant type hint listed by the caller at
hint declaration time ignoring duplicates) if any *or* the empty tuple
otherwise.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This function should always be called in lieu of attempting to directly
access the low-level** ``__parameters__`` **dunder attribute.** Various
singleton objects defined by the :mod:`typing` module (e.g.,
:attr:`typing.Any`, :attr:`typing.NoReturn`) fail to define this attribute,
guaranteeing :class:`AttributeError` exceptions from all general-purpose
logic attempting to directly access this attribute. Thus this function,
which "fills in the gaps" by implementing this oversight.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
Tuple[TypeVar, ...]
Either:
* If this object defines a ``__parameters__`` dunder attribute, the
value of that attribute.
* Else, the empty tuple.
Examples
----------
>>> import typing
>>> from beartype._util.hint.pep.utilpepget import (
... get_hint_pep_typevars)
>>> S = typing.TypeVar('S')
>>> T = typing.TypeVar('T')
>>> get_hint_pep_typevars(typing.Any)
()
>>> get_hint_pep_typevars(typing.List[T, int, S, str, T)
(T, S)
'''
# ....................{ GETTERS ~ sign }....................
def get_hint_pep_sign(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPepSignException,
exception_prefix: str = '',
) -> HintSign:
'''
**Sign** (i.e., :class:`HintSign` instance) uniquely identifying the passed
PEP-compliant type hint if PEP-compliant *or* raise an exception otherwise
(i.e., if this hint is *not* PEP-compliant).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Type hint to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPepSignException`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Returns
----------
dict
Sign uniquely identifying this hint.
Raises
----------
:exc:`exception_cls`
If this hint is either:
* PEP-compliant but *not* uniquely identifiable by a sign.
* PEP-noncompliant.
* *Not* a hint (i.e., neither PEP-compliant nor -noncompliant).
See Also
----------
:func:`get_hint_pep_sign_or_none`
Further details.
'''
# Sign uniquely identifying this hint if recognized *OR* "None" otherwise.
hint_sign = get_hint_pep_sign_or_none(hint)
# If this hint is unrecognized...
if hint_sign is None:
# Avoid circular import dependencies.
from beartype._util.hint.nonpep.utilnonpeptest import die_if_hint_nonpep
# If this hint is PEP-noncompliant, raise an exception.
die_if_hint_nonpep(
hint=hint,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this hint is *NOT* PEP-noncompliant. Since this hint was
# unrecognized, this hint *MUST* necessarily be a PEP-compliant type
# hint currently unsupported by the @beartype decorator.
# Raise an exception indicating this.
#
# Note that we intentionally avoid calling the
# die_if_hint_pep_unsupported() function here, which calls the
# is_hint_pep_supported() function, which calls this function.
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} '
f'currently unsupported by beartype. '
f'You suddenly feel encouraged to submit '
f'a feature request for this hint to our '
f'friendly issue tracker at:\n\t{URL_ISSUES}'
)
# Else, this hint is recognized.
# Return the sign uniquely identifying this hint.
return hint_sign
#FIXME: Revise us up the docstring, most of which is now obsolete.
@callable_cached
def get_hint_pep_sign_or_none(hint: Any) -> Optional[HintSign]:
'''
**Sign** (i.e., :class:`HintSign` instance) uniquely identifying the passed
PEP-compliant type hint if PEP-compliant *or* ``None`` otherwise (i.e., if
this hint is *not* PEP-compliant).
This getter function associates the passed hint with a public attribute of
the :mod:`typing` module effectively acting as a superclass of this hint
and thus uniquely identifying the "type" of this hint in the broadest sense
of the term "type". These attributes are typically *not* actual types, as
most actual :mod:`typing` types are private, fragile, and prone to extreme
violation (or even removal) between major Python versions. Nonetheless,
these attributes are sufficiently unique to enable callers to distinguish
between numerous broad categories of :mod:`typing` behaviour and logic.
Specifically, if this hint is:
* A :pep:`585`-compliant **builtin** (e.g., C-based type
hint instantiated by subscripting either a concrete builtin container
class like :class:`list` or :class:`tuple` *or* an abstract base class
(ABC) declared by the :mod:`collections.abc` submodule like
:class:`collections.abc.Iterable` or :class:`collections.abc.Sequence`),
this function returns ::class:`beartype.cave.HintGenericSubscriptedType`.
* A **generic** (i.e., subclass of the :class:`typing.Generic` abstract
base class (ABC)), this function returns :class:`HintSignGeneric`. Note
this includes :pep:`544`-compliant **protocols** (i.e., subclasses of the
:class:`typing.Protocol` ABC), which implicitly subclass the
:class:`typing.Generic` ABC as well.
* A **forward reference** (i.e., string or instance of the concrete
:class:`typing.ForwardRef` class), this function returns
:class:`HintSignTypeVar`.
* A **type variable** (i.e., instance of the concrete
:class:`typing.TypeVar` class), this function returns
:class:`HintSignTypeVar`.
* Any other class, this function returns that class as is.
* Anything else, this function returns the unsubscripted :mod:`typing`
attribute dynamically retrieved by inspecting this hint's **object
representation** (i.e., the non-human-readable string returned by the
:func:`repr` builtin).
This getter is memoized for efficiency.
Motivation
----------
Both :pep:`484` and the :mod:`typing` module implementing :pep:`484` are
functionally deficient with respect to their public APIs. Neither provide
external callers any means of deciding the categories of arbitrary
PEP-compliant type hints. For example, there exists no general-purpose
means of identifying a parametrized subtype (e.g., ``typing.List[int]``) as
a parametrization of its unparameterized base type (e.g., ``type.List``).
Thus this function, which "fills in the gaps" by implementing this
oversight.
Parameters
----------
hint : object
Type hint to be inspected.
Returns
----------
dict
Sign uniquely identifying this hint.
Raises
----------
BeartypeDecorHintPepException
If this hint is *not* PEP-compliant.
Examples
----------
>>> import typing
>>> from beartype._util.hint.pep.utilpepget import (
... get_hint_pep_sign_or_none)
>>> get_hint_pep_sign_or_none(typing.Any)
typing.Any
>>> get_hint_pep_sign_or_none(typing.Union[str, typing.Sequence[int]])
typing.Union
>>> T = typing.TypeVar('T')
>>> get_hint_pep_sign_or_none(T)
HintSignTypeVar
>>> class Genericity(typing.Generic[T]): pass
>>> get_hint_pep_sign_or_none(Genericity)
HintSignGeneric
>>> class Duplicity(typing.Iterable[T], typing.Container[T]): pass
>>> get_hint_pep_sign_or_none(Duplicity)
HintSignGeneric
'''
# For efficiency, this tester identifies the sign of this type hint with
# multiple phases performed in ascending order of average time complexity.
#
# Note that we intentionally avoid validating this type hint to be
# PEP-compliant (e.g., by calling the die_unless_hint_pep() validator).
# Why? Because this getter is the lowest-level hint validation function
# underlying all higher-level hint validation functions! Calling the latter
# here would thus induce infinite recursion, which would be very bad.
#
# ..................{ PHASE ~ classname }..................
# This phase attempts to map from the fully-qualified classname of this
# hint to a sign identifying *ALL* hints that are instances of that class.
#
# Since the "object.__class__.__qualname__" attribute is both guaranteed to
# exist and be efficiently accessible for all hints, this phase is the
# fastest and thus performed first. Although this phase identifies only a
# small subset of hints, those hints are extremely common.
#
# More importantly, some of these classes are implemented as maliciously
# masquerading as other classes entirely -- including __repr__() methods
# synthesizing erroneous machine-readable representations. To avoid false
# positives, this phase *MUST* thus be performed before repr()-based tests
# regardless of efficiency concerns: e.g.,
# # Under Python >= 3.10:
# >>> import typing
# >>> bad_guy_type_hint = typing.NewType('List', bool)
# >>> bad_guy_type_hint.__module__ = 'typing'
# >>> repr(bad_guy_type_hint)
# typing.List # <---- this is genuine bollocks
#
# Likewise, some of these classes define __repr__() methods prefixed by the
# machine-readable representations of their children. Again, to avoid false
# positives, this phase *MUST* thus be performed before repr()-based tests
# regardless of efficiency concerns: e.g.,
# # Under Python >= 3.10:
# >>> repr(tuple[str, ...] | bool)
# tuple[str, ...] | bool # <---- this is fine but *NOT* a tuple!
# Class of this hint.
hint_type = hint.__class__
#FIXME: Is this actually the case? Do non-physical classes dynamically
#defined at runtime actually define these dunder attributes as well?
# Fully-qualified name of this class. Note that *ALL* classes are
# guaranteed to define the dunder attributes accessed here.
hint_type_name = f'{hint_type.__module__}.{hint_type.__qualname__}'
# Sign identifying this hint if this hint is identifiable by its classname
# *OR* "None" otherwise.
hint_sign = HINT_TYPE_NAME_TO_SIGN.get(hint_type_name)
# If this hint is identifiable by its classname, return this sign.
if hint_sign is not None:
return hint_sign
# Else, this hint is *NOT* identifiable by its classname.
# ..................{ PHASE ~ repr }..................
# This phase attempts to map from the unsubscripted machine-readable
# representation of this hint to a sign identifying *ALL* hints of that
# representation.
#
# Since doing so requires both calling the repr() builtin on this hint
# *AND* munging the string returned by that builtin, this phase is
# significantly slower than the prior phase and thus *NOT* performed first.
# Although slow, this phase identifies the largest subset of hints.
# Parse the machine-readable representation of this hint into:
# * "hint_repr_prefix", the substring of this representation preceding the
# first "[" delimiter if this representation contains that delimiter *OR*
# this representation as is otherwise.
# * "hint_repr_subscripted", the "[" delimiter if this representation
# contains that delimiter *OR* the empty string otherwise.
#
# Note that the str.partition() method has been profiled to be the
# optimally efficient means of parsing trivial prefixes like these.
hint_repr_prefix, hint_repr_subscripted, _ = repr(hint).partition('[')
# Sign identifying this possibly unsubscripted hint if this hint is
# identifiable by its possibly unsubscripted representation *OR* "None".
hint_sign = HINT_REPR_PREFIX_ARGS_0_OR_MORE_TO_SIGN.get(hint_repr_prefix)
# If this hint is identifiable by its possibly unsubscripted
# representation, return this sign.
if hint_sign is not None:
return hint_sign
# Else, this hint is *NOT* identifiable by its possibly unsubscripted
# representation.
#
# If this representation (and thus this hint) is subscripted...
elif hint_repr_subscripted:
# Sign identifying this necessarily subscripted hint if this hint is
# identifiable by its necessarily subscripted representation *OR*
# "None" otherwise.
hint_sign = HINT_REPR_PREFIX_ARGS_1_OR_MORE_TO_SIGN.get(
hint_repr_prefix)
# If this hint is identifiable by its necessarily subscripted
# representation, return this sign.
if hint_sign is not None:
return hint_sign
# Else, this hint is *NOT* identifiable by its necessarily subscripted
# representation.
# Else, this representation (and thus this hint) is unsubscripted.
# ..................{ PHASE ~ manual }..................
# This phase attempts to manually identify the signs of all hints *NOT*
# efficiently identifiably by the prior phases.
#
# For minor efficiency gains, the following tests are intentionally ordered
# in descending likelihood of a match.
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import (
is_hint_pep484585_generic)
from beartype._util.hint.pep.proposal.utilpep589 import is_hint_pep589
# If this hint is a PEP 484- or 585-compliant generic (i.e., user-defined
# class superficially subclassing at least one PEP 484- or 585-compliant
# type hint), return that sign. However, note that:
# * Generics *CANNOT* be detected by the general-purpose logic performed
# above, as the "typing.Generic" ABC does *NOT* define a __repr__()
# dunder method returning a string prefixed by the "typing." substring.
# Ergo, we necessarily detect generics with an explicit test instead.
# * *ALL* PEP 484-compliant generics and PEP 544-compliant protocols are
# guaranteed by the "typing" module to subclass this ABC regardless of
# whether those generics originally did so explicitly. How? By type
# erasure, the gift that keeps on giving:
# >>> import typing as t
# >>> class MuhList(t.List): pass
# >>> MuhList.__orig_bases__
# (typing.List)
# >>> MuhList.__mro__
# (__main__.MuhList, list, typing.Generic, object)
# * *NO* PEP 585-compliant generics subclass this ABC unless those generics
# are also either PEP 484- or 544-compliant. Indeed, PEP 585-compliant
# generics subclass *NO* common superclass.
# * Generics are *NOT* necessarily classes, despite originally being
# declared as classes. Although *MOST* generics are classes, some are
# shockingly *NOT*: e.g.,
# >>> from typing import Generic, TypeVar
# >>> S = TypeVar('S')
# >>> T = TypeVar('T')
# >>> class MuhGeneric(Generic[S, T]): pass
# >>> non_class_generic = MuhGeneric[S, T]
# >>> isinstance(non_class_generic, type)
# False
#
# Ergo, the "typing.Generic" ABC uniquely identifies many but *NOT* all
# generics. While non-ideal, the failure of PEP 585-compliant generics to
# subclass a common superclass leaves us with little alternative.
if is_hint_pep484585_generic(hint):
return HintSignGeneric
# Else, this hint is *NOT* a PEP 484- or 585-compliant generic.
#
# If this hint is a PEP 589-compliant typed dictionary, return that sign.
elif is_hint_pep589(hint):
return HintSignTypedDict
# If the active Python interpreter targets Python < 3.10 (and thus defines
# PEP 484-compliant "NewType" type hints as closures returned by that
# function that are sufficiently dissimilar from all other type hints to
# require unique detection) *AND* this hint is such a hint, return the
# corresponding sign.
#
# Note that these hints *CANNOT* be detected by the general-purpose logic
# performed above, as the __repr__() dunder methods of the closures created
# and returned by the NewType() closure factory function return a standard
# representation rather than a string prefixed by "typing.": e.g.,
# >>> import typing as t
# >>> repr(t.NewType('FakeStr', str))
# '<function NewType.<locals>.new_type at 0x7fca39388050>'
elif IS_PYTHON_AT_MOST_3_9 and is_hint_pep484_newtype_pre_python310(hint):
return HintSignNewType
# ..................{ ERROR }..................
# Else, this hint is unrecognized. In this case, return "None".
return None
# ....................{ GETTERS ~ origin }....................
def get_hint_pep_origin_or_none(hint: Any) -> Optional[Any]:
'''
**Unsafe origin object** (i.e., arbitrary object possibly related to the
passed PEP-compliant type hint but *not* necessarily a non-:mod:`typing`
class such that *all* objects satisfying this hint are instances of this
class) originating this hint if this hint originates from an object *or*
``None`` otherwise (i.e., if this hint originates from *no* such object).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**The high-level** :func:`get_hint_pep_origin_type_isinstanceable`
function should always be called in lieu of this low-level function.**
Whereas the former is guaranteed to return either a class or ``None``, this
function enjoys no such guarantees and instead returns what the caller can
only safely assume to be an arbitrary object.
If this function *must* be called, **this function should always be called
in lieu of attempting to directly access the low-level** ``__origin__``
**dunder attribute.** That attribute is defined non-orthogonally by various
singleton objects in the :mod:`typing` module, including:
* Objects failing to define this attribute (e.g., :attr:`typing.Any`,
:attr:`typing.NoReturn`).
* Objects defining this attribute to be their unsubscripted :mod:`typing`
object (e.g., :attr:`typing.Optional`, :attr:`typing.Union`).
* Objects defining this attribute to be their origin type.
Since the :mod:`typing` module neither guarantees the existence of this
attribute nor imposes a uniform semantic on this attribute when defined,
that attribute is *not* safely directly accessible. Thus this function,
which "fills in the gaps" by implementing this oversight.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
Optional[Any]
Either:
* If this hint originates from an arbitrary object, that object.
* Else, ``None``.
Examples
----------
>>> import typing
>>> from beartype._util.hint.pep.utilpepget import (
... get_hint_pep_origin_or_none)
# This is sane.
>>> get_hint_pep_origin_or_none(typing.List)
list
>>> get_hint_pep_origin_or_none(typing.List[int])
list
>>> get_hint_pep_origin_or_none(typing.Union)
None
>>> get_hint_pep_origin_or_none(typing.Union[int])
None
# This is insane.
>>> get_hint_pep_origin_or_none(typing.Union[int, str])
Union
# This is crazy.
>>> typing.Union.__origin__
AttributeError: '_SpecialForm' object has no attribute '__origin__'
# This is balls crazy.
>>> typing.Union[int].__origin__
AttributeError: type object 'int' has no attribute '__origin__'
# This is balls cray-cray -- the ultimate evolution of crazy.
>>> typing.Union[int, str].__origin__
typing.Union
'''
# Return this hint's origin object if any *OR* "None" otherwise.
return getattr(hint, '__origin__', None)
# ....................{ GETTERS ~ origin : type }....................
def get_hint_pep_origin_type_isinstanceable(hint: object) -> type:
'''
**Isinstanceable origin type** (i.e., class passable as the second argument
to the :func:`isinstance` builtin such that *all* objects satisfying the
passed PEP-compliant type hint are instances of this class) originating
this hint if this hint originates from such a type *or* raise an exception
otherwise (i.e., if this hint does *not* originate from such a type).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
type
Standard origin type originating this hint.
Raises
----------
BeartypeDecorHintPepException
If this hint does *not* originate from a standard origin type.
See Also
----------
:func:`get_hint_pep_origin_type_isinstanceable_or_none`
Related getter.
'''
# Origin type originating this object if any *OR* "None" otherwise.
hint_origin_type = get_hint_pep_origin_type_isinstanceable_or_none(hint)
# If this type does *NOT* exist, raise an exception.
if hint_origin_type is None:
raise BeartypeDecorHintPepException(
f'Type hint {repr(hint)} not isinstanceable (i.e., does not '
f'originate from isinstanceable class).'
)
# Else, this type exists.
# Return this type.
return hint_origin_type
def get_hint_pep_origin_type_isinstanceable_or_none(
hint: Any) -> Optional[type]:
'''
**Standard origin type** (i.e., isinstanceable class declared by Python's
standard library such that *all* objects satisfying the passed
PEP-compliant type hint are instances of this class) originating this hint
if this hint originates from such a type *or* ``None`` otherwise (i.e., if
this hint does *not* originate from such a type).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This high-level getter should always be called in lieu of the low-level**
:func:`get_hint_pep_origin_or_none` **getter or attempting to
directly access the low-level** ``__origin__`` **dunder attribute.**
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
Optional[type]
Either:
* If this hint originates from a standard origin type, that type.
* Else, ``None``.
See Also
----------
:func:`get_hint_pep_origin_type_isinstanceable`
Related getter.
:func:`get_hint_pep_origin_or_none`
Further details.
'''
# Sign uniquely identifying this hint.
hint_sign = get_hint_pep_sign(hint)
# Return either...
return (
# If this sign originates from an origin type, that type;
get_hint_pep_origin_or_none(hint)
if hint_sign in HINT_SIGNS_ORIGIN_ISINSTANCEABLE else
# Else, "None".
None
)
# ....................{ PRIVATE ~ args }....................
_HINT_ARGS_EMPTY_TUPLE = ((),)
'''
Tuple containing only the empty tuple, to be returned from the
:func:`get_hint_pep_args` getter when passed either:
* A :pep:`585`-compliant type hint subscripted by the empty tuple (e.g.,
``tuple[()]``).
* A :pep:`484`-compliant type hint subscripted by the empty tuple (e.g.,
``typing.Tuple[()]``) under Python >= 3.11, which applied the :pep:`585`
approach throughout the :mod:`typing` module.
'''
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`586`-compliant type hint utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep586Exception
from beartype.typing import Any
from beartype._cave._cavefast import EnumMemberType, NoneType
from beartype._data.datatyping import TypeException
from beartype._data.hint.pep.sign.datapepsigns import HintSignLiteral
from beartype._util.text.utiltextjoin import join_delimited_disjunction_types
# ....................{ CONSTANTS }....................
_LITERAL_ARG_TYPES = (bool, bytes, int, str, EnumMemberType, NoneType)
'''
Tuple of all types of objects permissible as arguments subscripting the
:pep:`586`-compliant :attr:`typing.Literal` singleton.
These types are explicitly listed by :pep:`586` as follows:
Literal may be parameterized with literal ints, byte and unicode strings,
bools, Enum values and None.
'''
# ....................{ VALIDATORS }....................
def die_unless_hint_pep586(
# Mandatory parameters.
hint: Any,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep586Exception,
exception_prefix: str = '',
) -> None:
'''
Raise an exception of the passed type unless the passed object is a
:pep:`586`-compliant type hint (i.e., subscription of either the
:attr:`typing.Literal` or :attr:`typing_extensions.Literal` type hint
factories).
Ideally, the :attr:`typing.Literal` singleton would internally validate the
literal objects subscripting that singleton at subscription time (i.e., in
the body of the ``__class_getitem__()`` dunder method). Whereas *all* other
:mod:`typing` attributes do just that, :attr:`typing.Literal` permissively
accepts all possible arguments like a post-modern philosopher hopped up on
too much tenure. For inexplicable reasons, :pep:`586` explicitly requires
third-party type checkers (that's us) to validate these hints rather than
standardizing that validation in the :mod:`typing` module. Weep, Guido!
Caveats
----------
**This function is slow** and should thus be called only once per
visitation of a :pep:`586`-compliant type hint. Specifically, this function
is O(n) for n the number of arguments subscripting this hint.
Parameters
----------
hint : object
Object to be inspected.
exception_cls : TypeException
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep586Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this object either:
* Is *not* a subscription of either the :attr:`typing.Literal` or
:attr:`typing_extensions.Literal` type hint factories.
* Subscripts either factory with zero arguments via the empty tuple,
which these factories sadly fails to guard against.
* Subscripts either factory with one or more arguments that are *not*
**valid literals**, defined as the set of all:
* Booleans.
* Byte strings.
* Integers.
* Unicode strings.
* :class:`enum.Enum` members.
* The ``None`` singleton.
'''
# Tuple of zero or more literal objects subscripting this hint.
hint_literals = get_hint_pep586_literals(
hint=hint,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# If the caller maliciously subscripted this hint by the empty tuple and
# thus *NO* arguments, raise an exception. Ideally, the "typing.Literal"
# singleton would guard against this itself. It does not; thus, we do.
if not hint_literals:
raise exception_cls(
f'{exception_prefix}PEP 586 type hint {repr(hint)} '
f'subscripted by empty tuple.'
)
# If any argument subscripting this hint is *NOT* a valid literal...
#
# Sadly, despite PEP 586 imposing strict restrictions on the types of
# objects permissible as arguments subscripting the "typing.Literal"
# singleton, PEP 586 explicitly offloads the odious chore of enforcing
# those restrictions onto third-party type checkers by intentionally
# implementing that singleton to permissively accept *ALL* possible
# objects when subscripted:
# Although the set of parameters Literal[...] may contain at type
# check time is very small, the actual implementation of
# typing.Literal will not perform any checks at runtime.
if any(
not isinstance(hint_literal, _LITERAL_ARG_TYPES)
for hint_literal in hint_literals
# Then raise a human-readable exception describing this invalidity.
):
# For each argument subscripting this hint...
for hint_literal_index, hint_literal in enumerate(hint_literals):
# If this argument is invalid as a literal argument...
if not isinstance(hint_literal, _LITERAL_ARG_TYPES):
# Human-readable concatenation of the types of all valid
# literal arguments, delimited by commas and/or "or".
hint_literal_types = join_delimited_disjunction_types(
_LITERAL_ARG_TYPES)
# Raise an exception.
raise exception_cls(
f'{exception_prefix}PEP 586 type hint {repr(hint)} '
f'argument {hint_literal_index} '
f'{repr(hint_literal)} not {hint_literal_types}.'
)
# ....................{ GETTERS }....................
def get_hint_pep586_literals(
# Mandatory parameters.
hint: Any,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep586Exception,
exception_prefix: str = '',
) -> tuple:
'''
Tuple of zero or more literal objects subscripting the passed
:pep:`586`-compliant type hint (i.e., subscription of either the
:attr:`typing.Literal` or :attr:`typing_extensions.Literal` type hint
factories).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This low-level getter performs no validation of the contents of this
tuple.** Consider calling the high-level :func:`die_unless_hint_pep586`
validator to do so before leveraging this tuple elsewhere.
Parameters
----------
hint : object
:pep:`586`-compliant type hint to be inspected.
exception_cls : TypeException
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep586Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Returns
----------
tuple
Tuple of zero or more literal objects subscripting this hint.
Raises
----------
:exc:`exception_cls`
If this object is *not* a :pep:`586`-compliant type hint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign
# If this hint is *NOT* PEP 586-compliant, raise an exception.
if get_hint_pep_sign(hint) is not HintSignLiteral:
raise exception_cls(
f'{exception_prefix}PEP 586 type hint {repr(hint)} neither '
f'"typing.Literal" nor "typing_extensions.Literal".'
)
# Else, this hint is PEP 586-compliant.
# Return the standard tuple of all literals subscripting this hint.
return hint.__args__
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`593`-compliant type hint utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep593Exception
from beartype.typing import (
Any,
Optional,
Tuple,
)
from beartype._data.hint.pep.sign.datapepsigncls import HintSign
from beartype._data.hint.pep.sign.datapepsigns import HintSignAnnotated
from beartype._data.datatyping import TypeException
# ....................{ RAISERS }....................
#FIXME: Pass "exception_prefix" to all calls of this validator.
def die_unless_hint_pep593(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep593Exception,
exception_prefix: str = '',
) -> None:
'''
Raise an exception of the passed type unless the passed object is a
:pep:`593`-compliant **type metahint** (i.e., subscription of either the
:attr:`typing.Annotated` or :attr:`typing_extensions.Annotated` type hint
factories).
Parameters
----------
hint : object
Type hint to be inspected.
exception_cls : TypeException
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep593Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintPep593Exception
If this object is *not* a :pep:`593`-compliant type metahint.
'''
# If this hint is *NOT* PEP 593-compliant, raise an exception.
if not is_hint_pep593(hint):
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} not PEP 593-compliant '
f'(e.g., "typing.Annotated[...]", '
f'"typing_extensions.Annotated[...]").'
)
# ....................{ TESTERS }....................
#FIXME: Unit test us up.
def is_hint_pep593(hint: Any) -> bool:
'''
``True`` only if the passed object is a :pep:`593`-compliant **type
metahint** (i.e., subscription of either the :attr:`typing.Annotated` or
:attr:`typing_extensions.Annotated` type hint factories).
Parameters
----------
hint : Any
Type hint to be inspected.
Returns
----------
bool
``True`` only if this object is a :pep:`593`-compliant type metahint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign_or_none
# Return true only if this hint is PEP 593-compliant.
return get_hint_pep_sign_or_none(hint) is HintSignAnnotated
def is_hint_pep593_ignorable_or_none(
hint: object, hint_sign: HintSign) -> Optional[bool]:
'''
``True`` only if the passed object is a :pep:`593`-compliant ignorable type
hint, ``False`` only if this object is a :pep:`593`-compliant unignorable
type hint, and ``None`` if this object is *not* :pep:`593`-compliant.
Specifically, this tester function returns ``True`` only if this object is
the :data:`Annotated` singleton whose first subscripted argument is an
ignorable type hints (e.g., ``typing.Annotated[typing.Any, bool]``).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as this tester is only safely callable
by the memoized parent
:func:`beartype._util.hint.utilhinttest.is_hint_ignorable` tester.
Parameters
----------
hint : object
Type hint to be inspected.
hint_sign : HintSign
**Sign** (i.e., arbitrary object uniquely identifying this hint).
Returns
----------
Optional[bool]
Either:
* If this object is :pep:`593`-compliant:
* If this object is a ignorable, ``True``.
* Else, ``False``.
* If this object is *not* :pep:`593`-compliant, ``None``.
'''
# Avoid circular import dependencies.
from beartype._util.hint.utilhinttest import is_hint_ignorable
# print(f'!!!!!!!Received 593 hint: {repr(hint)} [{repr(hint_sign)}]')
# Return either...
return (
# If this hint is annotated, true only if the PEP-compliant child type
# hint annotated by this hint hint is ignorable (e.g., the "Any" in
# "Annotated[Any, 50, False]").
is_hint_ignorable(get_hint_pep593_metahint(hint))
if hint_sign is HintSignAnnotated else
# Else, "None".
None
)
# ....................{ TESTERS ~ beartype }....................
def is_hint_pep593_beartype(hint: Any) -> bool:
'''
``True`` only if the first argument subscripting the passed
:pep:`593`-compliant :attr:`typing.Annotated` type hint is
:mod:`beartype`-specific (e.g., instance of the :class:`BeartypeValidator`
class produced by subscripting (indexing) the :class:`Is` class).
Parameters
----------
hint : Any
:pep:`593`-compliant type hint to be inspected.
Returns
----------
bool
``True`` only if the first argument subscripting this hint is
:mod:`beartype`-specific.
Raises
----------
BeartypeDecorHintPep593Exception
If this object is *not* a :pep:`593`-compliant type metahint.
'''
# Defer heavyweight imports.
from beartype.vale._core._valecore import BeartypeValidator
# If this object is *NOT* a PEP 593-compliant type metahint, raise an
# exception.
die_unless_hint_pep593(hint)
# Else, this object is a PEP 593-compliant type metahint.
# Attempt to...
try:
# Tuple of one or more arbitrary objects annotating this metahint.
hint_metadata = get_hint_pep593_metadata(hint)
# Return true only if the first such object is a beartype validator.
# Note this object is guaranteed to exist by PEP 593 design.
# print(f'Checking first PEP 593 type hint {repr(hint)} arg {repr(hint_metadata[0])}...')
return isinstance(hint_metadata[0], BeartypeValidator)
# If the metaclass of the first argument subscripting this hint overrides
# the __isinstancecheck__() dunder method to raise an exception, silently
# ignore this exception by returning false instead.
except:
return False
# ....................{ GETTERS }....................
#FIXME: Unit test us up, please.
def get_hint_pep593_metadata(hint: Any) -> Tuple[Any, ...]:
'''
Tuple of one or more arbitrary objects annotating the passed
:pep:`593`-compliant **type metahint** (i.e., subscription of the
:attr:`typing.Annotated` singleton).
Specifically, this getter returns *all* arguments subscripting this
metahint excluding the first, which conveys its own semantics and is thus
returned by the :func:`get_hint_pep593_metahint` getter.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
`PEP 593`-compliant type metahint to be inspected.
Returns
----------
type
Tuple of one or more arbitrary objects annotating this metahint.
Raises
----------
BeartypeDecorHintPep593Exception
If this object is *not* a :pep:`593`-compliant type metahint.
See Also
----------
:func:`get_hint_pep593_metahint`
Related getter.
'''
# If this object is *NOT* a metahint, raise an exception.
die_unless_hint_pep593(hint)
# Else, this object is a metahint.
# Return the tuple of one or more objects annotating this metahint. By
# design, this tuple is guaranteed to be non-empty: e.g.,
# >>> from typing import Annotated
# >>> Annotated[int]
# TypeError: Annotated[...] should be used with at least two
# arguments (a type and an annotation).
return hint.__metadata__
#FIXME: Unit test us up, please.
def get_hint_pep593_metahint(hint: Any) -> Any:
'''
PEP-compliant type hint annotated by the passed :pep:`593`-compliant **type
metahint** (i.e., subscription of the :attr:`typing.Annotated` singleton).
Specifically, this getter returns the first argument subscripting this
metahint. By design, this argument is guaranteed to be a PEP-compliant type
hint. Note that although that hint *may* be a standard class, this is *not*
necessarily the case.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
:pep:`593`-compliant type metahint to be inspected.
Returns
----------
Any
PEP-compliant type hint annotated by this metahint.
Raises
----------
BeartypeDecorHintPep593Exception
If this object is *not* a :pep:`593`-compliant type metahint.
See Also
----------
:func:`get_hint_pep593_metadata`
Related getter.
'''
# If this object is *NOT* a metahint, raise an exception.
die_unless_hint_pep593(hint)
# Else, this object is a metahint.
# Return the PEP-compliant type hint annotated by this metahint.
#
# Note that most edge-case PEP-compliant type hints store their data in
# hint-specific dunder attributes (e.g., "__supertype__" for new type
# aliases, "__forward_arg__" for forward references). Some, however,
# coopt and misuse standard dunder attributes commonly used for
# entirely different purposes. PEP 593-compliant type metahints are the
# latter sort, preferring to store their class in the standard
# "__origin__" attribute commonly used to store the origin type of type
# hints originating from a standard class rather than in a
# metahint-specific dunder attribute.
return hint.__origin__
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`544`-compliant type hint utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from abc import abstractmethod
from beartype.roar import BeartypeDecorHintPep544Exception
from beartype.typing import (
Any,
BinaryIO,
Dict,
IO,
Optional,
TextIO,
)
from beartype._data.hint.pep.sign.datapepsigncls import HintSign
from beartype._data.mod.datamodtyping import TYPING_MODULE_NAMES_STANDARD
from beartype._util.cls.utilclstest import is_type_builtin
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_8
# ....................{ PRIVATE ~ mappings }....................
_HINTS_PEP484_IO_GENERIC = frozenset((IO, BinaryIO, TextIO,))
'''
Frozen set of all :mod:`typing` **IO generic base class** (i.e., either
:class:`typing.IO` itself *or* a subclass of :class:`typing.IO` defined by the
:mod:`typing` module).
'''
# Conditionally initialized by the _init() function below.
_HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL: Dict[type, Any] = {}
'''
Dictionary mapping from each :mod:`typing` **IO generic base class** (i.e.,
either :class:`typing.IO` itself *or* a subclass of :class:`typing.IO` defined
by the :mod:`typing` module) to the associated :mod:`beartype` **IO protocol**
(i.e., either :class:`_Pep544IO` itself *or* a subclass of :class:`_Pep544IO`
defined by this submodule).
'''
# ....................{ PRIVATE ~ classes }....................
# Conditionally initialized by the _init() function below.
_Pep544IO: Any = None # type: ignore[assignment]
'''
:pep:`544`-compliant protocol base class for :class:`_Pep544TextIO` and
:class:`_Pep544BinaryIO`.
This is an abstract, generic version of the return of open().
NOTE: This does not distinguish between the different possible classes (text
vs. binary, read vs. write vs. read/write, append-only, unbuffered). The TextIO
and BinaryIO subclasses below capture the distinctions between text vs. binary,
which is pervasive in the interface; however we currently do not offer a way to
track the other distinctions in the type system.
Design
----------
This base class intentionally duplicates the contents of the existing
:class:`typing.IO` generic base class by substituting the useless
:class:`typing.Generic` superclass of the latter with the useful
:class:`typing.Protocol` superclass of the former. Why? Because *no* stdlib
classes excluding those defined by the :mod:`typing` module itself subclass
:class:`typing.IO`. However, :class:`typing.IO` leverages neither the
:class:`abc.ABCMeta` metaclass *nor* the :class:`typing.Protocol` superclass
needed to support structural subtyping. Therefore, *no* stdlib objects
(including those returned by the :func:`open` builtin) satisfy either
:class:`typing.IO` itself or any subclasses of :class:`typing.IO` (e.g.,
:class:`typing.BinaryIO`, :class:`typing.TextIO`). Therefore,
:class:`typing.IO` and all subclasses thereof are functionally useless for all
practical intents. The conventional excuse `given by Python maintainers to
justify this abhorrent nonsensicality is as follows <typeshed_>`__:
There are a lot of "file-like" classes, and the typing IO classes are meant
as "protocols" for general files, but they cannot actually be protocols
because the file protocol isn't very well defined—there are lots of methods
that exist on some but not all filelike classes.
Like most :mod:`typing`-oriented confabulation, that, of course, is bollocks.
Refactoring the family of :mod:`typing` IO classes from inveterate generics
into pragmatic protocols is both technically trivial and semantically useful,
because that is exactly what :mod:`beartype` does. It works. It necessitates
modifying three lines of existing code. It preserves backward compatibility. In
short, it should have been done a decade ago. If the file protocol "isn't very
well defined," the solution is to define that protocol with a rigorous type
hierarchy satisfying all possible edge cases. The solution is *not* to pretend
that no solutions exist, that the existing non-solution suffices, and instead
do nothing. Welcome to :mod:`typing`, where no one cares that nothing works as
advertised (or at all)... *and no one ever will.*
.. _typeshed:
https://github.com/python/typeshed/issues/3225#issuecomment-529277448
'''
# Conditionally initialized by the _init() function below.
_Pep544BinaryIO: Any = None # type: ignore[assignment]
'''
Typed version of the return of open() in binary mode.
'''
# Conditionally initialized by the _init() function below.
_Pep544TextIO: Any = None # type: ignore[assignment]
'''
Typed version of the return of open() in text mode.
'''
# ....................{ TESTERS }....................
# If the active Python interpreter targets at least Python >= 3.8 and thus
# supports PEP 544, define these functions appropriately.
if IS_PYTHON_AT_LEAST_3_8:
# Defer version-dependent imports.
from typing import Protocol
def is_hint_pep544_ignorable_or_none(
hint: object, hint_sign: HintSign) -> Optional[bool]:
# Machine-readable representation of this hint.
hint_repr = repr(hint)
#FIXME: *OPTIMIZE.* Would a compiled regex test be faster? Possibly,
#but possibly not. Regexes are notoriously slow -- even when compiled.
# For the fully-qualified name of each standard typing module (i.e.,
# modules whose "Protocol" superclass strictly conforms with the
# runtime behaviour of the standard "typing.Protocol" superclass).
#
# Note this intentionally omits the "typing_extensions.Protocol"
# superclass, which does *NOT* conform with the runtime behaviour of
# the standard "typing.Protocol" superclass.
for typing_module_name in TYPING_MODULE_NAMES_STANDARD:
# If this hint is the "Protocol" superclass directly parametrized
# by one or more type variables (e.g., "typing.Protocol[S, T]"),
# ignore this superclass by returning true. Since this superclass
# can *ONLY* be parametrized by type variables, a trivial string
# test suffices.
#
# For unknown and uninteresting reasons, *ALL* possible objects
# satisfy the "Protocol" superclass. Ergo, this superclass and
# *ALL* parametrizations of this superclass are synonymous with the
# "object" root superclass.
if hint_repr.startswith(f'{typing_module_name}.Protocol['):
return True
# Else, this hint is *NOT* the "Protocol" superclass directly
# parametrized by one or more type variables. In this case, continue
# testing this hint for other kinds of ignorable by returning None.
return None
def is_hint_pep484_generic_io(hint: object) -> bool:
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import (
get_hint_pep_origin_or_none)
# Return true only if this hint is either...
return (
# An unsubscripted PEP 484-compliant IO generic base class
# (e.g., "typing.IO") *OR*....
(isinstance(hint, type) and hint in _HINTS_PEP484_IO_GENERIC) or
# A subscripted PEP 484-compliant IO generic base class
# (e.g., "typing.IO[str]") *OR*....
get_hint_pep_origin_or_none(hint) in _HINTS_PEP484_IO_GENERIC
)
def is_hint_pep544_protocol(hint: object) -> bool:
# Return true only if this hint is...
return (
# A type *AND*...
isinstance(hint, type) and
# A PEP 544-compliant protocol *AND*...
issubclass(hint, Protocol) and # type: ignore[arg-type]
# *NOT* a builtin type. For unknown reasons, some but *NOT* all
# builtin types erroneously present themselves to be PEP
# 544-compliant protocols under Python >= 3.8: e.g.,
# >>> from typing import Protocol
# >>> issubclass(str, Protocol)
# False # <--- this makes sense
# >>> issubclass(int, Protocol)
# True # <--- this makes no sense whatsoever
#
# Since builtin types are obviously *NOT* PEP 544-compliant
# protocols, explicitly exclude all such types. Why, Guido? Why?
not is_type_builtin(
cls=hint,
# Do *NOT* ignore fake builtins for the purposes of this
# test. Why? Because even fake builtins (e.g., "type(None)")
# erroneously masquerade as PEP 544-compliant protocols! :o
is_ignore_fake=False,
)
)
# Else, the active Python interpreter targets at most Python < 3.8 and thus
# fails to support PEP 544. In this case, fallback to declaring this function
# to unconditionally return False.
else:
def is_hint_pep544_ignorable_or_none(
hint: object, hint_sign: HintSign) -> Optional[bool]:
return None
def is_hint_pep484_generic_io(hint: object) -> bool:
return False
def is_hint_pep544_protocol(hint: object) -> bool:
return False
# ....................{ TESTERS ~ doc }....................
is_hint_pep544_ignorable_or_none.__doc__ = '''
``True`` only if the passed object is a :pep:`544`-compliant **ignorable
type hint,** ``False`` only if this object is a :pep:`544`-compliant
unignorable type hint, and ``None`` if this object is *not*
:pep:`544`-compliant.
Specifically, this tester function returns ``True`` only if this object is
a deeply ignorable :pep:`544`-compliant type hint, including:
* A parametrization of the :class:`typing.Protocol` abstract base class
(ABC) by one or more type variables. As the name implies, this ABC is
generic and thus fails to impose any meaningful constraints. Since a type
variable in and of itself also fails to impose any meaningful
constraints, these parametrizations are safely ignorable in all possible
contexts: e.g.,
.. code-block:: python
from typing import Protocol, TypeVar
T = TypeVar('T')
def noop(param_hint_ignorable: Protocol[T]) -> T: pass
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as this tester is only safely callable
by the memoized parent
:func:`beartype._util.hint.utilhinttest.is_hint_ignorable` tester.
Parameters
----------
hint : object
Type hint to be inspected.
hint_sign : HintSign
**Sign** (i.e., arbitrary object uniquely identifying this hint).
Returns
----------
Optional[bool]
Either:
* If this object is :pep:`544`-compliant:
* If this object is a ignorable, ``True``.
* Else, ``False``.
* If this object is *not* :pep:`544`-compliant, ``None``.
'''
is_hint_pep484_generic_io.__doc__ = '''
``True`` only if the passed object is a functionally useless
:pep:`484`-compliant :mod:`typing` **IO generic superclass** (i.e., either
:class:`typing.IO` itself *or* a subclass of :class:`typing.IO` defined by
the :mod:`typing` module effectively unusable at runtime due to botched
implementation details) that is losslessly replaceable with a useful
:pep:`544`-compliant :mod:`beartype` **IO protocol** (i.e., either
:class:`_Pep544IO` itself *or* a subclass of that class defined by this
submodule intentionally designed to be usable at runtime).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a :pep:`484`-compliant IO generic base
class.
See Also
----------
:class:`_Pep544IO`
Further commentary.
'''
is_hint_pep544_protocol.__doc__ = '''
``True`` only if the passed object is a :pep:`544`-compliant **protocol**
(i.e., subclass of the :class:`typing.Protocol` superclass).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a :pep:`544`-compliant protocol.
'''
# ....................{ REDUCERS }....................
def reduce_hint_pep484_generic_io_to_pep544_protocol(
hint: Any, exception_prefix: str) -> Any:
'''
:pep:`544`-compliant :mod:`beartype` **IO protocol** (i.e., either
:class:`_Pep544IO` itself *or* a subclass of that class defined by this
submodule intentionally designed to be usable at runtime) corresponding to
the passed :pep:`484`-compliant :mod:`typing` **IO generic base class**
(i.e., either :class:`typing.IO` itself *or* a subclass of
:class:`typing.IO` defined by the :mod:`typing` module effectively unusable
at runtime due to botched implementation details).
This reducer is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : type
:pep:`484`-compliant :mod:`typing` IO generic base class to be replaced
by the corresponding :pep:`544`-compliant :mod:`beartype` IO protocol.
exception_prefix : str
Human-readable label prefixing the representation of this object in the
exception message.
Returns
----------
Protocol
:pep:`544`-compliant :mod:`beartype` IO protocol corresponding to this
:pep:`484`-compliant :mod:`typing` IO generic base class.
Raises
----------
BeartypeDecorHintPep544Exception
If this object is *not* a :pep:`484`-compliant IO generic base class.
'''
# If this object is *NOT* a PEP 484-compliant "typing" IO generic,
# raise an exception.
if not is_hint_pep484_generic_io(hint):
raise BeartypeDecorHintPep544Exception(
f'{exception_prefix}type hint {repr(hint)} not '
f'PEP 484 IO generic base class '
f'(i.e., "typing.IO", "typing.BinaryIO", or "typing.TextIO").'
)
# Else, this object is *NOT* a PEP 484-compliant "typing" IO generic.
#
# If this dictionary has yet to be initialized, this submodule has yet to
# be initialized. In this case, do so.
#
# Note that this initialization is intentionally deferred until required.
# Why? Because this initialization performs somewhat space- and
# time-intensive work -- including importation of the "beartype.vale"
# subpackage, which we strictly prohibit importing from global scope.
elif not _HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL:
_init()
# In any case, this dictionary is now initialized.
# PEP 544-compliant IO protocol implementing this PEP 484-compliant IO
# generic if any *OR* "None" otherwise.
pep544_protocol = _HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL.get(hint)
# If *NO* such protocol implements this generic...
if pep544_protocol is None:
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import (
get_hint_pep_origin_or_none,
get_hint_pep_typevars,
)
# Tuple of zero or more type variables parametrizing this hint.
hint_typevars = get_hint_pep_typevars(hint)
#FIXME: Unit test us up, please.
# If this hint is unparametrized, raise an exception.
if not hint_typevars:
raise BeartypeDecorHintPep544Exception(
f'{exception_prefix}PEP 484 IO generic base class '
f'{repr(hint)} invalid (i.e., not subscripted (indexed) by '
f'either "str", "bytes", "typing.Any", or "typing.AnyStr").'
)
# Else, this hint is parametrized and thus defines the "__origin__"
# dunder attribute whose value is the type originating this hint.
#FIXME: Attempt to actually handle this type variable, please.
# Reduce this parametrized hint (e.g., "typing.IO[typing.AnyStr]") to
# the equivalent unparametrized hint (e.g., "typing.IO"), effectively
# ignoring the type variable parametrizing this hint.
hint_unparametrized: type = get_hint_pep_origin_or_none(hint) # type: ignore[assignment]
# PEP 544-compliant IO protocol implementing this unparametrized PEP
# 484-compliant IO generic. For efficiency, we additionally cache this
# mapping under the original parametrized hint to minimize the cost of
# similar reductions under subsequent annotations.
pep544_protocol = \
_HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL[hint] = \
_HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL[hint_unparametrized]
# Return this protocol.
return pep544_protocol
# ....................{ INITIALIZERS }....................
def _init() -> None:
'''
Initialize this submodule.
'''
# ..................{ VERSIONS }..................
# If the active Python interpreter only targets Python < 3.8 and thus fails
# to support PEP 544, silently reduce to a noop.
if not IS_PYTHON_AT_LEAST_3_8:
return
# Else, the active Python interpreter targets Python >= 3.8 and thus
# supports PEP 593.
# ..................{ IMPORTS }..................
# Defer Python version-specific imports.
from beartype._util.mod.lib.utiltyping import import_typing_attr_or_none
from beartype.typing import (
AnyStr,
List,
Protocol,
)
# ..................{ GLOBALS }..................
# Global attributes to be redefined below.
global \
_Pep544BinaryIO, \
_Pep544IO, \
_Pep544TextIO
# ..................{ PROTOCOLS ~ protocol }..................
# Note that these classes are intentionally *NOT* declared at global scope;
# instead, these classes are declared *ONLY* if the active Python
# interpreter targets Python >= 3.8.
# PEP-compliant type hint matching file handles opened in either text or
# binary mode.
# @runtime_checkable
class _Pep544IO(Protocol[AnyStr]):
# The body of this class is copied wholesale from the existing
# non-functional "typing.IO" class.
__slots__: tuple = ()
@property
@abstractmethod
def mode(self) -> str:
pass
@property
@abstractmethod
def name(self) -> str:
pass
@abstractmethod
def close(self) -> None:
pass
@property
@abstractmethod
def closed(self) -> bool:
pass
@abstractmethod
def fileno(self) -> int:
pass
@abstractmethod
def flush(self) -> None:
pass
@abstractmethod
def isatty(self) -> bool:
pass
@abstractmethod
def read(self, n: int = -1) -> AnyStr:
pass
@abstractmethod
def readable(self) -> bool:
pass
@abstractmethod
def readline(self, limit: int = -1) -> AnyStr:
pass
@abstractmethod
def readlines(self, hint: int = -1) -> List[AnyStr]:
pass
@abstractmethod
def seek(self, offset: int, whence: int = 0) -> int:
pass
@abstractmethod
def seekable(self) -> bool:
pass
@abstractmethod
def tell(self) -> int:
pass
@abstractmethod
def truncate(self, size: Optional[int] = None) -> int:
pass
@abstractmethod
def writable(self) -> bool:
pass
@abstractmethod
def write(self, s: AnyStr) -> int:
pass
@abstractmethod
def writelines(self, lines: List[AnyStr]) -> None:
pass
@abstractmethod
def __enter__(self) -> '_Pep544IO[AnyStr]':
pass
@abstractmethod
def __exit__(self, cls, value, traceback) -> None:
pass
# PEP-compliant type hint matching file handles opened in text rather than
# binary mode.
#
# Note that PEP 544 explicitly requires *ALL* protocols (including
# protocols subclassing protocols) to explicitly subclass the "Protocol"
# superclass, in violation of both sanity and usability. (Thanks, guys.)
# @runtime_checkable
class _Pep544TextIO(_Pep544IO[str], Protocol):
# The body of this class is copied wholesale from the existing
# non-functional "typing.TextIO" class.
__slots__: tuple = ()
@property
@abstractmethod
def buffer(self) -> _Pep544BinaryIO: # pyright: ignore[reportGeneralTypeIssues]
pass
@property
@abstractmethod
def encoding(self) -> str:
pass
@property
@abstractmethod
def errors(self) -> Optional[str]:
pass
@property
@abstractmethod
def line_buffering(self) -> bool:
pass
@property
@abstractmethod
def newlines(self) -> Any:
pass
@abstractmethod
def __enter__(self) -> '_Pep544TextIO':
pass
# ..................{ PROTOCOLS ~ validator }..................
# PEP-compliant type hint matching file handles opened in binary rather
# than text mode.
#
# If PEP 593 (e.g., "typing.Annotated") and thus beartype validators are
# unusable, this hint falls back to ambiguously matching the abstract
# "typing.IO" protocol ABC. This will yield false positives (i.e., fail to
# raise exceptions) for @beartype-decorated callables annotated as
# accepting binary file handles erroneously passed text file handles, which
# is non-ideal but certainly preferable to raising exceptions at decoration
# time on each such callable.
#
# If PEP 593 (e.g., "typing.Annotated") and thus beartype validators are
# usable, this hint matches the abstract "typing.IO" protocol ABC but *NOT*
# the concrete "typing.TextIO" subprotocol subclassing that ABC. Whereas
# the concrete "typing.TextIO" subprotocol unambiguously matches *ONLY*
# file handles opened in text mode, the concrete "typing.BinaryIO"
# subprotocol ambiguously matches file handles opened in both text *AND*
# binary mode. As the following hypothetical "_Pep544BinaryIO" subclass
# demonstrates, the "typing.IO" and "typing.BinaryIO" APIs are identical
# except for method annotations:
# class _Pep544BinaryIO(_Pep544IO[bytes], Protocol):
# # The body of this class is copied wholesale from the existing
# # non-functional "typing.BinaryIO" class.
#
# __slots__: tuple = ()
#
# @abstractmethod
# def write(self, s: Union[bytes, bytearray]) -> int:
# pass
#
# @abstractmethod
# def __enter__(self) -> '_Pep544BinaryIO':
# pass
#
# Sadly, the method annotations that differ between these APIs are
# insufficient to disambiguate file handles at runtime. Why? Because most
# file handles are C-based and thus lack *ANY* annotations whatsoever. With
# respect to C-based file handles, these APIs are therefore identical.
# Ergo, the "typing.BinaryIO" subprotocol is mostly useless at runtime.
#
# Note, however, that file handles are necessarily *ALWAYS* opened in
# either text or binary mode. This strict dichotomy implies that any file
# handle (i.e., object matching the "typing.IO" protocol) *NOT* opened in
# text mode (i.e., not matching the "typing.TextIO" protocol) must
# necessarily be opened in binary mode instead.
_Pep544BinaryIO = _Pep544IO
#FIXME: Safely replace this with "from typing import Annotated" after
#dropping Python 3.8 support.
# "typing.Annotated" type hint factory safely imported from whichever of
# the "typing" or "typing_extensions" modules declares this attribute if
# one or more do *OR* "None" otherwise (i.e., if none do).
typing_annotated = import_typing_attr_or_none('Annotated')
# If this factory is importable.
if typing_annotated is not None:
# Defer heavyweight imports.
from beartype.vale import IsInstance
# Expand this hint to unambiguously match binary file handles by
# subscripting this factory with a beartype validator doing so.
_Pep544BinaryIO = typing_annotated[
_Pep544IO, ~IsInstance[_Pep544TextIO]]
# Else, this factory is unimportable. In this case, accept this hint's
# default ambiguously matching both binary and text files.
# ..................{ MAPPINGS }..................
# Dictionary mapping from each "typing" IO generic base class to the
# associated IO protocol defined above.
#
# Note this global is intentionally modified in-place rather than
# reassigned to a new dictionary. Why? Because the higher-level
# reduce_hint_pep484_generic_io_to_pep544_protocol() function calling this
# lower-level initializer has already imported this global.
_HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL.update({
# Unsubscripted mappings.
IO: _Pep544IO,
BinaryIO: _Pep544BinaryIO,
TextIO: _Pep544TextIO,
# Subscripted mappings, leveraging the useful observation that these
# classes all self-cache by design: e.g.,
# >>> import typing
# >>> typing.IO[str] is typing.IO[str]
# True
#
# Note that we intentionally map:
# * "IO[Any]" to the unsubscripted "_Pep544IO" rather than the
# subscripted "_Pep544IO[Any]". Although the two are semantically
# equivalent, the latter is marginally more space- and time-efficient
# to generate code for and thus preferable.
# * "IO[bytes]" to the unsubscripted "_Pep544Binary" rather than the
# subscripted "_Pep544IO[bytes]". Why? Because the former applies
# meaningful runtime constraints, whereas the latter does *NOT*.
# * "IO[str]" to the unsubscripted "_Pep544Text" rather than the
# subscripted "_Pep544IO[str]" -- for the same reason.
#
# Note that we intentionally avoid mapping parametrizations of "IO" by
# type variables. Since there exist a countably infinite number of
# such parametrizations, the parent
# reduce_hint_pep484_generic_io_to_pep544_protocol() function calling
# this function handles such parametrizations mostly intelligently.
IO[Any]: _Pep544IO,
IO[bytes]: _Pep544BinaryIO,
IO[str]: _Pep544TextIO,
})
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`589`-compliant type hint utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._util.cls.utilclstest import is_type_subclass
from beartype._util.py.utilpyversion import IS_PYTHON_3_8
# ....................{ TESTERS }....................
# The implementation of the "typing.TypedDict" attribute substantially varies
# across Python interpreter *AND* "typing" implementation. Specifically:
# * The "typing.TypedDict" attribute under Python >= 3.9 is *NOT* actually a
# superclass but instead a factory function masquerading as a superclass by
# setting the subversive "__mro_entries__" dunder attribute to a tuple
# containing a private "typing._TypedDict" superclass. This superclass
# necessarily defines the three requisite dunder attributes.
# * The "typing_extensions.TypedDict" attribute under Python < 3.8 is actually
# a superclass also necessarily defining the three requisite dunder
# attributes.
# * The "typing.TypedDict" attribute under *ONLY* Python 3.8 is also actually
# a superclass that *ONLY* defines the requisite "__annotations__" dunder
# attribute. The two remaining dunder attributes are only conditionally
# defined and thus *CANNOT* be unconditionally assumed to exist.
# In all three cases, passing the passed hint and that superclass to the
# issubclass() builtin fails, as the metaclass of that superclass prohibits
# issubclass() checks. I am throwing up in my mouth as I write this.
#
# Unfortunately, all of the above complications are further complicated by the
# "dict" type under Python >= 3.10. For unknown reasons, Python >= 3.10 adds
# spurious "__annotations__" dunder attributes to "dict" subclasses -- even if
# those subclasses annotate *NO* class or instance variables. While a likely
# bug, we have little choice but to at least temporarily support this insanity.
def is_hint_pep589(hint: object) -> bool:
'''
``True`` only if the passed object is a :pep:`589`-compliant **typed
dictionary** (i.e., :class:`typing.TypedDict` subclass).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator). Although the implementation
inefficiently performs three calls to the :func:`hasattr` builtin (which
inefficiently calls the :func:`getattr` builtin and catches the
:exc:`AttributeError` exception to detect false cases), callers are
expected to instead (in order):
#. Call the memoized
:func:`beartype._util.hint.pep.utilpepget.get_hint_pep_sign_or_none`
getter, which internally calls this unmemoized tester.
#. Compare the object returned by that getter against the
:attr:`from beartype._util.data.hint.pep.sign.datapepsigns.HintSignTypedDict`
sign.
Parameters
----------
hint : object
Object to be tested.
Returns
----------
bool
``True`` only if this object is a typed dictionary.
'''
# If this hint is *NOT* a "dict" subclass, this hint *CANNOT* be a typed
# dictionary. By definition, typed dictionaries are "dict" subclasses.
#
# Note that PEP 589 actually lies about the type of typed dictionaries:
# Methods are not allowed, since the runtime type of a TypedDict object
# will always be just dict (it is never a subclass of dict).
#
# This is *ABSOLUTELY* untrue. PEP 589 authors plainly forgot to implement
# this constraint. Contrary to the above:
# * All typed dictionaries are subclasses of "dict".
# * The type of typed dictionaries is the private "typing._TypedDictMeta"
# metaclass across all Python versions (as of this comment).
#
# This is where we generously and repeatedly facepalm ourselves.
if not is_type_subclass(hint, dict):
return False
# Else, this hint is a "dict" subclass and thus *MIGHT* be a typed
# dictionary.
# Return true *ONLY* if this "dict" subclass defines all three dunder
# attributes guaranteed to be defined by all typed dictionaries. Although
# slow, this is still faster than the MRO-based approach delineated above.
#
# Note that *ONLY* the Python 3.8-specific implementation of
# "typing.TypedDict" fails to unconditionally define the
# "__required_keys__" and "__optional_keys__" dunder attributes. Ergo, if
# the active Python interpreter targets exactly Python 3.8, we relax this
# test to *ONLY* test for the "__annotations__" dunder attribute.
# Specifically, we return true only if...
#
# Technically, this test can also be performed by inefficiently violating
# privacy encapsulation. Specifically, this test could perform an O(k) walk
# up the class inheritance tree of the passed class (for k the number of
# superclasses of that class), iteratively comparing each such superclass
# for against the "typing.TypeDict" superclass. That is, this tester could
# crazily reimplement the issubclass() builtin in pure-Python. Since the
# implementation of typed dictionaries varies substantially across Python
# versions, doing so would require version-specific tests in addition to
# unsafely violating privacy encapsulation and inefficiently violating
# constant-time guarantees.
#
# Technically, the current implementation of this test is susceptible to
# false positives in unlikely edge cases. Specifically, this test queries
# for dunder attributes and thus erroneously returns true for user-defined
# "dict" subclasses *NOT* subclassing the "typing.TypedDict" superclass but
# nonetheless declaring the same dunder attributes declared by that
# superclass. Since the likelihood of any user-defined "dict" subclass
# accidentally defining these attributes is vanishingly small *AND* since
# "typing.TypedDict" usage is largely discouraged in the typing community,
# this error is unlikely to meaningfully arise in real-world use cases.
# Ergo, it is preferable to implement this test portably, safely, and
# efficiently rather than accommodate this error.
#
# In short, the current approach of is strongly preferable.
return (
# This "dict" subclass defines these "TypedDict" attributes *AND*...
hasattr(hint, '__annotations__') and
hasattr(hint, '__total__') and
# Either...
(
# The active Python interpreter targets exactly Python 3.8 and
# thus fails to unconditionally define the remaining attributes
# *OR*...
IS_PYTHON_3_8 or
# The active Python interpreter targets any other Python version
# and thus unconditionally defines the remaining attributes.
(
hasattr(hint, '__required_keys__') and
hasattr(hint, '__optional_keys__')
)
)
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`557`-compliant type hint utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep557Exception
from beartype._data.datatyping import TypeException
from beartype._data.hint.pep.sign.datapepsigns import HintSignDataclassInitVar
# ....................{ GETTERS }....................
def get_hint_pep557_initvar_arg(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep557Exception,
exception_prefix: str = '',
) -> object:
'''
PEP-compliant child type hint subscripting the passed PEP-compliant parent
type hint describing a **dataclass-specific initialization-only instance
variable** (i.e., instance of the :pep:`557`-compliant
:class:`dataclasses.InitVar` class introduced by Python 3.8.0).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Type hint to be inspected.
exception_cls : TypeException
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep557Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Returns
----------
object
PEP-compliant child type hint subscripting this parent type hint.
Raises
----------
BeartypeDecorHintPep557Exception
If this object does *not* describe a dataclass-specific
initialization-only instance variable.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign_or_none
# Sign uniquely identifying this hint if this hint is identifiable *OR*
# "None" otherwise.
hint_sign = get_hint_pep_sign_or_none(hint)
# If this hint does *NOT* describe a dataclass-specific
# initialization-only instance variable, raise an exception.
if hint_sign is not HintSignDataclassInitVar:
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} not '
f'PEP 557-compliant "dataclasses.TypeVar" instance.'
)
# Else, this hint describes such a variable.
# Return the child type hint subscripting this parent type hint. Yes,
# this hint exposes this child via a non-standard instance variable
# rather than the "__args__" dunder tuple standardized by PEP 484.
return hint.type # type: ignore[attr-defined]
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`604`-compliant type hint utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_10
# ....................{ TESTERS }....................
# If the active Python interpreter targets Python >= 3.10 and thus supports PEP
# 604, define testers requiring this level of support...
if IS_PYTHON_AT_LEAST_3_10:
# Defer version-specific imports.
from types import UnionType # type: ignore[attr-defined]
#FIXME: Unit test us up.
def is_hint_pep604(hint: object) -> bool:
# Release the werecars, Bender!
return isinstance(hint, UnionType)
# Else, the active Python interpreter targets Python < 3.10 and thus fails to
# support PEP 604. In this case, define fallback testers.
else:
def is_hint_pep604(hint: object) -> bool:
# Tonight, we howl at the moon. Tomorrow, the one-liner!
return False
is_hint_pep604.__doc__ = (
'''
``True`` only if the passed object is a :pep:`604`-compliant **union**
(i.e., ``|``-delimited disjunction of two or more isinstanceable types).
Parameters
----------
hint : object
Type hint to be inspected.
Returns
----------
bool
``True`` only if this object is a :pep:`604`-compliant union.
'''
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`585`-compliant type hint utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep585Exception
from beartype.typing import (
Any,
Set,
)
from beartype._cave._cavefast import HintGenericSubscriptedType
from beartype._util.cache.utilcachecall import callable_cached
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9
from beartype._util.utilobject import Iota
from beartype._data.datatyping import TupleTypes
# ....................{ HINTS }....................
HINT_PEP585_TUPLE_EMPTY = (
tuple[()] if IS_PYTHON_AT_LEAST_3_9 else Iota()) # type: ignore[misc]
'''
:pep:`585`-compliant empty fixed-length tuple type hint if the active Python
interpreter supports at least Python 3.9 and thus :pep:`585` *or* a unique
placeholder object otherwise to guarantee failure when comparing arbitrary
objects against this object via equality tests.
'''
# ....................{ VALIDATORS }....................
def die_unless_hint_pep585_generic(hint: object) -> None:
'''
Raise an exception unless the passed object is a :pep:`585`-compliant
**generic** (i.e., class superficially subclassing at least one subscripted
:pep:`585`-compliant pseudo-superclass).
Parameters
----------
hint : object
Object to be validated.
Raises
----------
BeartypeDecorHintPep585Exception
If this object is *not* a :pep:`585`-compliant generic.
'''
# If this object is *NOT* a PEP 585-compliant generic, raise an exception.
if not is_hint_pep585_generic(hint):
raise BeartypeDecorHintPep585Exception(
f'Type hint {repr(hint)} not PEP 585 generic.')
# Else, this object is a PEP 585-compliant generic.
# ....................{ TESTERS }....................
# If the active Python interpreter targets at least Python >= 3.9 and thus
# supports PEP 585, correctly declare this function.
if IS_PYTHON_AT_LEAST_3_9:
def is_hint_pep585_builtin(hint: object) -> bool:
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import (
is_hint_pep484585_generic)
# Return true only if this hint...
return (
# Is either a PEP 484- or -585-compliant subscripted generic or
# PEP 585-compliant builtin *AND*...
isinstance(hint, HintGenericSubscriptedType) and
# Is *NOT* a PEP 484- or -585-compliant subscripted generic.
not is_hint_pep484585_generic(hint)
)
@callable_cached
def is_hint_pep585_generic(hint: object) -> bool: # pyright: ignore[reportGeneralTypeIssues]
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import (
get_hint_pep484585_generic_type_or_none)
# If this hint is *NOT* a type, reduce this hint to the object
# originating this hint if any. See the comparable
# is_hint_pep484_generic() tester for further details.
hint = get_hint_pep484585_generic_type_or_none(hint)
# Tuple of all pseudo-superclasses originally subclassed by the passed
# hint if this hint is a generic *OR* false otherwise.
hint_bases_erased = getattr(hint, '__orig_bases__', False)
# If this hint subclasses *NO* pseudo-superclasses, this hint *CANNOT*
# be a generic. In this case, immediately return false.
if not hint_bases_erased:
return False
# Else, this hint subclasses one or more pseudo-superclasses.
# For each such pseudo-superclass...
#
# Unsurprisingly, PEP 585-compliant generics have absolutely *NO*
# commonality with PEP 484-compliant generics. While the latter are
# trivially detectable as subclassing "typing.Generic" after type
# erasure, the former are *NOT*. The only means of deterministically
# deciding whether or not a hint is a PEP 585-compliant generic is if:
# * That class defines both the __class_getitem__() dunder method *AND*
# the "__orig_bases__" instance variable. Note that this condition in
# and of itself is insufficient to decide PEP 585-compliance as a
# generic. Why? Because these dunder attributes have been
# standardized under various PEPs and may thus be implemented by
# *ANY* arbitrary classes.
# * The "__orig_bases__" instance variable is a non-empty tuple.
# * One or more objects listed in that tuple are PEP 585-compliant
# objects.
#
# Note we could technically also test that this hint defines the
# __class_getitem__() dunder method. Since this condition suffices to
# ensure that this hint is a PEP 585-compliant generic, however, there
# exists little benefit to doing so.
for hint_base_erased in hint_bases_erased: # type: ignore[union-attr]
# If this pseudo-superclass is itself a PEP 585-compliant type
# hint, return true.
if is_hint_pep585_builtin(hint_base_erased):
return True
# Else, this pseudo-superclass is *NOT* PEP 585-compliant. In this
# case, continue to the next pseudo-superclass.
# Since *NO* such pseudo-superclasses are PEP 585-compliant, this hint
# is *NOT* a PEP 585-compliant generic. In this case, return false.
return False
# Else, the active Python interpreter targets at most Python < 3.9 and thus
# fails to support PEP 585. In this case, fallback to declaring this function
# to unconditionally return False.
else:
def is_hint_pep585_builtin(hint: object) -> bool:
return False
def is_hint_pep585_generic(hint: object) -> bool:
return False
# ....................{ TESTERS ~ doc }....................
# Docstring for this function regardless of implementation details.
is_hint_pep585_builtin.__doc__ = '''
``True`` only if the passed object is a C-based :pep:`585`-compliant
**builtin type hint** (i.e., C-based type hint instantiated by subscripting
either a concrete builtin container class like :class:`list` or
:class:`tuple` *or* an abstract base class (ABC) declared by the
:mod:`collections.abc` submodule like :class:`collections.abc.Iterable` or
:class:`collections.abc.Sequence`).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This test returns false for** :pep:`585`-compliant **generics,** which
fail to satisfy the same API as all other :pep:`585`-compliant type hints.
Why? Because :pep:`560`-type erasure erases this API on
:pep:`585`-compliant generics immediately after those generics are
declared, preventing their subsequent detection as :pep:`585`-compliant.
Instead, :pep:`585`-compliant generics are only detectable by calling
either:
* The high-level PEP-agnostic
:func:`beartype._util.hint.pep.utilpeptest.is_hint_pep484585_generic`
tester.
* The low-level :pep:`585`-specific :func:`is_hint_pep585_generic` tester.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a :pep:`585`-compliant type hint.
'''
is_hint_pep585_generic.__doc__ = '''
``True`` only if the passed object is a :pep:`585`-compliant **generic**
(i.e., object that may *not* actually be a class originally subclassing at
least one subscripted :pep:`585`-compliant pseudo-superclass).
This tester is memoized for efficiency.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a :pep:`585`-compliant generic.
'''
# ....................{ GETTERS }....................
def get_hint_pep585_generic_bases_unerased(hint: Any) -> tuple:
'''
Tuple of all unerased :pep:`585`-compliant **pseudo-superclasses** (i.e.,
:mod:`typing` objects originally listed as superclasses prior to their
implicit type erasure under :pep:`560`) of the passed :pep:`585`-compliant
**generic** (i.e., class subclassing at least one non-class
:pep:`585`-compliant object).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
Tuple[object]
Tuple of the one or more unerased pseudo-superclasses of this
:pep:`585`-compliant generic.
Raises
----------
BeartypeDecorHintPep585Exception
If this hint is *not* a :pep:`585`-compliant generic.
See Also
----------
:func:`beartype._util.hint.pep.proposal.pep484585.utilpep484585generic.get_hint_pep484585_generic_bases_unerased`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import (
get_hint_pep484585_generic_type_or_none)
# If this hint is *NOT* a class, reduce this hint to the object originating
# this hint if any. See the is_hint_pep484_generic() tester for details.
hint = get_hint_pep484585_generic_type_or_none(hint)
# If this hint is *NOT* a PEP 585-compliant generic, raise an exception.
die_unless_hint_pep585_generic(hint)
# Return the tuple of all unerased pseudo-superclasses of this generic.
# While the "__orig_bases__" dunder instance variable is *NOT* guaranteed
# to exist for PEP 484-compliant generic types, this variable is guaranteed
# to exist for PEP 585-compliant generic types. Thanks for small favours.
return hint.__orig_bases__
@callable_cached
def get_hint_pep585_generic_typevars(hint: object) -> TupleTypes:
'''
Tuple of all **unique type variables** (i.e., subscripted :class:`TypeVar`
instances of the passed :pep:`585`-compliant generic listed by the caller
at hint declaration time ignoring duplicates) if any *or* the empty tuple
otherwise.
This getter is memoized for efficiency.
Motivation
----------
The current implementation of :pep:`585` under at least Python 3.9 is
fundamentally broken with respect to parametrized generics. While `PEP
484`_-compliant generics properly propagate type variables from
pseudo-superclasses to subclasses, :pep:`585` fails to do so. This function
"fills in the gaps" by recovering these type variables from parametrized
:pep:`585`-compliant generics by iteratively constructing a new tuple from
the type variables parametrizing all pseudo-superclasses of this generic.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
Tuple[TypeVar, ...]
Either:
* If this :pep:`585`-compliant generic defines a ``__parameters__``
dunder attribute, the value of that attribute.
* Else, the empty tuple.
Raises
----------
:exc:`BeartypeDecorHintPep585Exception`
If this hint is *not* a :pep:`585`-compliant generic.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_typevars
# Tuple of all pseudo-superclasses of this PEP 585-compliant generic.
hint_bases = get_hint_pep585_generic_bases_unerased(hint)
# Set of all type variables parametrizing these pseudo-superclasses.
#
# Note the following inefficient iteration *CANNOT* be reduced to an
# efficient set comprehension, as each get_hint_pep_typevars() call returns
# a tuple of type variables rather than single type variable to be added to
# this set.
hint_typevars: Set[type] = set()
# For each such pseudo-superclass, add all type variables parametrizing
# this pseudo-superclass to this set.
for hint_base in hint_bases:
# print(f'hint_base_typevars: {hint_base} [{get_hint_pep_typevars(hint_base)}]')
hint_typevars.update(get_hint_pep_typevars(hint_base))
# Return this set coerced into a tuple.
return tuple(hint_typevars)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant **new type hint utilities** (i.e.,
callables generically applicable to :pep:`484`-compliant types).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep484Exception
from beartype.typing import Any
from beartype._data.hint.pep.sign.datapepsigns import HintSignNewType
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_10
from types import FunctionType
# ....................{ TESTERS }....................
# If the active Python interpreter targets Python >= 3.10 and thus defines
# "typing.NewType" type hints as instances of that class, implement this tester
# unique to prior Python versions to raise an exception.
if IS_PYTHON_AT_LEAST_3_10:
def is_hint_pep484_newtype_pre_python310(hint: object) -> bool:
raise BeartypeDecorHintPep484Exception(
'is_hint_pep484_newtype_pre_python310() assumes Python < 3.10, '
'but current Python interpreter targets Python >= 3.10.'
)
# Else, the active Python interpreter targets Python < 3.10 and thus defines
# "typing.NewType" type hints as closures returned by that function. Since
# these closures are sufficiently dissimilar from all other type hints to
# require unique detection, implement this tester unique to this obsolete
# Python version to detect these closures.
else:
def is_hint_pep484_newtype_pre_python310(hint: object) -> bool:
# Return true only if...
return (
# This hint is a pure-Python function *AND*...
#
# Note that we intentionally do *NOT* call the callable() builtin
# here, as that builtin erroneously returns false positives for
# non-standard classes defining the __call__() dunder method to
# unconditionally raise exceptions. Critically, this includes most
# PEP 484-compliant type hints, which naturally fail to define both
# the "__module__" *AND* "__qualname__" dunder instance variables
# accessed below. Shoot me now, fam.
isinstance(hint, FunctionType) and
# This callable is a closure created and returned by the
# typing.NewType() function. Note that:
#
# * The "__module__" and "__qualname__" dunder instance variables
# are *NOT* generally defined for arbitrary objects but are
# specifically defined for callables.
# * "__qualname__" is safely available under Python >= 3.3.
# * This test derives from the observation that the concatenation
# of this callable's "__qualname__" and "__module" dunder
# instance variables suffices to produce a string unambiguously
# identifying whether this hint is a "NewType"-generated closure:
# >>> from typing import NewType
# >>> UserId = t.NewType('UserId', int)
# >>> UserId.__qualname__
# >>> 'NewType.<locals>.new_type'
# >>> UserId.__module__
# >>> 'typing'
f'{hint.__module__}.{hint.__qualname__}'.startswith(
'typing.NewType.')
)
is_hint_pep484_newtype_pre_python310.__doc__ = '''
``True`` only if the passed object is a Python < 3.10-specific
:pep:`484`-compliant **new type** (i.e., closure created and returned by
the :func:`typing.NewType` closure factory function).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**New type aliases are a complete farce and thus best avoided.**
Specifically, these PEP-compliant type hints are *not* actually types but
rather **identity closures** that return their passed parameters as is.
Instead, where distinct types are:
* *Not* required, simply annotate parameters and return values with the
desired superclasses.
* Required, simply:
* Subclass the desired superclasses as usual.
* Annotate parameters and return values with those subclasses.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a Python < 3.10-specific
:pep:`484`-compliant new type.
'''
# ....................{ GETTERS }....................
def get_hint_pep484_newtype_class(hint: Any) -> type:
'''
User-defined class aliased by the passed :pep:`484`-compliant **new type**
(i.e., object created and returned by the :func:`typing.NewType` type hint
factory).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
type
User-defined class aliased by this :pep:`484`-compliant new type.
Raises
----------
BeartypeDecorHintPep484Exception
If this object is *not* a :pep:`484`-compliant new type.
See Also
----------
:func:`is_hint_pep484_newtype`
Further commentary.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign
# If this object is *NOT* a PEP 484-compliant "NewType" hint, raise an
# exception.
if get_hint_pep_sign(hint) is not HintSignNewType:
raise BeartypeDecorHintPep484Exception(
f'Type hint {repr(hint)} not "typing.NewType".')
# Else, this object is a PEP 484-compliant "NewType" hint.
# Return the unqualified classname referred to by this reference. Note
# that this requires violating privacy encapsulation by accessing a dunder
# instance variable unique to closures created by the typing.NewType()
# closure factory function.
return hint.__supertype__
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant **union type hint utilities** (i.e.,
callables generically applicable to :pep:`484`-compliant :attr:`typing.Union`
subscriptions).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.typing import Union
# ....................{ MAKERS }....................
def make_hint_pep484_union(hints: tuple) -> object:
'''
:pep:`484`-compliant **union type hint** (:attr:`typing.Union`
subscription) synthesized from the passed tuple of two or more
PEP-compliant type hints if this tuple contains two or more items, the one
PEP-compliant type hint in this tuple if this tuple contains only one item,
*or* raise an exception otherwise (i.e., if this tuple is empty).
This maker is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the :attr:`typing.Union` type hint
factory already caches its subscripted arguments.
Parameters
----------
hint : object
Type hint to be inspected.
Returns
----------
object
Either:
* If this tuple contains two or more items, the union type hint
synthesized from these items.
* If this tuple contains only one item, this item as is.
Raises
----------
:exc:`TypeError`
If this tuple is empty.
'''
assert isinstance(hints, tuple), f'{repr(hints)} not tuple.'
# These are the one-liners of our lives.
return Union.__getitem__(hints) # pyright: ignore[reportGeneralTypeIssues]
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant **named tuple utilities** (i.e.,
callables generically applicable to :pep:`484`-compliant named tuples -- which
is to say, instances of concrete subclasses of the standard
:attr:`typing.NamedTuple` superclass).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._util.cls.utilclstest import is_type_subclass_proper
# from beartype.roar import BeartypeDecorHintPep484Exception
# from beartype.typing import Any
# from beartype._data.hint.pep.sign.datapepsigns import HintSignNewType
# from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_10
# from types import FunctionType
# ....................{ TESTERS }....................
#FIXME: Unit test us up, please.
#FIXME: Actually call this tester in the get_hint_pep_sign_or_none() getter to
#map "typing.NamedTuple" subclasses to the "HintSignNamedTuple" sign, please.
#FIXME: Actually type-check type hints identified by the "HintSignNamedTuple"
#sign. Specifically, for each "typing.NamedTuple" subclass identified by that
#sign, type-check that subclass as follows:
#* If that subclass is decorated by @beartype, reduce to the standard trivial
# isinstance() check. Since @beartype already type-checks instances of that
# subclass on instantiation, *NO* further type-checking is required or desired.
#* Else, that subclass is *NOT* decorated by @beartype. In this case, matters
# become considerably non-trivial. Why? Because:
# * This situation commonly arises when type-checking "typing.NamedTuple"
# subclasses *NOT* under user control (e.g., defined by upstream third-party
# packages in an app stack). Since these subclasses are *NOT* under user
# control, there exists *NO* safe means for @beartype to monkey-patch these
# subclasses with itself. Ergo, instances of these subclasses are guaranteed
# to *NOT* be type-checked at instantiation time.
# * The prior point implies that @beartype must instead type-check instances of
# these subclasses at @beartype call time. However, the naive approach to
# doing so is likely to prove inefficient. The naive approach is simply to
# type-check *ALL* fields of these instances *EVERY* time these instances are
# type-checked at @beartype call time. Since these fields could themselves
# refer to other "typing.NamedTuple" subclasses, combinatorial explosion
# violating O(1) constraints becomes a real possibility here.
# * *RECURSION.* Both direct and indirect recursion are feasible here. Both
# require PEP 563 and are thus unlikely. Nonetheless:
# * Direct recursion occurs under PEP 563 as follows:
# from __future__ import annotations
# from typing import NamedTuple
#
# class DirectlyRecursiveNamedTuple(NamedTuple):
# uhoh: DirectlyRecursiveNamedTuple
# * Indirect recursion occurs as PEP 563 follows:
# from typing import NamedTuple
#
# class IndirectlyRecursiveNamedTuple(NamedTuple):
# uhoh: YetAnotherNamedTuple
#
# class YetAnotherNamedTuple(NamedTuple):
# ohboy: IndirectlyRecursiveNamedTuple
#
#Guarding against both combinatorial explosion *AND* recursion is imperative. To
#do so, we'll need to fundamentally refactor our existing breadth-first search
#(BFS) over type hints into a new depth-first search (DFS) over type hints.
#We've extensively documented this in the "beartype._check.expr.__init__"
#submodule. Simply know that this will be non-trivial, albeit fun and needed!
def is_hint_pep484_namedtuple_subclass(hint: object) -> bool:
'''
``True`` only if the passed object is a :pep:`484`-compliant **named tuple
subclass** (i.e., concrete subclass of the standard
:attr:`typing.NamedTuple` superclass).
Note that the :attr:`typing.NamedTuple` attribute is *not* actually a
superclass; that attribute only superficially masquerades (through
inscrutable metaclass trickery) as a superclass. As one might imagine,
detecting "subclasses" of a non-existent superclass is non-trivial.
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a :pep:`484`-compliant named tuple
subclass.
'''
# Return true only if...
return (
# This hint is a proper tuple subclass (i.e., subclass of the builtin
# "tuple" type but *NOT* that type itself) *AND*...
is_type_subclass_proper(hint, tuple) and
#FIXME: Implement us up, please. To do so efficiently, we'll probably
#want to:
#* Declare a private global frozenset of the names of all uniquely
# identifying "typing.NamedTuple" attributes: e.g.,
# _NAMEDTUPLE_UNIQUE_ATTR_NAMES = frozenset((
# # "typing.NamedTuple"-specific quasi-public attributes.
# '__annotations__',
#
# # "collections.namedtuple"-specific quasi-public attributes.
# '_asdict',
# '_field_defaults',
# '_fields',
# '_make',
# '_replace',
# ))
#* Efficiently take the set intersection of that frozenset and
# "dir(tuple)". If that intersection is non-empty, then this type is
# *PROBABLY* a "typing.NamedTuple" subclass.
#
#Note that there does exist an alternative. Sadly, that alternative
#requires an O(n) test and is thus non-ideal. Nonetheless:
# typing.NamedTuple in getattr(hint, '__orig_bases__', ())
#
#That *DOES* have the advantage of being deterministic. But the above
#set intersection test is mostly deterministic and considerably
#faster... we think. Actually, is it? We have *NO* idea. Perhaps we
#should simply opt for the simplistic and deterministic O(n) approach.
True
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant **type variable utilities** (i.e.,
callables generically applicable to :pep:`484`-compliant type variables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep484Exception
from beartype.typing import TypeVar
from beartype._util.cache.utilcachecall import callable_cached
# ....................{ GETTERS }....................
@callable_cached
def get_hint_pep484_typevar_bound_or_none(hint: TypeVar) -> object:
'''
PEP-compliant type hint synthesized from all bounded constraints
parametrizing the passed :pep:`484`-compliant **type variable** (i.e.,
:mod:`typing.TypeVar` instance) if any *or* ``None`` otherwise (i.e., if
this type variable was parametrized by *no* bounded constraints).
Specifically, if this type variable was parametrized by:
#. One or more **constraints** (i.e., positional arguments passed by the
caller to the :meth:`typing.TypeVar.__init__` call initializing this
type variable), this getter returns a new **PEP-compliant union type
hint** (i.e., :attr:`typing.Union` subscription) of those constraints.
#. One **upper bound** (i.e., ``bound`` keyword argument passed by the
caller to the :meth:`typing.TypeVar.__init__` call initializing this
type variable), this getter returns that bound as is.
#. Else, this getter returns the ``None`` singleton.
Caveats
----------
**This getter treats constraints and upper bounds as semantically
equivalent,** preventing callers from distinguishing between these two
technically distinct variants of type variable metadata.
For runtime type-checking purposes, type variable constraints and bounds
are sufficiently similar as to be semantically equivalent for all intents
and purposes. To simplify handling of type variables, this getter
ambiguously aggregates both into the same tuple.
For static type-checking purposes, type variable constraints and bounds
are *still* sufficiently similar as to be semantically equivalent for all
intents and purposes. Any theoretical distinction between the two is likely
to be lost on *most* engineers, who tend to treat the two interchangeably.
To quote :pep:`484`:
...type constraints cause the inferred type to be _exactly_ one of the
constraint types, while an upper bound just requires that the actual
type is a subtype of the boundary type.
Inferred types are largely only applicable to static type-checkers, which
internally assign type variables contextual types inferred from set and
graph theoretic operations on the network of all objects (nodes) and
callables (edges) relating those objects. Runtime type-checkers have *no*
analogous operations, due to runtime space and time constraints.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator). If this type variable was parametrized
by one or more constraints, the :attr:`typing.Union` type hint factory
already caches these constraints; else, this getter performs no work. In
any case, this getter effectively performs to work.
Parameters
----------
hint : object
:pep:`484`-compliant type variable to be inspected.
Returns
----------
object
Either:
* If this type variable was parametrized by one or more constraints, a
new PEP-compliant union type hint aggregating those constraints.
* If this type variable was parametrized by an upper bound, that bound.
* Else, ``None``.
Raises
----------
BeartypeDecorHintPep484Exception
if this object is *not* a :pep:`484`-compliant type variable.
'''
# If this hint is *NOT* a type variable, raise an exception.
if not isinstance(hint, TypeVar):
raise BeartypeDecorHintPep484Exception(
f'{repr(hint)} not PEP 484 type variable.')
# Else, this hint is a type variable.
# If this type variable was parametrized by one or more constraints...
if hint.__constraints__:
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.pep484.utilpep484union import (
make_hint_pep484_union)
# Create and return the PEP 484-compliant union of these constraints.
return make_hint_pep484_union(hint.__constraints__)
# Else, this type variable was parametrized by *NO* constraints.
#
# If this type variable was parametrized by an upper bound, return that
# bound as is.
elif hint.__bound__ is not None:
return hint.__bound__
# Else, this type variable was parametrized by neither constraints *NOR* an
# upper bound.
# Return "None".
return None
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant **forward reference type hint utilities**
(i.e., callables specifically applicable to :pep:`484`-compliant forward
reference type hints).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintForwardRefException
from beartype.typing import (
Any,
ForwardRef,
)
from beartype._util.cache.utilcachecall import callable_cached
# ....................{ HINTS }....................
#FIXME: Refactor this now-useless global away, please. Specifically:
#* Globally replace all references to this global with references to
# "beartype.typing.ForwardRef" instead.
#* Excise this global.
HINT_PEP484_FORWARDREF_TYPE = ForwardRef
'''
:pep:`484`-compliant **forward reference type** (i.e., class of all forward
reference objects implicitly created by all :mod:`typing` type hint factories
when subscripted by a string).
'''
# ....................{ TESTERS }....................
def is_hint_pep484_forwardref(hint: object) -> bool:
'''
``True`` only if the passed object is a :pep:`484`-compliant **forward
reference type hint** (i.e., instance of the :class:`typing.ForwardRef`
class implicitly replacing all string arguments subscripting :mod:`typing`
objects).
The :mod:`typing` module implicitly replaces all strings subscripting
:mod:`typing` objects (e.g., the ``MuhType`` in ``List['MuhType']``) with
:class:`typing.ForwardRef` instances containing those strings as instance
variables, for nebulous reasons that make little justifiable sense.
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a :pep:`484`-compliant forward
reference type hint.
'''
# Return true only if this hint is an instance of the PEP 484-compliant
# forward reference superclass.
return isinstance(hint, HINT_PEP484_FORWARDREF_TYPE)
# ....................{ GETTERS }....................
@callable_cached
def get_hint_pep484_forwardref_type_basename(hint: Any) -> str:
'''
**Unqualified classname** (i.e., name of a class *not* containing a ``.``
delimiter and thus relative to the fully-qualified name of the lexical
scope declaring that class) referred to by the passed :pep:`484`-compliant
**forward reference type hint** (i.e., instance of the
:class:`typing.ForwardRef` class implicitly replacing all string arguments
subscripting :mod:`typing` objects).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
str
Unqualified classname referred to by this :pep:`484`-compliant forward
reference type hint.
Raises
----------
BeartypeDecorHintForwardRefException
If this object is *not* a :pep:`484`-compliant forward reference.
See Also
----------
:func:`is_hint_pep484_forwardref`
Further commentary.
'''
# If this object is *NOT* a PEP 484-compliant forward reference, raise an
# exception.
if not is_hint_pep484_forwardref(hint):
raise BeartypeDecorHintForwardRefException(
f'Type hint {repr(hint)} not forward reference.')
# Else, this object is a PEP 484-compliant forward reference.
# Return the unqualified classname referred to by this reference. Note
# that:
# * This requires violating privacy encapsulation by accessing a dunder
# instance variable unique to the "typing.ForwardRef" class.
# * This object defines a significant number of other "__forward_"-prefixed
# dunder instance variables, which exist *ONLY* to enable the blatantly
# useless typing.get_type_hints() function to avoid repeatedly (and thus
# inefficiently) reevaluating the same forward reference. *sigh*
return hint.__forward_arg__
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant **generic type hint utilities** (i.e.,
callables generically applicable to :pep:`484`-compliant generic classes).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep484Exception
from beartype.typing import (
Any,
Generic,
)
from beartype._util.cache.utilcachecall import callable_cached
from beartype._util.cls.utilclstest import is_type_subclass
# ....................{ TESTERS }....................
def is_hint_pep484_generic(hint: object) -> bool:
'''
``True`` only if the passed object is a :pep:`484`-compliant **generic**
(i.e., object that may *not* actually be a class originally subclassing at
least one PEP-compliant type hint defined by the :mod:`typing` module).
Specifically, this tester returns ``True`` only if this object was
originally defined as a class subclassing a combination of:
* At least one of:
* The :pep:`484`-compliant :mod:`typing.Generic` superclass.
* The :pep:`544`-compliant :mod:`typing.Protocol` superclass.
* Zero or more non-class :mod:`typing` pseudo-superclasses (e.g.,
``typing.List[int]``).
* Zero or more other standard superclasses.
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a :mod:`typing` generic.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import (
get_hint_pep484585_generic_type_or_none)
# If this hint is *NOT* a class, this hint is *NOT* an unsubscripted
# generic but could still be a subscripted generic (i.e., generic
# subscripted by one or more PEP-compliant child type hints). To
# decide, reduce this hint to the object originating this hint if any,
# enabling the subsequent test to test whether this origin object is an
# unsubscripted generic, which would then imply this hint to be a
# subscripted generic. If this strikes you as insane, you're not alone.
hint = get_hint_pep484585_generic_type_or_none(hint)
# Return true only if this hint is a subclass of the "typing.Generic"
# abstract base class (ABC), in which case this hint is a user-defined
# generic.
#
# Note that this test is robust against edge cases, as the "typing"
# module guarantees all user-defined classes subclassing one or more
# "typing" pseudo-superclasses to subclass the "typing.Generic"
# abstract base class (ABC) regardless of whether those classes did so
# explicitly. How? By type erasure, of course, the malignant gift that
# keeps on giving:
# >>> import typing as t
# >>> class MuhList(t.List): pass
# >>> MuhList.__orig_bases__
# (typing.List)
# >>> MuhList.__mro__
# (__main__.MuhList, list, typing.Generic, object)
#
# Note that:
# * This issubclass() call implicitly performs a surprisingly
# inefficient search over the method resolution order (MRO) of all
# superclasses of this hint. In theory, the cost of this search might
# be circumventable by observing that this ABC is expected to reside
# at the second-to-last index of the tuple exposing this MRO far all
# generics by virtue of fragile implementation details violating
# privacy encapsulation. In practice, this codebase is already
# fragile enough.
# * The following logic superficially appears to implement the same
# test *WITHOUT* the onerous cost of a search:
# return len(get_hint_pep484_generic_bases_unerased_or_none(hint)) > 0
# Why didn't we opt for that, then? Because this tester is routinely
# passed objects that *CANNOT* be guaranteed to be PEP-compliant.
# Indeed, the high-level is_hint_pep() tester establishing the
# PEP-compliance of arbitrary objects internally calls this
# lower-level tester to do so. Since the
# get_hint_pep484_generic_bases_unerased_or_none() getter internally
# reduces to returning the tuple of the general-purpose
# "__orig_bases__" dunder attribute formalized by PEP 560, testing
# whether that tuple is non-empty or not in no way guarantees this
# object to be a PEP-compliant generic.
return is_type_subclass(hint, Generic) # type: ignore[arg-type]
# ....................{ GETTERS }....................
@callable_cached
def get_hint_pep484_generic_base_erased_from_unerased(hint: Any) -> type:
'''
Erased superclass originating the passed :pep:`484`-compliant **unerased
pseudo-superclass** (i.e., :mod:`typing` object originally listed as a
superclass prior to its implicit type erasure by the :mod:`typing` module).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
:pep:`484`-compliant unerased pseudo-superclass to be reduced to its
erased superclass.
Returns
----------
type
Erased superclass originating this :pep:`484`-compliant unerased
pseudo-superclass.
Raises
----------
BeartypeDecorHintPep484Exception
if this object is *not* a :pep:`484`-compliant unerased
pseudo-superclass.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_origin_or_none
# Erased superclass originating this unerased pseudo-superclass if any *OR*
# "None" otherwise.
hint_origin_type = get_hint_pep_origin_or_none(hint)
# If this hint originates from *NO* such superclass, raise an exception.
if hint_origin_type is None:
raise BeartypeDecorHintPep484Exception(
f'Unerased PEP 484 generic or PEP 544 protocol {repr(hint)} '
f'originates from no erased superclass.'
)
# Else, this hint originates from such a superclass.
# Return this superclass.
return hint_origin_type
@callable_cached
def get_hint_pep484_generic_bases_unerased(hint: Any) -> tuple:
'''
Tuple of all unerased :mod:`typing` **pseudo-superclasses** (i.e.,
:mod:`typing` objects originally listed as superclasses prior to their
implicit type erasure under :pep:`560`) of the passed :pep:`484`-compliant
**generic** (i.e., class subclassing at least one non-class :mod:`typing`
object).
This getter is memoized for efficiency.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
tuple
Tuple of the one or more unerased pseudo-superclasses of this
:mod:`typing` generic. Specifically:
* If this generic defines an ``__orig_bases__`` dunder instance
variable, the value of that variable as is.
* Else, the value of the ``__mro__`` dunder instance variable stripped
of all ignorable classes conveying *no* semantic meaning, including:
* This generic itself.
* The :class:`object` root superclass.
Raises
----------
BeartypeDecorHintPep484Exception
If this hint is either:
* *Not* a :mod:`typing` generic.
* A :mod:`typing` generic that erased *none* of its superclasses but
whose method resolution order (MRO) lists strictly less than four
classes. Valid :pep:`484`-compliant generics should list at least
four classes, including (in order):
#. This class itself.
#. The one or more :mod:`typing` objects directly subclassed by this
generic.
#. The :class:`typing.Generic` superclass.
#. The zero or more non-:mod:`typing` superclasses subsequently
subclassed by this generic (e.g., :class:`abc.ABC`).
#. The :class:`object` root superclass.
See Also
----------
:func:`beartype._util.hint.pep.proposal.pep484585.utilpep484585generic.get_hint_pep484585_generic_bases_unerased`
Further details.
'''
#FIXME: This tuple appears to be implemented erroneously -- at least under
#Python 3.7, anyway. Although this tuple is implemented correctly for the
#common case of user-defined types directly subclassing "typing" types,
#this tuple probably is *NOT* implemented correctly for the edge case of
#user-defined types indirectly subclassing "typing" types: e.g.,
#
# >>> import collections.abc, typing
# >>> T = typing.TypeVar('T')
# >>> class Direct(collections.abc.Sized, typing.Generic[T]): pass
# >>> Direct.__orig_bases__
# (collections.abc.Sized, typing.Generic[~T])
# >>> class Indirect(collections.abc.Container, Direct): pass
# >>> Indirect.__orig_bases__
# (collections.abc.Sized, typing.Generic[~T])
#
#*THAT'S COMPLETELY INSANE.* Clearly, their naive implementation failed to
#account for actual real-world use cases.
#
#On the bright side, the current implementation prevents us from actually
#having to perform a breadth-first traversal of all original superclasses
#of this class in method resolution order (MRO). On the dark side, it's
#pants-on-fire balls -- but there's not much we can do about that. *sigh*
#
#If we ever need to perform that breadth-first traversal, resurrect this:
#
# # If this class was *NOT* subject to type erasure, reduce to a noop.
# if not hint_bases:
# return hint_bases
#
# # Fixed list of all typing super attributes to be returned.
# superattrs = acquire_fixed_list(FIXED_LIST_SIZE_MEDIUM)
#
# # 0-based index of the last item of this list.
# superattrs_index = 0
#
# # Fixed list of all transitive superclasses originally listed by this
# # class iterated in method resolution order (MRO).
# hint_orig_mro = acquire_fixed_list(FIXED_LIST_SIZE_MEDIUM)
#
# # 0-based indices of the current and last items of this list.
# hint_orig_mro_index_curr = 0
# hint_orig_mro_index_last = 0
#
# # Initialize this list with the tuple of all direct superclasses of this
# # class, which iteration then expands to all transitive superclasses.
# hint_orig_mro[:len(hint_bases)] = hint_bases
#
# # While the heat death of the universe has been temporarily forestalled...
# while (True):
# # Currently visited superclass of this class.
# hint_base = hint_orig_mro[hint_orig_mro_index_curr]
#
# # If this superclass is a typing attribute...
# if is_hint_pep_type_typing(hint_base):
# # Avoid inserting this attribute into the "hint_orig_mro" list.
# # Most typing attributes are *NOT* actual classes and those that
# # are have no meaningful public superclass. Ergo, iteration
# # terminates with typing attributes.
# #
# # Insert this attribute at the current item of this list.
# superattrs[superattrs_index] = hint_base
#
# # Increment this index to the next item of this list.
# superattrs_index += 1
#
# # If this class subclasses more than the maximum number of "typing"
# # attributes supported by this function, raise an exception.
# if superattrs_index >= FIXED_LIST_SIZE_MEDIUM:
# raise BeartypeDecorHintPep560Exception(
# '{} PEP type {!r} subclasses more than '
# '{} "typing" types.'.format(
# exception_prefix,
# hint,
# FIXED_LIST_SIZE_MEDIUM))
# # Else, this superclass is *NOT* a typing attribute. In this case...
# else:
# # Tuple of all direct superclasses originally listed by this class
# # prior to PEP 484 type erasure if any *OR* the empty tuple
# # otherwise.
# hint_base_bases = getattr(hint_base, '__orig_bases__')
#
# #FIXME: Implement breadth-first traversal here.
#
# # Tuple sliced from the prefix of this list assigned to above.
# superattrs_tuple = tuple(superattrs[:superattrs_index])
#
# # Release and nullify this list *AFTER* defining this tuple.
# release_fixed_list(superattrs)
# del superattrs
#
# # Return this tuple as is.
# return superattrs_tuple
#
#Also resurrect this docstring snippet:
#
# Raises
# ----------
# BeartypeDecorHintPep560Exception
# If this object defines the ``__orig_bases__`` dunder attribute but that
# attribute transitively lists :data:`FIXED_LIST_SIZE_MEDIUM` or more :mod:`typing`
# attributes.
#
#Specifically:
# * Acquire a fixed list of sufficient size (e.g., 64). We probably want
# to make this a constant in "utilcachelistfixedpool" for reuse
# everywhere, as this is clearly becoming a common idiom.
# * Slice-assign "__orig_bases__" into this list.
# * Maintain two simple 0-based indices into this list:
# * "bases_index_curr", the current base being visited.
# * "bases_index_last", the end of this list also serving as the list
# position to insert newly discovered bases at.
# * Iterate over this list and keep slice-assigning from either
# "__orig_bases__" (if defined) or "__mro__" (otherwise) into
# "list[bases_index_last:len(__orig_bases__)]". Note that this has the
# unfortunate disadvantage of temporarily iterating over duplicates,
# but... *WHO CARES.* It still works and we subsequently
# eliminate duplicates at the end.
# * Return a frozenset of this list, thus implicitly eliminating
# duplicate superclasses.
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import (
get_hint_pep484585_generic_type_or_none)
# If this hint is *NOT* a class, reduce this hint to the object originating
# this hint if any. See is_hint_pep484_generic() for details.
hint = get_hint_pep484585_generic_type_or_none(hint)
# If this hint is *NOT* a PEP 484-compliant generic, raise an exception.
if not is_hint_pep484_generic(hint):
raise BeartypeDecorHintPep484Exception(
f'Type hint {repr(hint)} neither '
f'PEP 484 generic nor PEP 544 protocol.'
)
# Else, this hint is a PEP 484-compliant generic.
# Unerased pseudo-superclasses of this generic if any *OR* "None"
# otherwise (e.g., if this generic is a single-inherited protocol).
hint_bases = getattr(hint, '__orig_bases__', None)
# If this generic erased its superclasses, return these superclasses as is.
if hint_bases is not None:
return hint_bases
# Else, this generic erased *NONE* of its superclasses. These superclasses
# *MUST* by definition be unerased and thus safely returnable as is.
# Unerased superclasses of this generic defined by the method resolution
# order (MRO) for this generic.
hint_bases = hint.__mro__
# Substring prefixing all exceptions raised below.
EXCEPTION_STR_PREFIX = (
f'PEP 484 generic {repr(hint)} '
f'method resolution order {repr(hint_bases)} '
)
# If this MRO lists strictly less than four classes, raise an exception.
# The MRO for any unerased generic should list at least four classes:
# * This class itself.
# * The one or more "typing" objects directly subclassed by this generic.
# * The "typing.Generic" superclass. Note that this superclass is typically
# but *NOT* necessarily the second-to-last superclass. Since this ad-hoc
# heuristic is *NOT* an actual constraint, we intentionally avoid
# asserting this to be the case. An example in which "typing.Generic" is
# *NOT* the second-to-last superclass is:
# class ProtocolCustomSuperclass(Protocol): pass
# class ProtocolCustomABC(ProtocolCustomSuperclass, ABC): pass
# * The "object" root superclass.
if len(hint_bases) < 4:
raise BeartypeDecorHintPep484Exception(
f'{EXCEPTION_STR_PREFIX}lists less than four types.')
# Else, this MRO lists at least four classes.
#
# If any class listed by this MRO fails to comply with the above
# expectations, raise an exception.
elif hint_bases[0] != hint:
raise BeartypeDecorHintPep484Exception(
f'{EXCEPTION_STR_PREFIX}first type '
f'{repr(hint_bases[0])} not {repr(hint)}.'
)
elif hint_bases[-1] != object:
raise BeartypeDecorHintPep484Exception(
f'{EXCEPTION_STR_PREFIX}last type '
f'{repr(hint_bases[-1])} not {repr(object)}.'
)
# Else, all classes listed by this MRO comply with the above expectations.
# Return a slice of this tuple preserving *ONLY* the non-ignorable
# superclasses listed by this tuple for conformance with the tuple returned
# by this getter from the "__orig_bases__", which similarly lists *ONLY*
# non-ignorable superclasses. Specifically, strip from this tuple:
# * This class itself.
# * The "object" root superclass.
#
# Ideally, the ignorable "(beartype.|)typing.(Generic|Protocol)"
# superclasses would also be stripped. Sadly, as exemplified by the above
# counter-example, those superclasses are *NOT* guaranteed to occupy the
# third- and second-to-last positions (respectively) of this tuple. Ergo,
# stripping these superclasses safely would require an inefficient
# iterative O(n) search across this tuple for those superclasses. Instead,
# we defer ignoring these superclasses to the caller -- which necessarily
# already (and hopefully efficiently) ignores ignorable superclasses.
return hint_bases[1:-1]
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant type hint utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._data.hint.pep.sign.datapepsigncls import HintSign
from beartype._data.hint.pep.sign.datapepsigns import (
HintSignGeneric,
HintSignNewType,
HintSignTypeVar,
)
from beartype._data.hint.pep.sign.datapepsignset import HINT_SIGNS_UNION
# Intentionally import PEP 484-compliant "typing" type hint factories rather
# than possibly PEP 585-compliant "beartype.typing" type hint factories.
from typing import (
Generic,
Optional,
Tuple,
)
# ....................{ HINTS }....................
HINT_PEP484_TUPLE_EMPTY = Tuple[()]
'''
:pep:`484`-compliant empty fixed-length tuple type hint.
'''
# ....................{ TESTERS ~ ignorable }....................
def is_hint_pep484_ignorable_or_none(
hint: object, hint_sign: HintSign) -> Optional[bool]:
'''
``True`` only if the passed object is a :pep:`484`-compliant **ignorable
type hint,** ``False`` only if this object is a :pep:`484`-compliant
unignorable type hint, and ``None`` if this object is *not* `PEP
484`_-compliant.
Specifically, this tester function returns ``True`` only if this object is
a deeply ignorable :pep:`484`-compliant type hint, including:
* A parametrization of the :class:`typing.Generic` abstract base class (ABC)
by one or more type variables. As the name implies, this ABC is generic
and thus fails to impose any meaningful constraints. Since a type variable
in and of itself also fails to impose any meaningful constraints, these
parametrizations are safely ignorable in all possible contexts: e.g.,
.. code-block:: python
from typing import Generic, TypeVar
T = TypeVar('T')
def noop(param_hint_ignorable: Generic[T]) -> T: pass
* The :func:`NewType` closure factory function passed an ignorable child
type hint. Unlike most :mod:`typing` constructs, that function does *not*
cache the objects it returns: e.g.,
.. code-block:: python
>>> from typing import NewType
>>> NewType('TotallyNotAStr', str) is NewType('TotallyNotAStr', str)
False
Since this implies every call to ``NewType({same_name}, object)`` returns
a new closure, the *only* means of ignoring ignorable new type aliases is
dynamically within this function.
* The :data:`Optional` or :data:`Union` singleton subscripted by one or
more ignorable type hints (e.g., ``typing.Union[typing.Any, bool]``).
Why? Because unions are by definition only as narrow as their widest
child hint. However, shallowly ignorable type hints are ignorable
precisely because they are the widest possible hints (e.g.,
:class:`object`, :attr:`typing.Any`), which are so wide as to constrain
nothing and convey no meaningful semantics. A union of one or more
shallowly ignorable child hints is thus the widest possible union,
which is so wide as to constrain nothing and convey no meaningful
semantics. Since there exist a countably infinite number of possible
:data:`Union` subscriptions by one or more ignorable type hints, these
subscriptions *cannot* be explicitly listed in the
:data:`HINTS_REPR_IGNORABLE_SHALLOW` frozenset. Instead, these
subscriptions are dynamically detected by this tester at runtime and thus
referred to as **deeply ignorable type hints.**
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as this tester is only safely callable
by the memoized parent
:func:`beartype._util.hint.utilhinttest.is_hint_ignorable` tester.
Parameters
----------
hint : object
Type hint to be inspected.
hint_sign : HintSign
**Sign** (i.e., arbitrary object uniquely identifying this hint).
Returns
----------
Optional[bool]
Either:
* If this object is :pep:`484`-compliant:
* If this object is a ignorable, ``True``.
* Else, ``False``.
* If this object is *not* :pep:`484`-compliant, ``None``.
'''
# print(f'Testing PEP 484 hint {repr(hint)} [{repr(hint_sign)}] deep ignorability...')
#FIXME: Remove this *AFTER* properly supporting type variables. For
#now, ignoring type variables is required ta at least shallowly support
#generics parametrized by one or more type variables.
# For minor efficiency gains, the following tests are intentionally ordered
# in descending likelihood of a match.
#
# If this hint is a PEP 484-compliant type variable, unconditionally return
# true. Type variables require non-trivial and currently unimplemented
# decorator support.
if hint_sign is HintSignTypeVar:
return True
# Else, this hint is *NOT* a PEP 484-compliant type variable.
#
# If this hint is a PEP 484-compliant union...
elif hint_sign in HINT_SIGNS_UNION:
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_args
from beartype._util.hint.utilhinttest import is_hint_ignorable
# Return true only if one or more child hints of this union are
# recursively ignorable. See the function docstring.
return any(
is_hint_ignorable(hint_child)
for hint_child in get_hint_pep_args(hint)
)
# Else, this hint is *NOT* a PEP 484-compliant union.
#
# If this hint is a PEP 484-compliant generic...
elif hint_sign is HintSignGeneric:
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import (
get_hint_pep_origin_or_none)
# print(f'Testing generic hint {repr(hint)} deep ignorability...')
# If this generic is the "typing.Generic" superclass directly
# parametrized by one or more type variables (e.g.,
# "typing.Generic[T]"), return true.
#
# Note that we intentionally avoid calling the
# get_hint_pep_origin_type_isinstanceable_or_none() function here, which
# has been intentionally designed to exclude PEP-compliant type hints
# originating from "typing" type origins for stability reasons.
if get_hint_pep_origin_or_none(hint) is Generic:
# print(f'Testing generic hint {repr(hint)} deep ignorability... True')
return True
# Else, this generic is *NOT* the "typing.Generic" superclass directly
# parametrized by one or more type variables and thus *NOT* an
# ignorable non-protocol.
#
# Note that this condition being false is *NOT* sufficient to declare
# this hint to be unignorable. Notably, the type origin originating
# both ignorable and unignorable protocols is "Protocol" rather than
# "Generic". Ergo, this generic could still be an ignorable protocol.
# print(f'Testing generic hint {repr(hint)} deep ignorability... False')
# Else, this hint is *NOT* a PEP 484-compliant generic.
#
# If this hint is a PEP 484-compliant new type...
elif hint_sign is HintSignNewType:
# Avoid circular import dependencies.
from beartype._util.hint.utilhinttest import is_hint_ignorable
from beartype._util.hint.pep.proposal.pep484.utilpep484newtype import (
get_hint_pep484_newtype_class)
# Return true only if this hint aliases an ignorable child type hint.
return is_hint_ignorable(get_hint_pep484_newtype_class(hint))
# Else, this hint is *NOT* a PEP 484-compliant new type.
# Return "None", as this hint is unignorable only under PEP 484.
return None
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`- and :pep:`585`-compliant **dual type hint utilities**
(i.e., callables generically applicable to both :pep:`484`- and
:pep:`585`-compliant type hints).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep484585Exception
from beartype.typing import (
Any,
Tuple,
TypeVar,
Union,
)
from beartype._data.hint.pep.sign.datapepsigns import (
HintSignForwardRef,
HintSignType,
HintSignUnion,
)
from beartype._util.cls.pep.utilpep3119 import (
die_unless_type_issubclassable,
die_unless_type_or_types_issubclassable,
)
from beartype._util.hint.pep.proposal.pep484585.utilpep484585arg import (
get_hint_pep484585_args_1)
from beartype._util.hint.pep.proposal.pep484585.utilpep484585ref import (
HINT_PEP484585_FORWARDREF_UNION)
from typing import (
Type as typing_Type, # <-- intentional to distinguish from "type" below
)
# ....................{ HINTS ~ private }....................
_HINT_PEP484585_SUBCLASS_ARGS_1_UNION = Union[
type, Tuple[type], TypeVar, HINT_PEP484585_FORWARDREF_UNION,]
'''
Union of the types of all permissible :pep:`484`- or :pep:`585`-compliant
**subclass type hint arguments** (i.e., PEP-compliant child type hints
subscripting (indexing) a subclass type hint).
'''
# ....................{ GETTERS }....................
def get_hint_pep484585_subclass_superclass(
hint: object,
exception_prefix: str,
) -> _HINT_PEP484585_SUBCLASS_ARGS_1_UNION:
'''
**Issubclassable superclass(es)** (i.e., class whose metaclass does *not*
define a ``__subclasscheck__()`` dunder method that raises an exception,
tuple of such classes, or forward reference to such a class) subscripting
the passed :pep:`484`- or :pep:`585`-compliant **subclass type hint**
(i.e., hint constraining objects to subclass that superclass).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
exception_prefix : str
Human-readable label prefixing the representation of this object in the
exception message.
Returns
----------
_HINT_PEP484585_SUBCLASS_ARGS_1_UNION
Argument subscripting this subclass type hint, guaranteed to be either:
* An issubclassable class.
* A tuple of issubclassable classes.
* A :pep:`484`-compliant forward reference to an issubclassable class
that typically has yet to be declared (i.e.,
:class:`typing.ForwardRef` instance).
* A :pep:`484`-compliant type variable constrained to classes (i.e.,
:class:`typing.TypeVar` instance).
* A :pep:`585`-compliant union of two or more issubclassable classes.
* A :pep:`484`-compliant type variable constrained to classes (i.e.,
:class:`typing.TypeVar` instance).
Raises
----------
BeartypeDecorHintPep3119Exception
If this superclass subscripting this type hint is *not*
**issubclassable** (i.e., class whose metaclass defines a
``__subclasscheck__()`` dunder method raising an exception).
BeartypeDecorHintPep484585Exception
If this hint is either:
* Neither a :pep:`484`- nor :pep:`585`-compliant subclass type hint.
* A :pep:`484`- or :pep:`585`-compliant subclass type hint subscripted
by one argument that is neither a class, union of classes, nor
forward reference to a class.
BeartypeDecorHintPep585Exception
If this hint is either:
* A :pep:`585`-compliant subclass type hint subscripted by either:
* *No* arguments.
* Two or more arguments.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import (
get_hint_pep_args,
get_hint_pep_sign_or_none,
)
# If this is *NOT* a subclass type hint, raise an exception.
_die_unless_hint_pep484585_subclass(
hint=hint, exception_prefix=exception_prefix)
# Else, this is either a subclass type hint.
# Superclass subscripting this hint.
hint_superclass = get_hint_pep484585_args_1(
hint=hint, exception_prefix=exception_prefix)
# Sign identifying this superclass.
hint_superclass_sign = get_hint_pep_sign_or_none(hint_superclass)
# If this superclass is actually a union of superclasses...
if hint_superclass_sign is HintSignUnion:
# Efficiently reduce this superclass to the tuple of superclasses
# subscripting and thus underlying this union.
hint_superclass = get_hint_pep_args(hint_superclass)
# If any item of this tuple is *NOT* an issubclassable class, raise an
# exception.
# print(f'hint_superclass union arg: {hint_superclass}')
die_unless_type_or_types_issubclassable(
type_or_types=hint_superclass, exception_prefix=exception_prefix) # type: ignore[arg-type]
# If this superclass is actually a forward reference to a superclass,
# silently accept this reference as is. This conditional exists only to
# avoid raising a subsequent exception.
elif hint_superclass_sign is HintSignForwardRef:
pass
# Else, this superclass is *NOT* a union of superclasses...
#
# If this superclass is a class...
elif isinstance(hint_superclass, type):
die_unless_type_issubclassable(
cls=hint_superclass, exception_prefix=exception_prefix)
# Else, this superclass is issubclassable.
# Else, this superclass is of an unexpected type. In this case, raise an
# exception.
#
# Note that PEP 585-compliant subclass type hints infrequently trigger this
# edge case. Although the "typing" module explicitly validates the
# arguments subscripting PEP 484-compliant type hints, the CPython
# interpreter applies *NO* such validation to PEP 585-compliant subclass
# type hints. For example, PEP 585-compliant subclass type hints are
# subscriptable by the empty tuple, which is technically an argument:
# >>> type[()].__args__
# () # <---- thanks fer nuthin
else:
raise BeartypeDecorHintPep484585Exception(
f'{exception_prefix}PEP 484 or 585 subclass type hint '
f'{repr(hint)} child type hint {repr(hint_superclass)} neither '
f'class, union of classes, nor forward reference to class.'
)
# Return this superclass.
return hint_superclass # type: ignore[return-value]
# ....................{ REDUCERS }....................
#FIXME: Unit test us up.
def reduce_hint_pep484585_subclass_superclass_if_ignorable(
hint: Any,
exception_prefix: str,
) -> Any:
'''
Reduce the passed :pep:`484`- or :pep:`585`-compliant **subclass type
hint** (i.e., hint constraining objects to subclass that superclass) to the
:class:`type` superclass if that hint is subscripted by an ignorable child
type hint (e.g., :attr:`typing.Any`, :class:`type`) *or* preserve this hint
as is otherwise (i.e., if that hint is *not* subscripted by an ignorable
child type hint).
This reducer is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Subclass type hint to be reduced.
exception_prefix : str
Human-readable label prefixing the representation of this object in the
exception message.
Raises
----------
BeartypeDecorHintPep484585Exception
If this hint is neither a :pep:`484`- nor :pep:`585`-compliant subclass
type hint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.utilhinttest import is_hint_ignorable
# If this is *NOT* a subclass type hint, raise an exception.
_die_unless_hint_pep484585_subclass(
hint=hint, exception_prefix=exception_prefix)
# Else, this is either a subclass type hint.
# If this hint is the unsubscripted PEP 484-compliant subclass type hint,
# immediately reduce this hint to the "type" superclass.
#
# Note that this is *NOT* merely a nonsensical optimization. The
# implementation of the unsubscripted PEP 484-compliant subclass type hint
# significantly differs across Python versions. Under some but *NOT* all
# supported Python versions (notably, Python 3.7 and 3.8), the "typing"
# module subversively subscripts this hint by a type variable; under all
# others, this hint remains unsubscripted. In the latter case, passing this
# hint to the subsequent get_hint_pep484585_args_1() would erroneously
# raise an exception.
if hint is typing_Type:
return type
# Else, this hint is *NOT* the unsubscripted PEP 484-compliant subclass
# type hint.
# Superclass subscripting this hint.
#
# Note that we intentionally do *NOT* call the high-level
# get_hint_pep484585_subclass_superclass() getter here, as the
# validation performed by that function would raise exceptions for
# various child type hints that are otherwise permissible (e.g.,
# "typing.Any").
hint_superclass = get_hint_pep484585_args_1(
hint=hint, exception_prefix=exception_prefix)
# If this argument is either...
if (
# An ignorable type hint (e.g., "typing.Any") *OR*...
is_hint_ignorable(hint_superclass) or
# The "type" superclass, which is effectively ignorable in this
# context of subclasses, as *ALL* classes necessarily subclass
# that superclass.
hint_superclass is type
):
# Reduce this subclass type hint to the "type" superclass.
hint = type
# Else, this argument is unignorable and thus irreducible.
# Return this possibly reduced type hint.
return hint
# ....................{ PRIVATE ~ validators }....................
def _die_unless_hint_pep484585_subclass(
hint: object, exception_prefix: str) -> None:
'''
Raise an exception unless the passed object is a :pep:`484`- or
:pep:`585`-compliant **subclass type hint** (i.e., hint constraining
objects to subclass that superclass).
Parameters
----------
hint : object
Object to be validated.
exception_prefix : str
Human-readable label prefixing the representation of this object in the
exception message.
Raises
----------
BeartypeDecorHintPep484585Exception
If this hint is neither a :pep:`484`- nor :pep:`585`-compliant subclass
type hint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign
# If this is neither a PEP 484- nor PEP 585-compliant subclass type hint,
# raise an exception.
if get_hint_pep_sign(hint) is not HintSignType:
raise BeartypeDecorHintPep484585Exception(
f'{exception_prefix}{repr(hint)} '
f'neither PEP 484 nor 585 subclass type hint.'
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`- and :pep:`585`-compliant **generic type hint
utilities** (i.e., callables generically applicable to both :pep:`484`-
and :pep:`585`-compliant generic classes).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep484585Exception
from beartype.typing import (
Optional,
Tuple,
)
from beartype._data.datatyping import TypeException
from beartype._data.hint.pep.sign.datapepsigns import HintSignGeneric
from beartype._util.cache.utilcachecall import callable_cached
from beartype._util.cache.pool.utilcachepoollistfixed import (
FIXED_LIST_SIZE_MEDIUM,
acquire_fixed_list,
release_fixed_list,
)
from beartype._util.hint.pep.proposal.pep484.utilpep484generic import (
get_hint_pep484_generic_bases_unerased,
is_hint_pep484_generic,
)
from beartype._util.hint.pep.proposal.utilpep585 import (
get_hint_pep585_generic_bases_unerased,
is_hint_pep585_generic,
)
from collections.abc import Iterable
# ....................{ TESTERS }....................
@callable_cached
def is_hint_pep484585_generic(hint: object) -> bool:
'''
``True`` only if the passed object is either a :pep:`484`- or
:pep:`585`-compliant **generic** (i.e., object that may *not* actually be a
class despite subclassing at least one PEP-compliant type hint that also
may *not* actually be a class).
Specifically, this tester returns ``True`` only if this object is either:
* A :pep:`585`-compliant generic as tested by the lower-level
:func:`is_hint_pep585_generic` function.
* A :pep:`484`-compliant generic as tested by the lower-level
:func:`is_hint_pep484_generic` function.
This tester is memoized for efficiency. Although the implementation
trivially reduces to a one-liner, constant factors associated with that
one-liner are non-negligible. Moreover, this tester is called frequently
enough to warrant its reduction to an efficient lookup.
Caveats
----------
**Generics are not necessarily classes,** despite originally being declared
as classes. Although *most* generics are classes, subscripting a generic
class usually produces a generic non-class that *must* nonetheless be
transparently treated as a generic class: e.g.,
.. code-block:: python
>>> from typing import Generic, TypeVar
>>> S = TypeVar('S')
>>> T = TypeVar('T')
>>> class MuhGeneric(Generic[S, T]): pass
>>> non_class_generic = MuhGeneric[S, T]
>>> isinstance(non_class_generic, type)
False
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a generic.
See Also
----------
:func:`is_hint_pep_typevars`
Commentary on the relation between generics and parametrized hints.
'''
# Return true only if this hint is...
return (
# A PEP 484-compliant generic. Note this test trivially reduces to
# an O(1) operation and is thus tested first.
is_hint_pep484_generic(hint) or
# A PEP 585-compliant generic. Note this test is O(n) in n the
# number of pseudo-superclasses originally subclassed by this
# generic and is thus tested last.
is_hint_pep585_generic(hint)
)
# ....................{ GETTERS ~ bases }....................
def get_hint_pep484585_generic_bases_unerased(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep484585Exception,
exception_prefix: str = '',
) -> Tuple[object, ...]:
'''
Tuple of all **unerased pseudo-superclasses** (i.e., PEP-compliant objects
originally listed as superclasses prior to their implicit type erasure
under :pep:`560`) of the passed :pep:`484`- or :pep:`585`-compliant
**generic** (i.e., class superficially subclassing at least one
PEP-compliant type hint that is possibly *not* an actual class) if this
object is a generic *or* raise an exception otherwise (i.e., if this object
is either not a class *or* is a class subclassing no non-class
PEP-compliant objects).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This function should always be called in lieu of attempting to directly
access the low-level** ``__orig_bases__`` **dunder instance variable.**
Most PEP-compliant type hints fail to declare that variable, guaranteeing
:class:`AttributeError` exceptions from all general-purpose logic
attempting to directly access that variable. Thus this function, which
"fills in the gaps" by implementing this oversight.
**This function returns tuples possibly containing a mixture of actual
superclasses and pseudo-superclasses superficially masquerading as actual
superclasses subscripted by one or more PEP-compliant child hints or type
variables** (e.g., ``(typing.Iterable[T], typing.Sized[T])``). Indeed, most
type hints used as superclasses produced by subscripting PEP-compliant type
hint factories are *not* actually types but singleton objects devilishly
masquerading as types. Most actual :mod:`typing` superclasses are private,
fragile, and prone to alteration or even removal between Python versions.
Motivation
----------
:pep:`560` (i.e., "Core support for typing module and generic types)
formalizes the ``__orig_bases__`` dunder attribute first informally
introduced by the :mod:`typing` module's implementation of :pep:`484`.
Naturally, :pep:`560` remains as unusable as :pep:`484` itself. Ideally,
:pep:`560` would have generalized the core intention of preserving each
original user-specified subclass tuple of superclasses as a full-blown
``__orig_mro__`` dunder attribute listing the original method resolution
order (MRO) of that subclass had that tuple *not* been modified.
Naturally, :pep:`560` did no such thing. The original MRO remains
obfuscated and effectively inaccessible. While computing that MRO would
technically be feasible, doing so would also be highly non-trivial,
expensive, and fragile. Instead, this function retrieves *only* the tuple
of :mod:`typing`-specific pseudo-superclasses that this object's class
originally attempted (but failed) to subclass.
You are probably now agitatedly cogitating to yourself in the darkness:
"But @leycec: what do you mean :pep:`560`? Wasn't :pep:`560` released
*after* :pep:`484`? Surely no public API defined by the Python stdlib would
be so malicious as to silently alter the tuple of base classes listed by a
user-defined subclass?"
As we've established both above and elsewhere throughout the codebase,
everything developed for :pep:`484` -- including :pep:`560`, which derives
its entire raison d'etre from :pep:`484` -- are fundamentally insane. In
this case, :pep:`484` is insane by subjecting parametrized :mod:`typing`
types employed as base classes to "type erasure," because:
...it is common practice in languages with generics (e.g. Java,
TypeScript).
Since Java and TypeScript are both terrible languages, blindly
recapitulating bad mistakes baked into such languages is an equally bad
mistake. In this case, "type erasure" means that the :mod:`typing` module
*intentionally* destroys runtime type information for nebulous and largely
unjustifiable reasons (i.e., Big Daddy Java and TypeScript do it, so it
must be unquestionably good).
Specifically, the :mod:`typing` module intentionally munges :mod:`typing`
types listed as base classes in user-defined subclasses as follows:
* All base classes whose origin is a builtin container (e.g.,
``typing.List[T]``) are reduced to that container (e.g.,
:class:`list`).
* All base classes derived from an abstract base class declared by the
:mod:`collections.abc` subpackage (e.g., ``typing.Iterable[T]``) are
reduced to that abstract base class (e.g.,
``collections.abc.Iterable``).
* All surviving base classes that are parametrized (e.g.,
``typing.Generic[S, T]``) are stripped of that parametrization (e.g.,
:class:`typing.Generic`).
Since there exists no counterpart to the :class:`typing.Generic`
superclass, the :mod:`typing` module preserves that superclass in
unparametrized form. Naturally, this is useless, as an unparametrized
:class:`typing.Generic` superclass conveys no meaningful type information.
All other superclasses are reduced to their non-:mod:`typing`
counterparts: e.g.,
.. code-block:: python
>>> from typing import TypeVar, Generic, Iterable, List
>>> T = TypeVar('T')
>>> class UserDefinedGeneric(List[T], Iterable[T], Generic[T]): pass
# This is type erasure.
>>> UserDefinedGeneric.__mro__
(list, collections.abc.Iterable, Generic)
# This is type preservation -- except the original MRO is discarded.
# So, it's not preservation; it's reduction! We take what we can get.
>>> UserDefinedGeneric.__orig_bases__
(typing.List[T], typing.Iterable[T], typing.Generic[T])
# Guess which we prefer?
So, we prefer the generally useful ``__orig_bases__`` dunder tuple over
the generally useless ``__mro__`` dunder tuple. Note, however, that the
latter *is* still occasionally useful and thus occasionally returned by
this getter. For inexplicable reasons, **single-inherited protocols**
(i.e., classes directly subclassing *only* the :pep:`544`-compliant
:attr:`typing.Protocol` abstract base class (ABC)) are *not* subject to
type erasure and thus constitute a notable exception to this heuristic:
.. code-block:: python
>>> from typing import Protocol
>>> class UserDefinedProtocol(Protocol): pass
>>> UserDefinedProtocol.__mro__
(__main__.UserDefinedProtocol, typing.Protocol, typing.Generic, object)
>>> UserDefinedProtocol.__orig_bases__
AttributeError: type object 'UserDefinedProtocol' has no attribute
'__orig_bases__'
Welcome to :mod:`typing` hell, where even :mod:`typing` types lie broken
and misshapen on the killing floor of overzealous theory-crafting purists.
Parameters
----------
hint : object
Generic type hint to be inspected.
exception_cls : TypeException
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep484585Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Returns
----------
Tuple[object]
Tuple of the one or more unerased pseudo-superclasses of this generic.
Raises
----------
:exc:`exception_cls`
If this hint is either:
* Neither a :pep:`484`- nor :pep:`585`-compliant generic.
* A :pep:`484`- nor :pep:`585`-compliant generic subclassing *no*
pseudo-superclasses.
Examples
----------
>>> import typing
>>> from beartype._util.hint.pep.utilpepget import (
... get_hint_pep484585_generic_bases_unerased)
>>> T = typing.TypeVar('T')
>>> class MuhIterable(typing.Iterable[T], typing.Container[T]): pass
>>> get_hint_pep585_generic_bases_unerased(MuhIterable)
(typing.Iterable[~T], typing.Container[~T])
>>> MuhIterable.__mro__
(MuhIterable,
collections.abc.Iterable,
collections.abc.Container,
typing.Generic,
object)
'''
#FIXME: Refactor get_hint_pep585_generic_bases_unerased() and
#get_hint_pep484_generic_bases_unerased() to:
#* Raise "BeartypeDecorHintPep484585Exception" instead.
#* Accept an optional "exception_prefix" parameter, which we should pass
# here.
# Tuple of either...
#
# Note this implicitly raises a "BeartypeDecorHintPepException" if this
# object is *NOT* a PEP-compliant generic. Ergo, we need not explicitly
# validate that above.
hint_pep_generic_bases_unerased = (
# If this is a PEP 585-compliant generic, all unerased
# pseudo-superclasses of this PEP 585-compliant generic.
get_hint_pep585_generic_bases_unerased(hint)
if is_hint_pep585_generic(hint) else
# Else, this *MUST* be a PEP 484-compliant generic. In this case, all
# unerased pseudo-superclasses of this PEP 484-compliant generic.
get_hint_pep484_generic_bases_unerased(hint)
)
# If this generic subclasses *NO* pseudo-superclass, raise an exception.
#
# Note this should have already been guaranteed on our behalf by:
# * If this generic is PEP 484-compliant, the "typing" module.
# * If this generic is PEP 585-compliant, CPython or PyPy itself.
if not hint_pep_generic_bases_unerased:
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
raise exception_cls(
f'{exception_prefix}PEP 484 or 585 generic {repr(hint)} '
f'subclasses no superclasses.'
)
# Else, this generic subclasses one or more pseudo-superclasses.
# Return this tuple of these pseudo-superclasses.
return hint_pep_generic_bases_unerased
# ....................{ GETTERS }....................
#FIXME: Unit test us up, please.
def get_hint_pep484585_generic_type(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep484585Exception,
exception_prefix: str = '',
) -> type:
'''
Either the passed :pep:`484`- or :pep:`585`-compliant **generic** (i.e.,
class superficially subclassing at least one PEP-compliant type hint that is
possibly *not* an actual class) if **unsubscripted** (i.e., indexed by *no*
arguments or type variables), the unsubscripted generic underlying this
generic if **subscripted** (i.e., indexed by one or more child type hints
and/or type variables), *or* raise an exception otherwise (i.e., if this
hint is *not* a generic).
Specifically, this getter returns (in order):
* If this hint originates from an **origin type** (i.e., isinstanceable
class such that *all* objects satisfying this hint are instances of that
class), this type regardless of whether this hint is already a class.
* Else if this hint is already a class, this hint as is.
* Else, raise an exception.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This getter returns false positives in edge cases.** That is, this getter
returns non-``None`` values for both generics and non-generics (notably,
non-generics defining the ``__origin__`` dunder attribute to an
isinstanceable class). Callers *must* perform subsequent tests to
distinguish these two cases.
Parameters
----------
hint : object
Generic type hint to be inspected.
exception_cls : TypeException
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep484585Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Returns
----------
type
Class originating this generic.
Raises
----------
:exc:`exception_cls`
If this hint is *not* a generic.
See Also
----------
:func:`get_hint_pep484585_generic_type_or_none`
Further details.
'''
# Either this hint if this hint is an unsubscripted generic, the
# unsubscripted generic underlying this hint if this hint is a subscripted
# generic, *OR* "None" if this hint is not a generic.
hint_generic_type = get_hint_pep484585_generic_type_or_none(hint)
# If this hint is *NOT* a generic, raise an exception.
if hint_generic_type is None:
raise exception_cls(
f'{exception_prefix}PEP 484 or 585 generic {repr(hint)} '
f'not generic (i.e., originates from no isinstanceable class).'
)
# Else, this hint is a generic.
# Return this class.
return hint_generic_type
def get_hint_pep484585_generic_type_or_none(hint: object) -> Optional[type]:
'''
Either the passed :pep:`484`- or :pep:`585`-compliant **generic** (i.e.,
class superficially subclassing at least one PEP-compliant type hint that
is possibly *not* an actual class) if **unsubscripted** (i.e., indexed by
*no* arguments or type variables), the unsubscripted generic underlying
this generic if **subscripted** (i.e., indexed by one or more child type
hints and/or type variables), *or* ``None`` otherwise (i.e., if this hint
is *not* a generic).
Specifically, this getter returns (in order):
* If this hint originates from an **origin type** (i.e., isinstanceable
class such that *all* objects satisfying this hint are instances of that
class), this type regardless of whether this hint is already a class.
* Else if this hint is already a class, this hint as is.
* Else, ``None``.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This getter returns false positives in edge cases.** That is, this getter
returns non-``None`` values for both generics and non-generics (notably,
non-generics defining the ``__origin__`` dunder attribute to an
isinstanceable class). Callers *must* perform subsequent tests to
distinguish these two cases.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
Optional[type]
Either:
* If this hint is a generic, the class originating this generic.
* Else, ``None``.
See Also
----------
:func:`get_hint_pep_origin_or_none`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_origin_or_none
# Arbitrary object originating this hint if any *OR* "None" otherwise.
hint_origin = get_hint_pep_origin_or_none(hint)
# print(f'{repr(hint)} hint_origin: {repr(hint_origin)}')
# If this origin is a type, this is the origin type originating this hint.
# In this case, return this type.
if isinstance(hint_origin, type):
return hint_origin
# Else, this origin is *NOT* a type.
#
# Else if this hint is already a type, this type is effectively already its
# origin type. In this case, return this type as is.
elif isinstance(hint, type):
return hint
# Else, this hint is *NOT* a type. In this case, this hint originates from
# *NO* origin type.
# Return the "None" singleton.
return None
# ....................{ ITERATORS }....................
#FIXME: Unit test us up, please.
def iter_hint_pep484585_generic_bases_unerased_tree(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep484585Exception,
exception_prefix: str = '',
) -> Iterable:
'''
Breadth-first search (BFS) generator iteratively yielding the one or more
unignorable unerased transitive pseudo-superclasses originally declared as
superclasses prior to their type erasure of the passed :pep:`484`- or
:pep:`585`-compliant generic.
This generator yields the full tree of all pseudo-superclasses by
transitively visiting both all direct pseudo-superclasses of this generic
*and* all indirect pseudo-superclasses transitively superclassing all direct
pseudo-superclasses of this generic. For efficiency, this generator is
internally implemented with an efficient imperative First In First Out
(FILO) queue rather than an inefficient (and dangerous, due to both
unavoidable stack exhaustion and avoidable infinite recursion) tree of
recursive function calls.
Motivation
----------
Ideally, a BFS would *not* be necessary. Instead, pseudo-superclasses
visited by this BFS should be visitable as is via whatever external parent
BFS is currently iterating over the tree of all transitive type hints (e.g.,
our code generation algorithm implemented by the
:func:`beartype._check.expr.exprmake.make_func_wrapper_code` function).
That's how we transitively visit all other kinds of type hints, right?
Sadly, that simple solution fails to scale to all possible edge cases that
arise with generics. Why? Because our code generation algorithm sensibly
requires that *only* unignorable hints may be enqueued onto its outer BFS.
Generics confound that constraint. Some pseudo-superclasses are
paradoxically:
* Ignorable from the perspective of code generation. *No* type-checking code
should be generated for these pseudo-superclasses. See reasons below.
* Unignorable from the perspective of algorithm visitation. These
pseudo-superclasses generate *no* code but may themselves subclass other
pseudo-superclasses for which type-checking code should be generated and
which must thus be visited by our outer BFS.
Paradoxical pseudo-superclasses include:
* User-defined :pep:`484`-compliant subgenerics (i.e., user-defined generics
subclassing one or more parent user-defined generic superclasses).
* User-defined :pep:`544`-compliant subprotocols (i.e., user-defined
protocols subclassing one or more parent user-defined protocol
superclasses).
Consider this example :pep:`544`-compliant subprotocol:
>>> import typing as t
>>> class UserProtocol(t.Protocol[t.AnyStr]): pass
>>> class UserSubprotocol(UserProtocol[str], t.Protocol): pass
>>> UserSubprotocol.__orig_bases__
(UserProtocol[str], typing.Protocol)
>>> UserProtocolUnerased = UserSubprotocol.__orig_bases__[0]
>>> UserProtocolUnerased is UserProtocol
False
>>> isinstance(UserProtocolUnerased, type)
False
:pep:`585`-compliant generics suffer no such issues:
>>> from beartype._util.hint.pep.proposal.utilpep585 import is_hint_pep585_builtin
>>> class UserGeneric(list[int]): pass
>>> class UserSubgeneric(UserGeneric[int]): pass
>>> UserSubgeneric.__orig_bases__
(UserGeneric[int],)
>>> UserGenericUnerased = UserSubgeneric.__orig_bases__[0]
>>> isinstance(UserGenericUnerased, type)
True
>>> UserGenericUnerased.__mro__
(UserGeneric, list, object)
>>> is_hint_pep585_builtin(UserGenericUnerased)
True
Iteratively walking up the unerased inheritance hierarchy for any such
paradoxical generic or protocol subclass (e.g., ``UserSubprotocol`` but
*not* ``UserSubgeneric`` above) would visit a user-defined generic or
protocol pseudo-superclass subscripted by type variables. Due to poorly
defined obscurities in the :mod:`typing` implementation, that
pseudo-superclass is *not* actually a class but rather an instance of a
private :mod:`typing` class (e.g., :class:`typing._SpecialForm`). This
algorithm would then detect that pseudo-superclass as neither a generic nor
a :mod:`typing` object and thus raise an exception. Fortunately, that
pseudo-superclass conveys no meaningful intrinsic semantics with respect to
type-checking; its only use is to register its own pseudo-superclasses (one
or more of which could convey meaningful intrinsic semantics with respect to
type-checking) for visitation by this BFS.
Parameters
----------
hint : object
Generic type hint to be inspected.
exception_cls : TypeException
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep484585Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Returns
----------
Iterable
Breadth-first search (BFS) generator iteratively yielding the one or
more unignorable unerased transitive pseudo-superclasses originally
declared as superclasses prior to their type erasure of this generic.
Raises
----------
:exc:`exception_cls`
If this hint is *not* a generic.
See Also
----------
:func:`get_hint_pep484585_generic_type_or_none`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.proposal.utilpep585 import (
is_hint_pep585_builtin)
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign_or_none
from beartype._util.hint.pep.utilpeptest import is_hint_pep_typing
from beartype._util.hint.utilhinttest import is_hint_ignorable
# Tuple of the one or more unerased pseudo-superclasses originally listed as
# superclasses prior to their type erasure by this generic.
hint_bases_direct = get_hint_pep484585_generic_bases_unerased(
hint=hint,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# print(f'generic {hint} hint_bases_direct: {hint_bases_direct}')
# Fixed list of the one or more unerased transitive pseudo-superclasses
# originally listed as superclasses prior to their type erasure by this
# generic that have yet to be visited by the breadth-first search (BFS) over
# these superclasses performed below.
hint_bases = acquire_fixed_list(size=FIXED_LIST_SIZE_MEDIUM)
# 0-based index of the currently visited pseudo-superclass of this list.
hint_bases_index_curr = 0
# 0-based index of one *PAST* the last pseudo-superclass of this list.
hint_bases_index_past_last = len(hint_bases_direct)
# Initialize this list to these direct pseudo-superclasses of this generic.
hint_bases[0:hint_bases_index_past_last] = hint_bases_direct
# print(f'generic pseudo-superclasses [initial]: {repr(hint_childs)}')
# While the 0-based index of the next visited pseudo-superclass does *NOT*
# exceed that of the last pseudo-superclass in this list, there remains one
# or more pseudo-superclasses to be visited in this BFS.
while hint_bases_index_curr < hint_bases_index_past_last:
# Currently visited pseudo-superclass.
hint_base = hint_bases[hint_bases_index_curr]
# print(f'generic {hint} base: {repr(hint_base)}')
# Sign uniquely identifying this pseudo-superclass if any *OR* "None".
hint_base_sign = get_hint_pep_sign_or_none(hint_base)
# If this pseudo-superclass is neither...
if not (
# A type conveying no meaningful typing semantics *NOR*...
#
# Note that types conveying no meaningful typing semantics are
# effectively ignorable. Why? Because the caller already type-checks
# this pith against the generic subclassing this superclass and thus
# this superclass as well in an isinstance() call (e.g., in the
# "PEP484585_CODE_HINT_GENERIC_PREFIX" snippet leveraged by the
# "beartype._check.expr.exprmake" submodule).
hint_base_sign is None or
# An ignorable PEP-compliant type hint...
is_hint_ignorable(hint_base)
# Then this pseudo-superclass is unignorable. In this case...
):
#FIXME: Unit test up this branch, please.
# If this pseudo-superclass is...
if (
# A PEP-compliant generic *AND*...
hint_base_sign is HintSignGeneric and
# Is neither...
not (
# A PEP 585-compliant superclass *NOR*...
is_hint_pep585_builtin(hint_base) and
# A PEP 484- nor 544-compliant superclass defined by the
# "typing" module...
is_hint_pep_typing(hint_base)
)
):
# Then this pseudo-superclass is a user-defined PEP 484-compliant
# generic or 544-compliant protocol. In this case, generate *NO*
# type-checking code for this pseudo-superclass; we only enqueue all
# parent pseudo-superclasses of this pseudo-superclasses for
# visitation by later iteration of this inner BFS.
#
# See "hints_bases" for explanatory commentary.
# Tuple of the one or more parent pseudo-superclasses of this
# child pseudo-superclass.
hint_base_bases = (
get_hint_pep484585_generic_bases_unerased(
hint=hint_base,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
))
# 0-based index of the last pseudo-superclass
# of this list *BEFORE* adding onto this list.
hint_bases_index_past_last_prev = (
hint_bases_index_past_last)
# 0-based index of the last pseudo-superclass
# of this list *AFTER* adding onto this list.
hint_bases_index_past_last += len(hint_base_bases)
# Enqueue these superclasses onto this list.
hint_bases[
hint_bases_index_past_last_prev:
hint_bases_index_past_last
] = hint_base_bases
# Else, this pseudo-superclass is neither an ignorable user-defined
# PEP 484-compliant generic *NOR* an ignorable 544-compliant
# protocol. In this case, yield this unignorable pseudo-superclass.
else:
yield hint_base
# Else, this pseudo-superclass is ignorable.
# else:
# print(f'Ignoring generic {hint} base...')
# print(f'Is generic {hint} base type? {isinstance(hint_base, type)}')
# Nullify the previously visited pseudo-superclass in
# this list for safety.
hint_bases[hint_bases_index_curr] = None
# Increment the 0-based index of the next visited
# pseudo-superclass in this list *BEFORE* visiting that
# pseudo-superclass but *AFTER* performing all other
# logic for the currently visited pseudo-superclass.
hint_bases_index_curr += 1
# Release this list. Pray for salvation, for we find none here.
release_fixed_list(hint_bases)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`- and :pep:`585`-compliant **callable type hint
utilities** (i.e., callables generically applicable to both :pep:`484`- and
:pep:`585`-compliant ``Callable[...]`` type hints).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
import beartype.typing as typing
from beartype.roar import BeartypeDecorHintPep484585Exception
from beartype.typing import (
TYPE_CHECKING,
Union,
)
from beartype._data.datatyping import TypeException
from beartype._data.hint.pep.sign.datapepsigns import HintSignCallable
from beartype._data.hint.pep.sign.datapepsignset import (
HINT_SIGNS_CALLABLE_PARAMS)
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_10
# ....................{ HINTS }....................
# If an external static type checker (e.g., "mypy") is currently subjecting
# "beartype" to static analysis, reduce this hint to a simplistic facsimile of
# its full form tolerated by static type checkers.
if TYPE_CHECKING:
_HINT_PEP484585_CALLABLE_PARAMS = Union[
# For hints of the form "Callable[[{arg_hints}], {return_hint}]".
tuple,
# For hints of the form "Callable[typing.ParamSpec[...], {return_hint}]".
typing.ParamSpec
]
# Else, expand this hint to its full form supported by runtime type checkers.
else:
_HINT_PEP484585_CALLABLE_PARAMS = Union[
# For hints of the form "Callable[[{arg_hints}], {return_hint}]".
tuple,
# For hints of the form "Callable[..., {return_hint}]".
type(Ellipsis),
# If the active Python interpreter targets Python >= 3.10, a union
# additionally matching the PEP 612-compliant "ParamSpec" type.
(
# For hints of the form "Callable[typing.ParamSpec[...], {return_hint}]".
typing.ParamSpec
if IS_PYTHON_AT_LEAST_3_10 else
# Else, the active Python interpreter targets Python < 3.10. In this
# case, a meaninglessly redundant type listed above reducing to a noop.
tuple
)
]
'''
PEP-compliant type hint matching the first argument originally subscripting
a :pep:`484`- or :pep:`585`-compliant **callable type hint** (i.e.,
``typing.Callable[...]`` or ``collections.abc.Callable[...]`` type hint).
'''
# ....................{ VALIDATORS }....................
def _die_unless_hint_pep484585_callable(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep484585Exception,
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is either a :pep:`484`- or
:pep:`585`-compliant **callable type hint** (i.e., ``typing.Callable[...]``
or ``collections.abc.Callable[...]`` type hint).
Parameters
----------
hint : object
Object to be validated.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep484585Exception`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this hint is either:
* PEP-compliant but *not* uniquely identifiable by a sign.
* PEP-noncompliant.
* *Not* a hint (i.e., neither PEP-compliant nor -noncompliant).
* *Not* a callable type hint (i.e., ``typing.Callable[...]`` or
``collections.abc.Callable[...]``).
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign
# Sign uniquely identifying this hint if any *OR* raise an exception.
hint_sign = get_hint_pep_sign(
hint=hint,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# If this object is *NOT* a callable type hint, raise an exception.
if hint_sign is not HintSignCallable:
assert issubclass(exception_cls, Exception), (
f'{repr(exception_cls)} not exception class.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} not '
f'PEP 484 or 585 callable type hint '
f'(i.e., "typing.Callable[...]" or '
f'"collections.abc.Callable[...]").'
)
# Else, this object is a callable type hint, raise an exception.
# ....................{ GETTERS }....................
def get_hint_pep484585_callable_params(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep484585Exception,
exception_prefix: str = '',
) -> _HINT_PEP484585_CALLABLE_PARAMS:
'''
Object describing all **parameter type hints** (i.e., PEP-compliant child
type hints typing the parameters accepted by a passed or returned callable)
of the passed **callable type hint** (i.e., :pep:`484`-compliant
``typing.Callable[...]`` or :pep:`585`-compliant
``collections.abc.Callable[...]`` type hint).
This getter returns one of several different types of objects, conditionally
depending on the type of the first argument originally subscripting this
hint. Specifically, if this hint was of the form:
* ``Callable[[{arg_hints}], {return_hint}]``, this getter returns a tuple of
the zero or more parameter type hints subscripting (indexing) this hint.
* ``Callable[..., {return_hint}]``, the :data:`Ellipsis` singleton.
* ``Callable[typing.ParamSpec[...], {return_hint}]``, the
``typing.ParamSpec[...]`` subscripting (indexing) this hint.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation requires no
iteration and thus exhibits guaranteed constant-time behaviour.
Parameters
----------
hint : object
Callable type hint to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep484585Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Returns
----------
_HINT_PEP484585_CALLABLE_PARAMS
First argument originally subscripting this hint.
Raises
----------
:exc:`exception_cls`
If this hint is *not* a callable type hint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import (
get_hint_pep_args,
get_hint_pep_sign_or_none,
)
# If this hint is *NOT* a callable type hint, raise an exception.
_die_unless_hint_pep484585_callable(hint)
# Else, this hint is a callable type hint.
# Flattened tuple of the one or more child type hints subscripting this
# callable type hint. Presumably for space efficiency reasons, both PEP 484-
# *AND* 585-compliant callable type hints implicitly flatten the "__args__"
# dunder tuple from the original data structure subscripting those hints.
# CPython produces this flattened tuple as the concatenation of:
#
# * Either:
# * If the first child type originally subscripting this hint was a list,
# all items subscripting the nested list of zero or more parameter type
# hints originally subscripting this hint as is: e.g.,
# >>> Callable[[], bool]
# (bool,)
# >>> Callable[[int, str], bool]
# (int, str, bool)
# This includes a list containing only the empty tuple signifying a
# callable accepting *NO* parameters, in which case that empty tuple is
# preserved as is: e.g.,
# >>> Callable[[()], bool]
# ((), bool)
# * Else, the first child type originally subscripting this hint as is. In
# this case, that child type is required to be either:
# * An ellipsis object (i.e., the "Ellipsis" builtin singleton): e.g.,
# >>> Callable[..., bool]
# (Ellipsis, bool)
# * A PEP 612-compliant parameter specification (i.e.,
# "typing.ParamSpec[...]" type hint): e.g.,
# >>> Callable[ParamSpec('P'), bool]
# (~P, bool)
# * A PEP 612-compliant parameter concatenation (i.e.,
# "typing.Concatenate[...]" type hint): e.g.,
# >>> Callable[Concatenate[str, ParamSpec('P')], bool]
# (typing.Concatenate[str, ~P], bool)
# * The return type hint originally subscripting this hint.
#
# Note that both PEP 484- *AND* 585-compliant callable type hints guarantee
# this tuple to contain at least one child type hint. Ergo, we avoid
# validating that constraint here: e.g.,
# >>> from typing import Callable
# >>> Callable[()]
# TypeError: Callable must be used as Callable[[arg, ...], result].
# >>> from collections.abc import Callable
# >>> Callable[()]
# TypeError: Callable must be used as Callable[[arg, ...], result].
hint_args = get_hint_pep_args(hint)
# Number of parameter type hints flattened into this tuple, calculated by
# excluding the trailing return type hint also flattened into this tuple.
#
# Note that by the above constraint, this number is guaranteed to be
# non-negative: e.g.,
# >>> hint_args_len >= 0
# True
hint_params_len = len(hint_args) - 1
# If this callable type hint was subscripted by *NO* parameter type hints,
# return the empty tuple for efficiency.
if hint_params_len == 0:
return ()
# Else, this callable type hint was subscripted by one or more parameter
# type hints.
#
# If this callable type hint was subscripted by two or more parameter type
# hints, this callable type hint *CANNOT* have been subscripted by a single
# "special" parameter type hint (e.g., ellipsis, parameter specification).
# By elimination, the only remaining category of parameter type hint is a
# nested list of two or more parameter type hints. In this case, return the
# tuple slice containing the parameter type hints omitting the trailing
# return type hint.
elif hint_params_len >= 2:
return hint_args[:-1]
# Else, this callable type hint was subscripted by exactly one parameter
# type hint... which could be either a nested list of one or more parameter
# type hints *OR* a "special" parameter type hint. To differentiate the
# former from the latter, we explicitly detect all possible instances of the
# latter and only fallback to the former after exhausting the latter.
# Empty tuple singleton. Yes, we know exactly what you're thinking: "Why
# would anyone do this, @leycec? Why not just directly access the empty
# tuple singleton as ()?" Because Python insanely requires us to do this
# under Python >= 3.8 to detect empty tuples:
# $ python3.7
# >>> () is ()
# True # <-- yes, this is good
#
# $ python3.8
# >>> () is ()
# SyntaxWarning: "is" with a literal. Did you mean "=="? # <-- WUT
# >>> _TUPLE_EMPTY = ()
# >>> _TUPLE_EMPTY is _TUPLE_EMPTY
# True # <-- *FACEPALM*
#
# Note there's no point in globalizing this. Doing so would needlessly
# incur a globals lookup cost while saving no space or time.
_TUPLE_EMPTY = ()
# Single parameter type hint subscripting this callable type hint.
hint_param = hint_args[0]
# If this parameter type hint is either...
#
# Note that we intentionally avoid attempting to efficiently test this
# parameter type hint against a set (e.g., "hint_param in {..., ()}"). This
# parameter type hint is *NOT* guaranteed to be hashable and thus testable
# against a hash-based collection.
if (
# An ellipsis, return an ellipsis.
hint_param is ... or
# The empty tuple, reduce this unlikely (albeit possible) edge case
# to the empty tuple returned for the more common case of a callable
# type hint subscripted by an empty list. That is, reduce these two
# cases to the same empty tuple for simplicity: e.g.,
# >>> Callable[[], bool].__args__
# (bool,) # <------ this is good
# >>> Callable[[()], bool].__args__
# ((), bool,) # <-- this is bad, so pretend this never happens
hint_param is _TUPLE_EMPTY
):
return hint_param
# Else, this parameter type hint is neither the empty tuple *NOR* an
# ellipsis.
# Sign uniquely identifying this parameter type hint if any *OR* "None".
hint_param_sign = get_hint_pep_sign_or_none(hint_param)
# If this parameter type hint is a PEP-compliant parameter type (i.e.,
# uniquely identifiable by a sign), return this hint as is.
#
# Note that:
# * This requires callers to handle all possible categories of
# PEP-compliant parameter type hints -- including both
# "typing.ParamSpec[...]" and "typing.Concatenate[...]" parameter type
# hints, presumably by (...somewhat redundantly, but what can you do)
# calling the get_hint_pep_sign_or_none() getter themselves.
# * Both PEP 484- *AND* 585-compliant callable type hints guarantee
# this parameter type hint to be constrained to the subset of
# PEP-compliant parameter type hints. Arbitrary parameter type hints
# are prohibited. Ergo, we avoid validating that constraint here:
# e.g.,
# >>> from typing import Callable, List
# >>> Callable[List[int], bool]
# TypeError: Callable[args, result]: args must be a list. Got
# typing.List[int]
if hint_param_sign in HINT_SIGNS_CALLABLE_PARAMS:
return hint_param
# Else, this parameter type hint is *NOT* a PEP-compliant parameter type
# hint. This hint *CANNOT* be "special" and *MUST* thus be the single
# parameter type hint of a nested list: e.g.,
# >>> Callable[[list[int]], bool].__args__
# (list[int], bool)
# In this case, return the 1-tuple containing exactly this hint.
# print(f'get_hint_pep484585_callable_params({repr(hint)}) == ({repr(hint_param)},)')
# print(f'{repr(hint_param)} sign: {repr(hint_param_sign)}')
return (hint_param,)
def get_hint_pep484585_callable_return(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep484585Exception,
exception_prefix: str = '',
) -> object:
'''
**Return type hint** (i.e., PEP-compliant child type hint typing the return
returned by a passed or returned callable) of the passed
**callable type hint** (i.e., :pep:`484`-compliant ``typing.Callable[...]``
or :pep:`585`-compliant ``collections.abc.Callable[...]`` type hint).
This getter is considerably more trivial than the companion
:func:`get_hint_pep484585_callable_params` getter. Although this getter
exists largely for orthogonality and completeness, callers are advised to
defer to this getter rather than access this return type hint directly.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Callable type hint to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep484585Exception`.
exception_prefix : str, optional
Human-readable substring prefixing the representation of this object in
the exception message. Defaults to the empty string.
Returns
----------
object
Last argument originally subscripting this hint.
Raises
----------
:exc:`exception_cls`
If this hint is *not* a callable type hint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_args
# If this hint is *NOT* a callable type hint, raise an exception.
_die_unless_hint_pep484585_callable(hint)
# Else, this hint is a callable type hint.
# Flattened tuple of the one or more child type hints subscripting this
# callable type hint. See get_hint_pep484585_callable_params() for details.
hint_args = get_hint_pep_args(hint)
# Return the last object subscripting this hint.
#
# Note that both the PEP 484-compliant "typing.Callable" factory *AND* the
# PEP 585-compliant "collections.abc.Callable" factory guarantee this object
# to exist. Ergo, we intentionally avoid repeating any validation here:
# $ python3.10
# >>> from collections.abc import Callable
# >>> Callable[()]
# TypeError: Callable must be used as Callable[[arg, ...], result].
return hint_args[-1]
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`- and :pep:`585`-compliant **argument type hint
utilities** (i.e., callables generically applicable to child type hints
subscripting both :pep:`484`- and :pep:`585`-compliant type hints).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep585Exception
from beartype.typing import Tuple
from beartype._util.text.utiltextlabel import prefix_callable_decorated_pith
from collections.abc import Callable
# ....................{ GETTERS }....................
def get_hint_pep484585_args_1(hint: object, exception_prefix: str) -> object:
'''
Argument subscripting the passed :pep:`484`- or :pep:`585`-compliant
**single-argument type hint** (i.e., hint semantically subscriptable
(indexable) by exactly one argument).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Caveats
----------
**This higher-level getter should always be called in lieu of directly
accessing the low-level** ``__args__`` **dunder attribute,** which is
typically *not* validated at runtime and thus should *not* be assumed to be
sane. Although the :mod:`typing` module usually validates the arguments
subscripting :pep:`484`-compliant type hints and thus the ``__args__``
**dunder attribute at hint instantiation time, C-based CPython internals
fail to similarly validate the arguments subscripting :pep:`585`-compliant
type hints at any time:
.. code-block:: python
>>> import typing
>>> typing.Type[str, bool]
TypeError: Too many parameters for typing.Type; actual 2, expected 1
>>> type[str, bool]
type[str, bool] # <-- when everything is okay, nothing is okay
Parameters
----------
hint : Any
PEP-compliant type hint to be inspected.
exception_prefix : str
Human-readable label prefixing the representation of this object in the
exception message.
Returns
----------
object
Single argument subscripting this hint.
Raises
----------
BeartypeDecorHintPep585Exception
If this hint is subscripted by either:
* *No* arguments.
* Two or more arguments.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_args
# Tuple of all arguments subscripting this hint.
hint_args = get_hint_pep_args(hint)
# If this hint is *NOT* subscripted by one argument, raise an exception.
if len(hint_args) != 1:
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
raise BeartypeDecorHintPep585Exception(
f'{exception_prefix}PEP 585 type hint {repr(hint)} '
f'not subscripted (indexed) by one argument (i.e., '
f'subscripted by {len(hint_args)} != 1 arguments).'
)
# Else, this hint is subscripted by one argument.
# Return this argument as is.
return hint_args[0]
def get_hint_pep484585_args_3(
hint: object, exception_prefix: str) -> Tuple[object, object, object]:
'''
3-tuple of the three arguments subscripting the passed :pep:`484`- or
:pep:`585`-compliant **three-argument type hint** (i.e., hint semantically
subscriptable (indexable) by exactly three arguments).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : Any
PEP-compliant type hint to be inspected.
exception_prefix : str
Human-readable label prefixing the representation of this object in the
exception message.
Returns
----------
Tuple[object, object, object]
3-tuple of the three arguments subscripting this hint.
Raises
----------
BeartypeDecorHintPep585Exception
If this hint is subscripted by either:
* *No* arguments.
* One or two arguments.
* Four or more arguments.
See Also
----------
:func:`get_hint_pep484585_args_1`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpepget import get_hint_pep_args
# Tuple of all arguments subscripting this hint.
hint_args = get_hint_pep_args(hint)
# If this hint is *NOT* subscripted by three arguments, raise an exception.
if len(hint_args) != 3:
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
raise BeartypeDecorHintPep585Exception(
f'{exception_prefix}PEP 585 type hint {repr(hint)} '
f'not subscripted (indexed) by three arguments (i.e., '
f'subscripted by {len(hint_args)} != 3 arguments).'
)
# Else, this hint is subscripted by one argument.
# Return this tuple of arguments as is.
return hint_args # type: ignore[return-value]
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`- and :pep:`585`-compliant **forward reference type hint
utilities** (i.e., callables generically applicable to both :pep:`484`- and
:pep:`585`-compliant forward reference type hints).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintForwardRefException
from beartype.typing import Union
from beartype._data.datatyping import TypeException
from beartype._util.cls.utilclstest import die_unless_type
from beartype._util.hint.pep.proposal.pep484.utilpep484ref import (
HINT_PEP484_FORWARDREF_TYPE,
get_hint_pep484_forwardref_type_basename,
is_hint_pep484_forwardref,
)
from beartype._util.mod.utilmodget import get_object_module_name
from beartype._util.mod.utilmodimport import import_module_attr
# ....................{ HINTS }....................
HINT_PEP484585_FORWARDREF_TYPES = (str, HINT_PEP484_FORWARDREF_TYPE)
'''
Tuple union of all :pep:`484`- or :pep:`585`-compliant **forward reference
types** (i.e., classes of all forward reference objects).
Specifically, this union contains:
* :class:`str`, the class of all :pep:`585`-compliant forward reference objects
implicitly preserved by all :pep:`585`-compliant type hint factories when
subscripted by a string.
* :class:`HINT_PEP484_FORWARDREF_TYPE`, the class of all :pep:`484`-compliant
forward reference objects implicitly created by all :mod:`typing` type hint
factories when subscripted by a string.
While :pep:`585`-compliant type hint factories preserve string-based forward
references as is, :mod:`typing` type hint factories coerce string-based forward
references into higher-level objects encapsulating those strings. The latter
approach is the demonstrably wrong approach, because encapsulating strings only
harms space and time complexity at runtime with *no* concomitant benefits.
'''
HINT_PEP484585_FORWARDREF_UNION = Union[str, HINT_PEP484_FORWARDREF_TYPE]
'''
Union of all :pep:`484`- or :pep:`585`-compliant **forward reference types**
(i.e., classes of all forward reference objects).
See Also
----------
:data`HINT_PEP484585_FORWARDREF_TYPES`
Further details.
'''
# ....................{ VALIDATORS }....................
def die_unless_hint_pep484585_forwardref(
# Mandatory parameters.
hint: object,
# Optional parameters.
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is either a :pep:`484`- or
:pep:`585`-compliant **forward reference type hint** (i.e., object
referring to a user-defined class that typically has yet to be defined).
Equivalently, this validator raises an exception if this object is neither:
* A string whose value is the syntactically valid name of a class.
* An instance of the :class:`typing.ForwardRef` class. The :mod:`typing`
module implicitly replaces all strings subscripting :mod:`typing` objects
(e.g., the ``MuhType`` in ``List['MuhType']``) with
:class:`typing.ForwardRef` instances containing those strings as instance
variables, for nebulous reasons that make little justifiable sense but
what you gonna do 'cause this is 2020. *Fight me.*
Parameters
----------
hint : object
Object to be validated.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintForwardRefException
If this object is *not* a forward reference type hint.
'''
# If this object is *NOT* a forward reference type hint, raise an exception.
if not isinstance(hint, HINT_PEP484585_FORWARDREF_TYPES):
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
raise BeartypeDecorHintForwardRefException(
f'{exception_prefix}type hint {repr(hint)} not forward reference '
f'(i.e., neither string nor "typing.ForwardRef" instance).'
)
# Else, this object is a forward reference type hint.
# ....................{ GETTERS ~ kind : forwardref }....................
#FIXME: Unit test against nested classes.
#FIXME: Validate that this forward reference string is *NOT* the empty string.
#FIXME: Validate that this forward reference string is a syntactically valid
#"."-delimited concatenation of Python identifiers. We already have logic
#performing that validation somewhere, so let's reuse that here, please.
#Right. So, we already have an is_identifier() tester; now, we just need to
#define a new die_unless_identifier() validator.
def get_hint_pep484585_forwardref_classname(
hint: HINT_PEP484585_FORWARDREF_UNION) -> str:
'''
Possibly unqualified classname referred to by the passed :pep:`484`- or
:pep:`585`-compliant **forward reference type hint** (i.e., object
indirectly referring to a user-defined class that typically has yet to be
defined).
Specifically, this function returns:
* If this hint is a :pep:`484`-compliant forward reference (i.e., instance
of the :class:`typing.ForwardRef` class), the typically unqualified
classname referred to by that reference. Although :pep:`484` only
explicitly supports unqualified classnames as forward references, the
:class:`typing.ForwardRef` class imposes *no* runtime constraints and
thus implicitly supports both qualified and unqualified classnames.
* If this hint is a :pep:`585`-compliant forward reference (i.e., string),
this string as is referring to a possibly unqualified classname. Both
:pep:`585` and :mod:`beartype` itself impose *no* runtime constraints and
thus explicitly support both qualified and unqualified classnames.
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Forward reference to be inspected.
Returns
----------
str
Possibly unqualified classname referred to by this forward reference.
Raises
----------
BeartypeDecorHintForwardRefException
If this forward reference is *not* actually a forward reference.
See Also
----------
:func:`get_hint_pep484585_forwardref_classname_relative_to_object`
Getter returning fully-qualified forward reference classnames.
'''
# If this is *NOT* a forward reference type hint, raise an exception.
die_unless_hint_pep484585_forwardref(hint)
# Return either...
return (
# If this hint is a PEP 484-compliant forward reference, the typically
# unqualified classname referred to by this reference.
get_hint_pep484_forwardref_type_basename(hint) # type: ignore[return-value]
if is_hint_pep484_forwardref(hint) else
# Else, this hint is a string. In this case, this string as is.
hint
)
#FIXME: Unit test against nested classes.
def get_hint_pep484585_forwardref_classname_relative_to_object(
hint: HINT_PEP484585_FORWARDREF_UNION, obj: object) -> str:
'''
Fully-qualified classname referred to by the passed **forward reference
type hint** (i.e., object indirectly referring to a user-defined class that
typically has yet to be defined) canonicalized if this hint is unqualified
relative to the module declaring the passed object (e.g., callable, class).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Forward reference to be canonicalized.
obj : object
Object to canonicalize the classname referred to by this forward
reference if that classname is unqualified (i.e., relative).
Returns
----------
str
Fully-qualified classname referred to by this forward reference
relative to this callable.
Raises
----------
BeartypeDecorHintForwardRefException
If this forward reference is *not* actually a forward reference.
_BeartypeUtilModuleException
If ``module_obj`` does *not* define the ``__module__`` dunder instance
variable.
See Also
----------
:func:`get_hint_pep484585_forwardref_classname`
Getter returning possibly unqualified forward reference classnames.
'''
# Possibly unqualified classname referred to by this forward reference.
forwardref_classname = get_hint_pep484585_forwardref_classname(hint)
# Return either...
return (
# If this classname contains one or more "." characters and is thus
# already hopefully fully-qualified, this classname as is;
forwardref_classname
if '.' in forwardref_classname else
# Else, the "."-delimited concatenation of the fully-qualified name of
# the module declaring this class with this unqualified classname.
f'{get_object_module_name(obj)}.{forwardref_classname}'
)
# ....................{ IMPORTERS }....................
#FIXME: Unit test us up, please.
def import_pep484585_forwardref_type_relative_to_object(
# Mandatory parameters.
hint: HINT_PEP484585_FORWARDREF_UNION,
obj: object,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintForwardRefException,
exception_prefix: str = '',
) -> type:
'''
Class referred to by the passed :pep:`484` or :pep:`585`-compliant
**forward reference type hint** (i.e., object indirectly referring to a
user-defined class that typically has yet to be defined) canonicalized if
this hint is unqualified relative to the module declaring the passed object
(e.g., callable, class).
This getter is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the passed object is typically a
:func:`beartype.beartype`-decorated callable passed exactly once to this
function.
Parameters
----------
hint : HINT_PEP484585_FORWARDREF_UNION
Forward reference type hint to be resolved.
obj : object
Object to canonicalize the classname referred to by this forward
reference if that classname is unqualified (i.e., relative).
exception_cls : Type[Exception]
Type of exception to be raised by this function. Defaults to
:class:`BeartypeDecorHintForwardRefException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Returns
----------
type
Class referred to by this forward reference.
Raises
----------
:exc:`exception_cls`
If the object referred to by this forward reference is either undefined
*or* is defined but is not a class.
'''
# Human-readable label prefixing exception messages raised below.
EXCEPTION_PREFIX = f'{exception_prefix}{repr(hint)} referenced class '
# Fully-qualified classname referred to by this forward reference relative
# to this object.
hint_forwardref_classname = (
get_hint_pep484585_forwardref_classname_relative_to_object(
hint=hint, obj=obj))
# Object dynamically imported from this classname.
hint_forwardref_type = import_module_attr(
module_attr_name=hint_forwardref_classname,
exception_cls=exception_cls,
exception_prefix=EXCEPTION_PREFIX,
)
# If this object is *NOT* a class, raise an exception.
die_unless_type(
cls=hint_forwardref_type,
exception_cls=exception_cls,
exception_prefix=EXCEPTION_PREFIX,
)
# Else, this object is a class.
# Return this class.
return hint_forwardref_type
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`- and :pep:`585`-compliant **decorated callable type
hint utilities** (i.e., callables generically applicable to both :pep:`484`-
and :pep:`585`-compliant type hints directly annotating the user-defined
callable currently being decorated by :func:`beartype.beartype`).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep484585Exception
from beartype._data.hint.pep.sign.datapepsigns import HintSignCoroutine
from beartype._data.hint.pep.sign.datapepsignset import (
HINT_SIGNS_RETURN_GENERATOR_ASYNC,
HINT_SIGNS_RETURN_GENERATOR_SYNC,
)
from beartype._util.func.utilfunctest import (
is_func_coro,
is_func_async_generator,
is_func_sync_generator,
)
from beartype._util.hint.pep.proposal.pep484585.utilpep484585arg import (
get_hint_pep484585_args_3)
from beartype._util.hint.pep.utilpepget import get_hint_pep_sign_or_none
from beartype._util.text.utiltextlabel import (
prefix_callable_decorated_return)
from beartype._data.datatyping import TypeException
from collections.abc import Callable
# ....................{ REDUCERS ~ return }....................
def reduce_hint_pep484585_func_return(
func: Callable, exception_prefix: str) -> object:
'''
Reduce the possibly PEP-noncompliant type hint annotating the return of the
passed callable if any to a simpler form to generate optimally efficient
type-checking by the :func:`beartype.beartype` decorator.
Parameters
----------
func : Callable
Currently decorated callable to be inspected.
exception_prefix : str
Human-readable label prefixing the representation of this object in the
exception message.
Returns
----------
object
Single argument subscripting this hint.
Raises
----------
BeartypeDecorHintPep484585Exception
If this callable is either:
* A synchronous generator *not* annotated by a type hint identified by
a sign in the :data:`HINT_SIGNS_RETURN_GENERATOR_SYNC` set.
* An asynchronous generator *not* annotated by a type hint identified
by a sign in the :data:`HINT_SIGNS_RETURN_GENERATOR_ASYNC` set.
'''
# Type hint annotating this callable's return, which the caller has already
# explicitly guaranteed to exist.
hint = func.__annotations__['return']
# Sign uniquely identifying this hint if any *OR* "None" otherwise (e.g.,
# if this hint is an isinstanceable class).
hint_sign = get_hint_pep_sign_or_none(hint)
# If the decorated callable is a coroutine...
if is_func_coro(func):
# If this hint is "Coroutine[...]"...
if hint_sign is HintSignCoroutine:
# 3-tuple of all child type hints subscripting this hint if
# subscripted by three such hints *OR* raise an exception.
hint_args = get_hint_pep484585_args_3(
hint=hint, exception_prefix=exception_prefix)
# Reduce this hint to the last child type hint subscripting this
# hint, whose value is the return type hint for this coroutine.
#
# All other child type hints are currently ignorable, as the *ONLY*
# means of validating objects sent to and yielded from a coroutine
# is to wrap that coroutine with a @beartype-specific wrapper
# object, which we are currently unwilling to do. Why? Because
# safety and efficiency. Coroutines receiving and yielding multiple
# objects are effectively iterators; type-checking all iterator
# values is an O(n) rather than O(1) operation, violating the core
# @beartype guarantee.
#
# Likewise, the parent "Coroutine" type is *ALWAYS* ignorable.
# Since Python itself implicitly guarantees *ALL* coroutines to
# return coroutine objects, validating that constraint is silly.
hint = hint_args[-1]
# Else, this hint is *NOT* "Coroutine[...]". In this case, silently
# accept this hint as if this hint had instead been expanded to the
# semantically equivalent PEP 484- or 585-compliant coroutine hint
# "Coroutine[None, None, {hint}]".
# Else, the decorated callable is *NOT* a coroutine.
#
# If the decorated callable is an asynchronous generator...
elif is_func_async_generator(func):
#FIXME: Unit test this up, please!
# If this hint is semantically invalid as the return annotation of this
# callable, raise an exception.
if hint_sign not in HINT_SIGNS_RETURN_GENERATOR_ASYNC:
_die_of_hint_return_invalid(
func=func,
exception_suffix=(
' (i.e., expected either '
'collections.abc.AsyncGenerator[YieldType, SendType], '
'collections.abc.AsyncIterable[YieldType], '
'collections.abc.AsyncIterator[YieldType], '
'typing.AsyncGenerator[YieldType, SendType], '
'typing.AsyncIterable[YieldType], or '
'typing.AsyncIterator[YieldType] '
'type hint).'
),
)
# Else, this hint is valid as the return annotation of this callable.
# Else, the decorated callable is *NOT* an asynchronous generator.
#
# If the decorated callable is a synchronous generator...
elif is_func_sync_generator(func):
#FIXME: Unit test this up, please!
# If this hint is semantically invalid as the return annotation of this
# callable, raise an exception.
if hint_sign not in HINT_SIGNS_RETURN_GENERATOR_SYNC:
_die_of_hint_return_invalid(
func=func,
exception_suffix=(
' (i.e., expected either '
'collections.abc.Generator[YieldType, SendType, ReturnType], '
'collections.abc.Iterable[YieldType], '
'collections.abc.Iterator[YieldType], '
'typing.Generator[YieldType, SendType, ReturnType], '
'typing.Iterable[YieldType], or '
'typing.Iterator[YieldType] '
'type hint).'
),
)
# Else, this hint is valid as the return annotation of this callable.
# Else, the decorated callable is none of the kinds detected above.
# Return this possibly reduced hint.
return hint
# ....................{ PRIVATE ~ validators }....................
def _die_of_hint_return_invalid(
# Mandatory parameters.
func: Callable,
exception_suffix: str,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep484585Exception,
) -> str:
'''
Raise an exception of the passed type with a message suffixed by the passed
substring explaining why the possibly PEP-noncompliant type hint annotating
the return of the passed decorated callable is contextually invalid.
Parameters
----------
func : Callable
Decorated callable whose return is annotated by an invalid type hint.
exception_cls : TypeException
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep484585Exception`.
exception_suffix : str
Substring suffixing the exception message to be raised.
Raises
----------
:exc:`exception_cls`
Exception explaining the invalidity of this return type hint.
'''
assert callable(func), f'{repr(func)} not callable.'
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not class.'
assert isinstance(exception_suffix, str), (
f'{repr(exception_suffix)} not string.')
# Type hint annotating this callable's return, which the caller has already
# explicitly guaranteed to exist.
hint = func.__annotations__['return']
# Raise an exception of this type with a message suffixed by this suffix.
raise exception_cls(
f'{prefix_callable_decorated_return(func)}type hint '
f'{repr(hint)} contextually invalid{exception_suffix}.'
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`- and :pep:`585`-compliant **dual type hint utilities**
(i.e., callables generically applicable to both :pep:`484`- and
:pep:`585`-compliant type hints).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._util.hint.pep.proposal.pep484.utilpep484 import (
HINT_PEP484_TUPLE_EMPTY)
from beartype._util.hint.pep.proposal.utilpep585 import (
HINT_PEP585_TUPLE_EMPTY)
# ....................{ TESTERS ~ kind : tuple }....................
def is_hint_pep484585_tuple_empty(hint: object) -> bool:
'''
``True`` only if the passed object is either a :pep:`484`- or
:pep:`585`-compliant **empty fixed-length tuple type hint** (i.e., hint
constraining objects to be the empty tuple).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as this tester is only called under
fairly uncommon edge cases.
Motivation
----------
Since type variables are not themselves types but rather placeholders
dynamically replaced with types by type checkers according to various
arcane heuristics, both type variables and types parametrized by type
variables warrant special-purpose handling.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is an empty fixed-length tuple hint.
'''
# Return true only if this hint resembles either the PEP 484- or
# 585-compliant fixed-length empty tuple type hint. Since there only exist
# two such hints *AND* comparison against these hints is mostly fast, this
# test is efficient in the general case.
#
# Note that this test may also be inefficiently performed by explicitly
# obtaining this hint's sign and then subjecting this hint to specific
# tests conditionally depending on which sign and thus PEP this hint
# complies with: e.g.,
# # Return true only if this hint is either...
# return true (
# # A PEP 585-compliant "tuple"-based hint subscripted by no
# # child hints *OR*...
# (
# hint.__origin__ is tuple and
# hint_childs_len == 0
# ) or
# # A PEP 484-compliant "typing.Tuple"-based hint subscripted
# # by exactly one child hint *AND* this child hint is the
# # empty tuple,..
# (
# hint.__origin__ is Tuple and
# hint_childs_len == 1 and
# hint_childs[0] == ()
# )
# )
return (
hint == HINT_PEP585_TUPLE_EMPTY or
hint == HINT_PEP484_TUPLE_EMPTY
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **PEP-noncompliant NumPy type hint** (i.e., type hint defined by
the third-party :mod:`numpy` package) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: The top-level of this module should avoid importing from third-party
# optional libraries, both because those libraries cannot be guaranteed to be
# either installed or importable here *AND* because those imports are likely to
# be computationally expensive, particularly for imports transitively importing
# C extensions (e.g., anything from NumPy or SciPy).
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
from beartype.roar import (
BeartypeDecorHintNonpepNumpyException,
BeartypeDecorHintNonpepNumpyWarning,
)
from beartype.typing import Any, FrozenSet
from beartype._data.hint.pep.sign.datapepsigns import HintSignNumpyArray
from beartype._util.cache.utilcachecall import callable_cached
from beartype._util.mod.lib.utiltyping import import_typing_attr_or_none
from beartype._util.hint.pep.utilpepget import (
get_hint_pep_args,
get_hint_pep_sign_or_none,
)
from beartype._util.utilobject import is_object_hashable
from warnings import warn
# ....................{ REDUCERS }....................
#FIXME: Ideally, this reducer would be memoized. Sadly, the
#"numpy.typing.NDArray" type hint itself fails to memoize. Memoization here
#would just consume all available memory. *sigh*
#The solution is the exact same as for PEP 585 type hints, which similarly fail
#to memoize: forcefully coerce "numpy.typing.NDArray" type hints that have the
#same repr() into the same previously cached "numpy.typing.NDArray" type hint.
#This is particularly vital here, as the process of manually reducing each
#identical "numpy.typing.NDArray" type hint to the same underlying beartype
#validator consumes dramatically more *TIME* than a caching solution.
# @callable_cached
def reduce_hint_numpy_ndarray(
# Mandatory parameters.
hint: Any,
# Optional parameters.
exception_prefix: str = '',
) -> Any:
'''
Reduce the passed **PEP-noncompliant typed NumPy array** (i.e.,
subscription of the third-party :attr:`numpy.typing.NDArray` type hint
factory) to the equivalent beartype validator validating arbitrary objects
be instances of that array type -- which has the substantial merit of
already being well-supported, well-tested, and well-known to generate
optimally efficient type-checking by the :func:`beartype.beartype`
decorator.
Technically, beartype could instead explicitly handle typed NumPy arrays
throughout the codebase. Of course, doing so would yield *no* tangible
benefits while imposing a considerable maintenance burden.
This reducer is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
PEP-noncompliant typed NumPy array to return the data type of.
exception_prefix : Optional[str]
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintNonpepNumpyException
If either:
* The active Python interpreter targets Python < 3.9 and either:
* The third-party :mod:`typing_extensions` module is unimportable.
* The third-party :mod:`typing_extensions` module is importable but
sufficiently old that it fails to declare the
:attr:`typing_extensions.Annotated` attribute.
* This hint is *not* a typed NumPy array.
* This hint is a typed NumPy array but either:
* *Not* subscripted by exactly two arguments.
* Subscripted by exactly two arguments but whose second argument is
neither:
* A **NumPy data type** (i.e., :class:`numpy.dtype` instance).
* An object coercible into a NumPy data type by passing to the
:meth:`numpy.dtype.__init__` method.
'''
# ..................{ SIGN }..................
# Sign uniquely identifying this hint if this hint is identifiable *OR*
# "None" otherwise.
hint_sign = get_hint_pep_sign_or_none(hint)
# If this hint is *NOT* a typed NumPy array, raise an exception.
if hint_sign is not HintSignNumpyArray:
raise BeartypeDecorHintNonpepNumpyException(
f'{exception_prefix}type hint {repr(hint)} not typed NumPy array '
f'(i.e., subscription of the '
f'"numpy.typing.NDArray" type hint factory).'
)
# Else, this hint is a typed NumPy array.
# ..................{ IMPORTS }..................
# Defer heavyweight imports until *AFTER* validating this hint to be a
# typed NumPy array. Why? Because these imports are *ONLY* safely
# importable if this hint is a typed NumPy array. Why? Because
# instantiating this hint required these imports. QED.
#
# Note that third-party packages should typically *ONLY* be imported via
# utility functions raising human-readable exceptions when those packages
# are either uninstalled or unimportable. In this case, however, NumPy will
# almost *ALWAYS* be importable. Why? Because this hint was externally
# instantiated by the user by first importing the "numpy.typing.NDArray"
# attribute passed to this getter.
from beartype.vale import IsAttr, IsEqual, IsSubclass
from numpy import dtype, ndarray # pyright: ignore[reportMissingImports]
from numpy.typing import NDArray # type: ignore[attr-defined]
#FIXME: Consider submitting an upstream issue about this. We don't
#particularly feel like arguing tonight, because that's a lonely hill.
# If this hint is the unsubscripted "NDArray" type hint, this hint
# permissively matches *ALL* NumPy arrays rather than strictly matching
# *ONLY* appropriately typed NumPy arrays. In this case, reduce this hint
# to the untyped "numpy.ndarray" class.
#
# Note the similar test matching the subscripted "NDArray[Any]" hint below.
# Moreover, note this test *CANNOT* be performed elsewhere (e.g., by
# adding "HintSignNumpyArray" to the "HINT_SIGNS_ORIGIN_ISINSTANCEABLE"
# frozen set of all signs whose unsubscripted type hint factories are
# shallowly type-checkable). Why? Because the "NDArray" type hint factory
# violates type hinting standards. Specifically, this factory implicitly
# subscripts *AND* parametrizes itself with the "numpy.ScalarType" type
# variable bounded above by the "numpy.generic" abstract base class for
# NumPy scalars.
#
# We have *NO* idea why NumPy does this. This implicit behaviour is
# semantically lossy rather than lossless and thus arguably constitutes an
# upstream bug. Why? Because this behaviour violates:
# * The NumPy API. The "NDArray" type hint factory is subscriptable by more
# than merely NumPy scalar types. Ergo, "NDArray" is semantically
# inaccurate!
# * PEP 484, which explicitly standardizes an equivalence between
# unsubscripted type hint factories and the same factories subscripted by
# the "typing.Any" singleton. However, "NDArray" is *MUCH* semantically
# narrower than and thus *NOT* equivalent to "NDArray[Any]"!
#
# Of course, upstream is unlikely to see it that way. We're *NOT* dying on
# an argumentative hill about semantics. Upstream makes the rules. Do it.
if hint is NDArray:
return ndarray
# ..................{ CONSTANTS }..................
# Frozen set of all NumPy scalar data type abstract base classes (ABCs).
NUMPY_DTYPE_TYPE_ABCS = _get_numpy_dtype_type_abcs()
# ..................{ ARGS }..................
# Objects subscripting this hint if any *OR* the empty tuple otherwise.
hint_args = get_hint_pep_args(hint)
# If this hint was *NOT* subscripted by exactly two arguments, this hint is
# malformed as a typed NumPy array. In this case, raise an exception.
if len(hint_args) != 2:
raise BeartypeDecorHintNonpepNumpyException(
f'{exception_prefix}typed NumPy array {repr(hint)} '
f'not subscripted by exactly two arguments.'
)
# Else, this hint was subscripted by exactly two arguments.
# Data type subhint subscripting this hint. Yes, the "numpy.typing.NDArray"
# type hint bizarrely encapsulates its data type argument into a private
# "numpy._DTypeMeta" type subhint. Why? We have absolutely no idea, but we
# have no say in the matter. NumPy, you're on notice for stupidity.
hint_dtype_subhint = hint_args[1]
# Objects subscripting this subhint if any *OR* the empty tuple otherwise.
hint_dtype_subhint_args = get_hint_pep_args(hint_dtype_subhint)
# If this hint was *NOT* subscripted by exactly one argument, this subhint
# is malformed as a data type subhint. In this case, raise an exception.
if len(hint_dtype_subhint_args) != 1:
raise BeartypeDecorHintNonpepNumpyException(
f'{exception_prefix}typed NumPy array {repr(hint)} '
f'data type subhint {repr(hint_dtype_subhint)} '
f'not subscripted by exactly one argument.'
)
# Else, this subhint was subscripted by exactly one argument.
# Data type-like object subscripting this subhint. Look, just do it.
hint_dtype_like = hint_dtype_subhint_args[0]
# If this dtype-like is "typing.Any", this hint permissively matches *ALL*
# NumPy arrays rather than strictly matching *ONLY* appropriately typed
# NumPy arrays. In this case, reduce this hint to the untyped
# "numpy.ndarray" class.
#
# Note the similar test matching the unsubscripted "NDArray" hint above.
if hint_dtype_like is Any:
return ndarray
# ..................{ REDUCTION }..................
#FIXME: Safely replace this with "from typing import Annotated" after
#dropping Python 3.8 support.
# "typing.Annotated" type hint factory safely imported from whichever of
# the "typing" or "typing_extensions" modules declares this attribute if
# one or more do *OR* "None" otherwise (i.e., if none do).
typing_annotated = import_typing_attr_or_none('Annotated')
# If this factory is unimportable, this typed NumPy array *CANNOT* be
# reduced to a subscription of this factory by one or more semantically
# equivalent beartype validators. In this case...
if typing_annotated is None:
# Emit a non-fatal warning informing the user of this issue.
warn(
(
f'{exception_prefix}typed NumPy array {repr(hint)} '
f'reduced to untyped NumPy array {repr(ndarray)} '
f'(i.e., as neither "typing.Annotated" nor '
f'"typing_extensions.Annotated" importable).'
),
BeartypeDecorHintNonpepNumpyWarning,
)
# Reduce this hint to the untyped "ndarray" class with apologies.
return ndarray
# Else, this factory is importable.
# Equivalent nested beartype validator reduced from this hint.
hint_validator = None # type: ignore[assignment]
# If...
if (
# This dtype-like is hashable *AND*...
is_object_hashable(hint_dtype_like) and
# This dtype-like is a scalar data type abstract base class (ABC)...
hint_dtype_like in NUMPY_DTYPE_TYPE_ABCS
):
# Then avoid attempting to coerce this possibly non-dtype into a proper
# dtype. Although NumPy previously silently coerced these ABCs into
# dtypes (e.g., from "numpy.floating" to "numpy.float64"), recent
# versions of NumPy now emit non-fatal deprecation warnings on doing so
# and will presumably raise fatal exceptions in the near future:
# >>> import numpy as np
# >>> np.dtype(np.floating)
# DeprecationWarning: Converting `np.inexact` or `np.floating` to a
# dtype is deprecated. The current result is `float64` which is not
# strictly correct.
# We instead follow mypy's lead presumably defined somewhere in the
# incredibly complex innards of NumPy's mypy plugin -- which we
# admittedly failed to grep despite ~~wasting~~ "investing" several
# hours in doing so. Specifically, mypy treats subscriptions of the
# "numpy.typing.NDArray" type hint factory by one of these ABCs (rather
# than either a scalar or proper dtype) as a type inheritance (rather
# than object equality) relation. Since this is sensible, we do too.
# Equivalent nested beartype validator reduced from this hint.
hint_validator = (
IsAttr['dtype', IsAttr['type', IsSubclass[hint_dtype_like]]])
# Else, this dtype-like is either unhashable *OR* not such an ABC.
else:
# Attempt to coerce this possibly non-dtype into a proper dtype. Note
# that the dtype.__init__() constructor efficiently maps non-dtype
# scalar types (e.g., "numpy.float64") to corresponding cached dtypes:
# >>> import numpy
# >>> i4_dtype = numpy.dtype('>i4')
# >>> numpy.dtype(i4_dtype) is numpy.dtype(i4_dtype)
# True
# >>> numpy.dtype(numpy.float64) is numpy.dtype(numpy.float64)
# True
# Ergo, the call to this constructor here is guaranteed to already
# effectively be memoized.
try:
hint_dtype = dtype(hint_dtype_like)
# If this object is *NOT* coercible into a dtype, raise an exception.
# This is essential. As of NumPy 1.21.0, "numpy.typing.NDArray" fails
# to validate its subscripted argument to actually be a dtype: e.g.,
# >>> from numpy.typing import NDArray
# >>> NDArray['wut']
# numpy.ndarray[typing.Any, numpy.dtype['wut']] # <-- you kidding me?
except Exception as exception:
raise BeartypeDecorHintNonpepNumpyException(
f'{exception_prefix}typed NumPy array {repr(hint)} '
f'data type {repr(hint_dtype_like)} invalid '
f'(i.e., neither data type nor coercible into data type).'
) from exception
# Else, this object is now a proper dtype.
# Equivalent nested beartype validator reduced from this hint.
hint_validator = IsAttr['dtype', IsEqual[hint_dtype]]
# Replace the usually less readable representation of this validator with
# the usually more readable representation of this hint (e.g.,
# "numpy.ndarray[typing.Any, numpy.float64]").
hint_validator.get_repr = repr(hint)
# Return this validator annotating the NumPy array type.
return typing_annotated[ndarray, hint_validator]
# ....................{ PRIVATE ~ getter }....................
#FIXME: File an upstream NumPy issue politely requesting they publicize either:
#* An equivalent container listing these types.
#* Documentation officially listing these types.
@callable_cached
def _get_numpy_dtype_type_abcs() -> FrozenSet[type]:
'''
Frozen set of all **NumPy scalar data type abstract base classes** (i.e.,
superclasses of all concrete NumPy scalar data types (e.g.,
:class:`numpy.int64`, :class:`numpy.float32`)).
This getter is memoized for efficiency. To defer the substantial cost of
importing from NumPy, the frozen set memoized by this getter is
intentionally deferred to call time rather than globalized as a constant.
Caveats
----------
**NumPy currently provides no official container listing these classes.**
Likewise, NumPy documentation provides no official list of these classes.
Ergo, this getter. This has the dim advantage of working but the profound
disadvantage of inviting inevitable discrepancies between the
:mod:`beartype` and :mod:`numpy` codebases. So it goes.
'''
# Defer heavyweight imports.
from numpy import ( # pyright: ignore[reportMissingImports]
character,
complexfloating,
flexible,
floating,
generic,
inexact,
integer,
number,
signedinteger,
unsignedinteger,
)
# Create, return, and cache a frozen set listing these ABCs.
return frozenset((
character,
complexfloating,
flexible,
floating,
generic,
inexact,
integer,
number,
signedinteger,
unsignedinteger,
))
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **PEP-noncompliant type hint** utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: Validate strings to be syntactically valid classnames via a globally
#scoped compiled regular expression. Raising early exceptions at decoration
#time is preferable to raising late exceptions at call time.
#FIXME: Indeed, we now provide such a callable:
# from beartype._util.mod.utilmodget import die_unless_module_attr_name
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintNonpepException
from beartype._util.cache.utilcachecall import callable_cached
from beartype._util.cls.pep.utilpep3119 import (
die_unless_type_isinstanceable,
is_type_or_types_isinstanceable,
)
from beartype._data.datatyping import TypeException
# ....................{ VALIDATORS }....................
#FIXME: Unit test us up, please.
def die_if_hint_nonpep(
# Mandatory parameters.
hint: object,
# Optional parameters.
is_str_valid: bool = True,
exception_cls: TypeException = BeartypeDecorHintNonpepException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception if the passed object is a **PEP-noncompliant type hint**
(i.e., :mod:`beartype`-specific annotation *not* compliant with
annotation-centric PEPs).
This validator is effectively (but technically *not*) memoized. See the
:func:`beartype._util.hint.utilhinttest.die_unless_hint` validator.
Parameters
----------
hint : object
Object to be validated.
is_str_valid : bool, optional
``True`` only if this function permits this object to either be a
string or contain strings. Defaults to ``True``. If this boolean is:
* ``True``, this object is valid only if this object is either a class
or tuple of classes and/or classnames.
* ``False``, this object is valid only if this object is either a class
or tuple of classes.
exception_cls : type[Exception]
Type of the exception to be raised by this function. Defaults to
:class:`BeartypeDecorHintNonpepException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this object is either:
* An **isinstanceable type** (i.e., standard class passable as the
second parameter to the :func:`isinstance` builtin and thus typically
*not* compliant with annotation-centric PEPs).
* A **non-empty tuple** (i.e., semantic union of types) containing one
or more:
* Non-:mod:`typing` types.
* If ``is_str_valid``, **strings** (i.e., forward references
specified as either fully-qualified or unqualified classnames).
'''
# If this object is a PEP-noncompliant type hint, raise an exception.
#
# Note that this memoized call is intentionally passed positional rather
# than keyword parameters to maximize efficiency.
if is_hint_nonpep(hint, is_str_valid):
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not type.')
assert issubclass(exception_cls, Exception), (
f'{repr(exception_cls)} not exception type.')
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} '
f'is PEP-noncompliant (e.g., neither ' +
(
(
'isinstanceable class, forward reference, nor tuple of '
'isinstanceable classes and/or forward references).'
)
if is_str_valid else
'isinstanceable class nor tuple of isinstanceable classes).'
)
)
# Else, this object is *NOT* a PEP-noncompliant type hint.
#FIXME: Unit test this function with respect to non-isinstanceable classes.
def die_unless_hint_nonpep(
# Mandatory parameters.
hint: object,
# Optional parameters.
is_str_valid: bool = True,
exception_cls: TypeException = BeartypeDecorHintNonpepException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is a **PEP-noncompliant type
hint** (i.e., :mod:`beartype`-specific annotation *not* compliant with
annotation-centric PEPs).
This validator is effectively (but technically *not*) memoized. See the
:func:`beartype._util.hint.utilhinttest.die_unless_hint` validator.
Parameters
----------
hint : object
Object to be validated.
is_str_valid : bool, optional
``True`` only if this function permits this object to either be a
string or contain strings. Defaults to ``True``. If this boolean is:
* ``True``, this object is valid only if this object is either a class
or tuple of classes and/or classnames.
* ``False``, this object is valid only if this object is either a class
or tuple of classes.
exception_cls : type[Exception], optional
Type of the exception to be raised by this function. Defaults to
:class:`BeartypeDecorHintNonpepException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this object is neither:
* An **isinstanceable type** (i.e., standard class passable as the
second parameter to the :func:`isinstance` builtin and thus typically
*not* compliant with annotation-centric PEPs).
* A **non-empty tuple** (i.e., semantic union of types) containing one
or more:
* Non-:mod:`typing` types.
* If ``is_str_valid``, **strings** (i.e., forward references
specified as either fully-qualified or unqualified classnames).
'''
# If this object is a PEP-noncompliant type hint, reduce to a noop.
#
# Note that this memoized call is intentionally passed positional rather
# than keyword parameters to maximize efficiency.
if is_hint_nonpep(hint, is_str_valid):
return
# Else, this object is *NOT* a PEP-noncompliant type hint. In this case,
# subsequent logic raises an exception specific to the passed parameters.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# BEGIN: Synchronize changes here with the is_hint_nonpep() tester below.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not type.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# If this object is a class...
if isinstance(hint, type):
# If this class is *NOT* PEP-noncompliant, raise an exception.
die_unless_hint_nonpep_type(
hint=hint,
exception_prefix=exception_prefix,
exception_cls=exception_cls,
)
# Else, this class is isinstanceable. In this case, silently accept
# this class as is.
return
# Else, this object is *NOT* a class.
#
# If this object is a tuple, raise a tuple-specific exception.
elif isinstance(hint, tuple):
die_unless_hint_nonpep_tuple(
hint=hint,
exception_prefix=exception_prefix,
is_str_valid=is_str_valid,
exception_cls=exception_cls,
)
# Else, this object is neither a type nor type tuple.
# Raise a generic exception.
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} either '
f'PEP-noncompliant or currently unsupported by @beartype.'
)
#FIXME: Temporarily preserved in case we want to restore this. *shrug*
# # Else, this object is neither a forward reference, class, nor tuple. Ergo,
# # this object is *NOT* a PEP-noncompliant type hint.
# #
# # If forward references are supported, raise an exception noting that.
# elif is_str_valid:
# raise exception_cls(
# f'{exception_prefix}type hint {repr(hint)} '
# f'neither PEP-compliant nor -noncompliant '
# f'(e.g., neither PEP-compliant, isinstanceable class, forward reference, or '
# f'tuple of isinstanceable classes and forward references).'
# )
# # Else, forward references are unsupported. In this case, raise an
# # exception noting that.
# else:
# raise exception_cls(
# f'{exception_prefix}type hint {repr(hint)} '
# f'neither PEP-compliant nor -noncompliant '
# f'(e.g., isinstanceable class or tuple of isinstanceable classes).'
# )
# ....................{ VALIDATORS ~ kind }....................
#FIXME: Unit test us up.
def die_unless_hint_nonpep_type(
# Mandatory parameters.
hint: type,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintNonpepException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is an **isinstanceable type**
(i.e., standard class passable as the second parameter to the
:func:`isinstance` builtin and thus typically *not* compliant with
annotation-centric PEPs).
This validator is effectively (but technically *not*) memoized. See the
:func:`beartype._util.hint.utilhinttest.die_unless_hint` validator.
Parameters
----------
hint : type
Object to be validated.
exception_cls : Optional[type]
Type of the exception to be raised by this function. Defaults to
:class:`BeartypeDecorHintNonpepException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintPep3119Exception
If this object is *not* an isinstanceable class (i.e., class passable
as the second argument to the :func:`isinstance` builtin).
:exc:`exception_cls`
If this object is a PEP-compliant type hint.
'''
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpeptest import die_if_hint_pep
# If this object is a PEP-compliant type hint, raise an exception.
die_if_hint_pep(
hint=hint,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this object is *NOT* a PEP-noncompliant type hint.
#
# If this object is *NOT* an isinstanceable class, raise an exception. Note
# that this validation is typically slower than the prior validation and
# thus intentionally performed last.
die_unless_type_isinstanceable(
cls=hint,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# If this object is an isinstanceable class.
#FIXME: Unit test this function with respect to tuples containing
#non-isinstanceable classes.
#FIXME: Optimize both this and the related _is_hint_nonpep_tuple() tester
#defined below. The key realization here is that EAFP is *MUCH* faster in this
#specific case than iteration. Why? Because iteration is guaranteed to
#internally raise a stop iteration exception, whereas EAFP only raises an
#exception if this tuple is invalid, in which case efficiency is no longer a
#concern. So, what do we do instead? Simple. We internally refactor:
#* If "is_str_valid" is True, we continue to perform the existing
# implementation of both functions. *shrug*
#* Else, we:
# * Perform a new optimized EAFP-style isinstance() check resembling that
# performed by die_unless_type_isinstanceable().
# * Likewise for _is_hint_nonpep_tuple() vis-a-vis is_type_or_types_isinstanceable().
#Fortunately, tuple unions are now sufficiently rare in the wild (i.e., in
#real-world use cases) that this mild inefficiency probably no longer matters.
#FIXME: Indeed! Now that we have the die_unless_type_or_types_isinstanceable()
#validator, this validator should reduce to efficiently calling
#die_unless_type_or_types_isinstanceable() directly if "is_str_valid" is False.
#die_unless_type_or_types_isinstanceable() performs the desired EAFP-style
#isinstance() check in an optimally efficient manner.
def die_unless_hint_nonpep_tuple(
# Mandatory parameters.
hint: object,
# Optional parameters.
is_str_valid: bool = False,
exception_cls: TypeException = BeartypeDecorHintNonpepException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is a **PEP-noncompliant tuple**
(i.e., :mod:`beartype`-specific tuple of one or more PEP-noncompliant types
*not* compliant with annotation-centric PEPs).
This validator is effectively (but technically *not*) memoized. See the
:func:`beartype._util.hint.utilhinttest.die_unless_hint` validator.
Parameters
----------
hint : object
Object to be validated.
is_str_valid : bool, optional
``True`` only if this function permits this tuple to contain strings.
Defaults to ``False``. If:
* ``True``, this tuple is valid only when containing classes and/or
classnames.
* ``False``, this tuple is valid only when containing classes.
exception_cls : type, optional
Type of the exception to be raised by this function. Defaults to
:class:`BeartypeDecorHintNonpepException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this object is neither:
* A non-:mod:`typing` type (i.e., class *not* defined by the
:mod:`typing` module, whose public classes are used to instantiate
PEP-compliant type hints or objects satisfying such hints that
typically violate standard class semantics and thus require
PEP-specific handling).
* A **non-empty tuple** (i.e., semantic union of types) containing one
or more:
* Non-:mod:`typing` types.
* If ``is_str_valid``, **strings** (i.e., forward references
specified as either fully-qualified or unqualified classnames).
'''
# If this object is a tuple union, reduce to a noop.
#
# Note that this memoized call is intentionally passed positional rather
# than keyword parameters to maximize efficiency.
if _is_hint_nonpep_tuple(hint, is_str_valid):
return
# Else, this object is *NOT* a tuple union. In this case, subsequent logic
# raises an exception specific to the passed parameters.
#
# Note that the prior call has already validated "is_str_valid".
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not type.'
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# BEGIN: Synchronize changes here with the _is_hint_nonpep_tuple() tester.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# If this object is *NOT* a tuple, raise an exception.
if not isinstance(hint, tuple):
raise exception_cls(
f'{exception_prefix}type hint {repr(hint)} not tuple.')
# Else, this object is a tuple.
#
# If this tuple is empty, raise an exception.
elif not hint:
raise exception_cls(f'{exception_prefix}tuple type hint empty.')
# Else, this tuple is non-empty.
# For each item of this tuple...
for hint_item in hint:
# Duplicate the above logic. For negligible efficiency gains (and more
# importantly to avoid exhausting the stack), avoid calling this
# function recursively to do so. *shrug*
# If this item is a class...
if isinstance(hint_item, type):
# If this class is *NOT* isinstanceable, raise an exception.
die_unless_type_isinstanceable(
cls=hint_item,
exception_prefix=exception_prefix,
exception_cls=exception_cls,
)
# Else, this item is *NOT* a class.
#
# If this item is a forward reference...
elif isinstance(hint_item, str):
# If forward references are unsupported, raise an exception.
if not is_str_valid:
raise exception_cls(
f'{exception_prefix}tuple type hint {repr(hint)} '
f'forward reference "{hint_item}" unsupported.'
)
# Else, silently accept this item.
# Else, this item is neither a class nor forward reference. Ergo,
# this item is *NOT* a PEP-noncompliant type hint. In this case,
# raise an exception whose message contextually depends on whether
# forward references are permitted or not.
else:
raise exception_cls(
f'{exception_prefix}tuple type hint {repr(hint)} '
f'item {repr(hint_item)} invalid '
f'{"neither type nor string" if is_str_valid else "not type"}.'
)
# ....................{ TESTERS }....................
def is_hint_nonpep(
# Mandatory parameters.
hint: object,
# Optional parameters.
is_str_valid: bool = False,
) -> bool:
'''
``True`` only if the passed object is a **PEP-noncompliant type hint**
(i.e., :mod:`beartype`-specific annotation *not* compliant with
annotation-centric PEPs).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
is_str_valid : bool, optional
``True`` only if this function permits this object to be a string.
Defaults to ``False``. If this boolean is:
* ``True``, this object is valid only if this object is either a class
or tuple of classes and/or classnames.
* ``False``, this object is valid only if this object is either a class
or tuple of classes.
Returns
----------
bool
``True`` only if this object is either:
* A non-:mod:`typing` type (i.e., class *not* defined by the
:mod:`typing` module, whose public classes are used to instantiate
PEP-compliant type hints or objects satisfying such hints that
typically violate standard class semantics and thus require
PEP-specific handling).
* A **non-empty tuple** (i.e., semantic union of types) containing one
or more:
* Non-:mod:`typing` types.
* If ``is_str_valid``, **strings** (i.e., forward references
specified as either fully-qualified or unqualified classnames).
'''
assert isinstance(is_str_valid, bool), f'{repr(is_str_valid)} not boolean.'
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# BEGIN: Synchronize changes here with die_unless_hint_nonpep() above.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Return true only if either...
return (
# If this object is a class, return true only if this is *NOT* a
# PEP-compliant class, in which case this *MUST* be a PEP-noncompliant
# class by definition.
_is_hint_nonpep_type(hint) if isinstance(hint, type) else
# Else, this object is *NOT* a class.
#
# If this object is a tuple, return true only if this tuple contains
# only one or more caller-permitted forward references and
# PEP-noncompliant classes.
_is_hint_nonpep_tuple(hint, is_str_valid) if isinstance(hint, tuple)
# Else, this object is neither a class nor tuple. Return false, as this
# object *CANNOT* be PEP-noncompliant.
else False
)
# ....................{ TESTERS ~ private }....................
@callable_cached
def _is_hint_nonpep_tuple(
# Mandatory parameters.
hint: object,
# Optional parameters.
is_str_valid: bool = False,
) -> bool:
'''
``True`` only if the passed object is a PEP-noncompliant non-empty tuple of
one or more types.
This tester is memoized for efficiency.
Parameters
----------
hint : object
Object to be inspected.
is_str_valid : bool, optional
``True`` only if this function permits this tuple to contain strings.
Defaults to ``False``. If this boolean is:
* ``True``, this tuple is valid only when containing classes and/or
classnames.
* ``False``, this object is valid only when containing classes.
Returns
----------
bool
``True`` only if this object is a **non-empty tuple** (i.e., semantic
union of types) containing one or more:
* Non-:mod:`typing` types.
* If ``is_str_valid``, **strings** (i.e., forward references
specified as either fully-qualified or unqualified classnames).
'''
assert isinstance(is_str_valid, bool), f'{repr(is_str_valid)} not boolean.'
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# BEGIN: Synchronize changes here with die_unless_hint_nonpep() above.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Return true only if this object is...
return (
# A tuple *AND*...
isinstance(hint, tuple) and
# This tuple is non-empty *AND*...
len(hint) > 0 and
# Each item of this tuple is either a caller-permitted forward
# reference *OR* an isinstanceable class.
all(
is_type_or_types_isinstanceable(hint_item) if isinstance(hint_item, type) else
is_str_valid if isinstance(hint_item, str) else
False
for hint_item in hint
)
)
def _is_hint_nonpep_type(hint: object) -> bool:
'''
``True`` only if the passed object is a PEP-noncompliant type.
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
hint : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a PEP-noncompliant type.
'''
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# BEGIN: Synchronize changes here with die_unless_hint_nonpep() above.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Avoid circular import dependencies.
from beartype._util.hint.pep.utilpeptest import is_hint_pep
# Return true only if this object is isinstanceable and *NOT* a
# PEP-compliant class, in which case this *MUST* be a PEP-noncompliant
# class by definition.
return is_type_or_types_isinstanceable(hint) and not is_hint_pep(hint)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Python interpreter version utilities**.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from sys import version_info
# ....................{ CONSTANTS ~ at least }....................
IS_PYTHON_AT_LEAST_4_0 = version_info >= (4, 0)
'''
``True`` only if the active Python interpreter targets at least Python 4.0.0.
'''
#FIXME: After dropping Python 3.10 support:
#* Refactor all code conditionally testing this global to be unconditional.
#* Remove this global.
#* Remove all decorators resembling:
# @skip_if_python_version_less_than('3.11.0')
IS_PYTHON_AT_LEAST_3_11 = IS_PYTHON_AT_LEAST_4_0 or version_info >= (3, 11)
'''
``True`` only if the active Python interpreter targets at least Python 3.11.0.
'''
#FIXME: After dropping Python 3.9 support:
#* Remove this global.
IS_PYTHON_AT_MOST_3_10 = not IS_PYTHON_AT_LEAST_3_11
'''
``True`` only if the active Python interpreter targets at most Python 3.10.x.
'''
#FIXME: After dropping Python 3.9 support:
#* Refactor all code conditionally testing this global to be unconditional.
#* Remove this global.
#* Remove all decorators resembling:
# @skip_if_python_version_less_than('3.10.0')
IS_PYTHON_AT_LEAST_3_10 = IS_PYTHON_AT_LEAST_3_11 or version_info >= (3, 10)
'''
``True`` only if the active Python interpreter targets at least Python 3.10.0.
'''
#FIXME: After dropping Python 3.9 support:
#* Remove this global.
IS_PYTHON_AT_MOST_3_9 = not IS_PYTHON_AT_LEAST_3_10
'''
``True`` only if the active Python interpreter targets at most Python 3.9.x.
'''
#FIXME: After dropping Python 3.8 support:
#* Refactor all code conditionally testing this global to be unconditional.
#* Remove this global.
#* Remove all decorators resembling:
# @skip_if_python_version_less_than('3.9.0')
IS_PYTHON_AT_LEAST_3_9 = IS_PYTHON_AT_LEAST_3_10 or version_info >= (3, 9)
'''
``True`` only if the active Python interpreter targets at least Python 3.9.0.
'''
#FIXME: After dropping Python 3.8 support:
#* Remove this global.
IS_PYTHON_AT_MOST_3_8 = not IS_PYTHON_AT_LEAST_3_9
'''
``True`` only if the active Python interpreter targets at most Python 3.8.x.
'''
#FIXME: After dropping Python 3.7 support:
#* Refactor all code conditionally testing this global to be unconditional.
#* Remove this global.
#* Remove all decorators resembling:
# @skip_if_python_version_less_than('3.8.0')
IS_PYTHON_AT_LEAST_3_8 = IS_PYTHON_AT_LEAST_3_9 or version_info >= (3, 8)
'''
``True`` only if the active Python interpreter targets at least Python 3.8.0.
'''
#FIXME: After dropping Python 3.8 support, *REMOVE* all code conditionally
#testing this global.
IS_PYTHON_3_8 = version_info[:2] == (3, 8)
'''
``True`` only if the active Python interpreter targets exactly Python 3.8.
'''
#FIXME: After dropping Python 3.7 support:
#* Refactor all code conditionally testing this global to be unconditional.
#* Remove this global.
#* Remove all decorators resembling:
# @skip_if_python_version_less_than('3.7.2')
IS_PYTHON_AT_LEAST_3_7_2 = IS_PYTHON_AT_LEAST_3_8 or version_info >= (3, 7, 2)
'''
``True`` only if the active Python interpreter targets at least Python 3.7.2,
which introduced several new public attributes to the :mod:`typing` module
(e.g., :attr:`typing.OrderedDict`).
'''
#FIXME: After dropping Python 3.7 support, *REMOVE* all code conditionally
#testing this global.
IS_PYTHON_3_7 = version_info[:2] == (3, 7)
'''
``True`` only if the active Python interpreter targets exactly Python 3.7.
'''
# ....................{ GETTERS }....................
def get_python_version_major_minor() -> str:
'''
``"."``-delimited major and minor version of the active Python interpreter
(e.g., ``3.11``, ``3.7``), excluding the patch version of this interpreter.
'''
# Heroic one-liners are an inspiration to us all.
return f'{version_info[0]}.{version_info[1]}'
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **weak reference** (i.e., references to objects explicitly
allowing those objects to be garbage-collected at *any* time) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilPythonWeakrefException
from beartype.typing import (
Tuple,
)
from weakref import ref as weakref_ref
# ....................{ GETTERS }....................
def make_obj_weakref_and_repr(obj: object) -> Tuple[object, str]:
'''
2-tuple ``(weakref, repr)`` weakly referring to the passed object.
Parameters
----------
obj : object
Arbitrary object to be weakly referred to.
Returns
----------
Tuple[object, str]
2-tuple ``(weakref, repr)`` weakly referring to this object such that:
* ``weakref`` is either:
* If this object supports weak references, a **weak reference** (i.e.,
:class:`weakref.ref` instance) to this object.
* If this object prohibits weak references (e.g., due to being a
common C-based variable-sized container like a tuple or string),
``None``.
* ``repr`` is the machine-readable representation of this object,
truncated to ~10KB to minimize space consumption in the worst case of
an obscenely large object.
'''
# Avoid circular import dependencies.
from beartype._util.text.utiltextrepr import represent_object
# Weak reference to this object if this object supports weak references *OR*
# "None" otherwise (e.g., if this object is a variable-sized container).
obj_weakref = None
# Machine-readable representation of this object truncated to minimize space
# consumption for the worst case of an obscenely large object.
obj_repr = represent_object(
obj=obj,
# Store at most 1KB of the full representation, which should
# certainly suffice for most use cases. Note that the
# default of 96B is far too small to be useful here.
max_len=1000,
)
# If this object is "None", substitute "None" for this non-"None"
# placeholder. Since the "weakref.ref" class ambiguously returns "None" when
# this object has already been garbage-collected, this placeholder enables
# subsequent calls to the get_obj_weakref_or_repr() getter to disambiguate
# between these two common edge cases.
if obj is None:
obj_weakref = _WEAKREF_NONE
# Else, this object is *NOT* "None". In this case...
else:
# Attempt to classify a weak reference to this object for safety.
try:
obj_weakref = weakref_ref(obj)
# If doing so raises a "TypeError", this object *CANNOT* be weakly
# referred to. Sadly, builtin variable-sized C-based types (e.g.,
# "dict", "int", "list", "tuple") *CANNOT* be weakly referred to. This
# constraint is officially documented by the "weakref" module:
# Several built-in types such as list and dict do not directly
# support weak references but can add support through subclassing.
# CPython implementation detail: Other built-in types such as tuple
# and int do not support weak references even when subclassed.
#
# Since this edge case is common, permitting this exception to unwind
# the call stack is unacceptable; likewise, even coercing this exception
# into non-fatal warnings would generic excessive warning spam and is
# thus also unacceptable. The only sane solution remaining is to
# silently store the machine-readable representation of this object and
# return that rather than this object from the "object" property.
except TypeError:
pass
return obj_weakref, obj_repr
def get_weakref_obj_or_repr(obj_weakref: object, obj_repr: str) -> object:
'''
Object weakly referred to by the passed object if this object is indeed a
weak reference to another existing object *or* the passed machine-readable
representation otherwise (i.e., if this object is either ``None`` *or* is a
weak reference to a dead garbage-collected object).
This function is typically passed the pair of objects returned by a prior
call to the companion :func:`make_obj_weakref_and_repr` function.
Parameters
----------
obj_weakref : object
Either:
* If the **referent** (i.e., target object being weakly referred to) is
the ``None`` singleton, the :data:`_WEAKREF_NONE` placeholder.
* Else if the referent supports weak references, a **weak reference**
(i.e., :class:`weakref.ref` instance) to that object.
* Else, ``None``.
obj_repr : str
Machine-readable representation of that object, typically truncated to
some number of characters to avoid worst-case space consumption.
Returns
----------
object
Either:
* If this weak reference is the :data:`_WEAKREF_NONE` placeholder, the
``None`` singleton.
* Else if this referent support weak references, either:
* If this referent is still alive (i.e., has yet to be
garbage-collected), this referent.
* Else, this referent is now dead (i.e., has already been
garbage-collected). In this case, the passed representation.
* Else, this referent does *not* support weak references (i.e., this
weak reference is ``None``). In this case, the passed representation.
Raises
----------
_BeartypeUtilPythonWeakrefException
If ``obj_weakref`` is invalid: i.e., neither ``None``,
:data:`_WEAKREF_NONE`, nor a weak reference.
'''
assert isinstance(obj_repr, str), f'{repr(obj_repr)} not string.'
# If this weak reference is "None", the prior call to
# make_obj_weakref_and_repr() was passed an object that could *NOT* be
# weakly referred to (e.g., C-based container). In this case, fallback to
# the machine-readable representation of that object.
if obj_weakref is None:
return obj_repr
# Else, this weak reference is *NOT* "None".
#
# If this weak reference is "_WEAKREF_NONE", the prior call to
# make_obj_weakref_and_repr() was passed the "None" singleton. In this case,
# substitute this placeholder for "None". See that factory.
elif obj_weakref is _WEAKREF_NONE:
return None
# Else, this weak reference is *NOT* that placeholder.
#
# If this weak reference is *NOT* a weak reference, raise an exception.
elif not isinstance(obj_weakref, weakref_ref):
raise _BeartypeUtilPythonWeakrefException(
f'Weak reference {repr(obj_weakref)} invalid '
f'(i.e., neither weak reference, "None", nor "_WEAKREF_NONE").'
)
# Else, this weak reference is a weak reference.
# Object weakly referred to by this weak reference if this object is alive
# *OR* "None" otherwise (i.e., if this object was garbage-collected).
obj = obj_weakref()
# Return either...
return (
# If this object is still alive, this object;
obj if obj is not None else
# Else, this object is now dead. In this case, the machine-readable
# representation of this object instead.
obj_repr
)
# ....................{ PROPERTIES ~ constants }....................
_WEAKREF_NONE = object()
'''
Singleton substitute for the ``None`` singleton, enabling
:class:`BeartypeCallHintViolation` exceptions to differentiate between weak
references to ``None`` and weak references whose referents are already dead
(i.e., have already been garbage-collected).
'''
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Beartype **Python word size** (i.e., bit length of Python variables of internal
type ``Py_ssize_t`` under the active Python interpreter) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from sys import maxsize
# ....................{ INTEGERS }....................
SHORT_MAX_32_BIT = 1 << 32
'''
Maximum value of **32-bit Python shorts** (i.e., integer variables of internal
type ``Py_ssize_t`` under 32-bit Python interpreters roughly corresponding to
the ``long`` C type under 32-bit machines, confusingly).
This value is suitable for comparison with :attr:`sys.maxsize`, the maximum
value of such variables under the active Python interpreter.
'''
# ....................{ BOOLEANS }....................
IS_WORD_SIZE_64 = maxsize > SHORT_MAX_32_BIT
'''
``True`` only if the active Python interpreter is **64-bit** (i.e., was
compiled with a 64-bit toolchain into a 64-bit executable).
Equivalently, this is ``True`` only if the maximum value of Python shorts under
this interpreter is larger than the maximum value of 32-bit Python shorts.
While obtuse, this test is well-recognized by the Python community as the
best means of testing this portably. Valid but worse alternatives include:
* ``'PROCESSOR_ARCHITEW6432' in os.environ``, which depends upon optional
environment variables and hence is clearly unreliable.
* ``platform.architecture()[0] == '64bit'``, which fails under:
* macOS, returning ``64bit`` even when the active Python interpreter is a
32-bit executable binary embedded in a so-called "universal binary."
'''
# ....................{ INTEGERS ~ more }....................
WORD_SIZE = 64 if IS_WORD_SIZE_64 else 32
'''
Bit length of **Python shorts** (i.e., integer variables of internal type
``Py_ssize_t`` roughly corresponding to the ``long`` C type, confusingly).
This integer is guaranteed to be either:
* If the active Python interpreter is 64-bit, ``64``.
* Else, ``32``.
'''
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Python interpreter** utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import (
_BeartypeUtilPathException,
_BeartypeUtilPythonInterpreterException,
)
from beartype._util.cache.utilcachecall import callable_cached
from platform import python_implementation
from sys import executable as sys_executable
# ....................{ TESTERS }....................
@callable_cached
def is_py_pypy() -> bool:
'''
``True`` only if the active Python interpreter is **PyPy**.
This tester is memoized for efficiency.
'''
return python_implementation() == 'PyPy'
# ....................{ GETTERS }....................
def get_interpreter_filename() -> str:
'''
Absolute filename of the executable binary underlying the active Python
interpreter if Python successfully queried this filename *or* raise an
exception otherwise.
Raises
----------
_BeartypeUtilPathException
If Python successfully queried this filename but no such file exists.
_BeartypeUtilPythonInterpreterException
If Python failed to query this filename.
'''
# Avoid circular import dependencies.
# from beartype._util.path.utilfile import
# If Python failed to query this filename, raise an exception.
#
# Note that this test intentionally matches both the empty string and
# "None", as the official documentation for "sys.executable" states:
# If Python is unable to retrieve the real path to its executable,
# sys.executable will be an empty string or None.
if not sys_executable:
raise _BeartypeUtilPythonInterpreterException(
'Absolute filename of Python interpreter unknown.')
# Else, Python successfully queried this filename.
#FIXME: Actually implement this up. Doing so will require declaring a
#new beartype._util.path.utilfile.die_unless_file_executable() tester. For
#simplicity, we currently assume Python knows what it's talking about here.
# # If no such file exists, raise an exception.
# die_unless_file_executable(sys_executable)
# # Else, this file exists, raise an exception.
# Return this filename as is.
return sys_executable
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **caching metaclass utilities** (i.e., low-level metaclasses
performing general-purpose memoization of classes using those metaclasses).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: Preserved for posterity, as this is the optimal approach to defining
#singletons in Python. Fascinating... but sadly currently unused.
# # ....................{ IMPORTS }....................
# from beartype.typing import (
# Optional,
# Type,
# TypeVar,
# )
#
# # ....................{ PRIVATE ~ hints }....................
# _T = TypeVar('_T')
# '''
# PEP-compliant type variable matching any arbitrary object.
# '''
#
# # ....................{ METACLASSES }....................
# #FIXME: Unit test us up, please.
# class SingletonMeta(type):
# '''
# **Singleton metaclass** (i.e., the root :class:`type` metaclass augmented
# with caching to implement the singleton design pattern).
#
# This metaclass is superior to the usual approach of implementing the
# singleton design pattern: overriding the :meth:`__new__` method of a
# singleton class to conditionally create a new instance of that class only if
# an instance has *not* already been created. Why? Because that approach
# unavoidably re-calls the :meth:`__init__` method of a previously initialized
# singleton instance on each instantiation of that class. Doing so is
# generally considered harmful.
#
# This metaclass instead guarantees that the :meth:`__init__` method of a
# singleton instance is only called exactly once on the first instantiation of
# that class.
#
# Attributes
# ----------
# __singleton : Optional[type]
# Either:
#
# * If the current singleton abstract base class (ABC) has been
# initialized (i.e., if the :meth:`__init__` method of this metaclass
# initializing that class with metaclass-specific logic) but a singleton
# instance of that class has *not* yet been instantiated (i.e., if the
# :meth:`__call__` method of this metaclass calling the :meth:`__new__`
# and :meth:`__init__` methods of that class (in that order) has been
# called), ``None``.
# * Else, the current singleton ABC has been initialized and a singleton
# instance of that class has been instantiated. In this case, that
# instance.
#
# For forward compatibility with future :class:`ABCMeta` changes, the name
# of this instance variable is prefixed by ``"__"`` and thus implicitly
# obfuscated by Python to be externally inaccessible.
#
# See Also
# ----------
# https://stackoverflow.com/a/8665179/2809027
# StackOverflow answers strongly inspiring this implementation.
# '''
#
# # ..................{ INITIALIZERS }..................
# def __init__(cls: Type[_T], *args, **kwargs) -> None:
# '''
# Initialize the passed singleton abstract base class (ABC).
#
# Parameters
# ----------
# cls : type
# Singleton abstract base class (ABC) whose class is this metaclass.
#
# All remaining parameters are passed as is to the superclass
# :meth:`type.__init__` method.
# '''
#
# # Initialize our superclass with all passed parameters.
# super().__init__(*args, **kwargs)
#
# # Nullify all instance variables for safety.
# cls.__singleton: Optional[type] = None
# # print(f'!!!!!!!!!!!!! [ in SingletonMeta.__init__({repr(cls)}) ] !!!!!!!!!!!!!!!')
#
#
# def __call__(cls: Type[_T], *args, **kwargs) -> _T:
# '''
# Instantiate the passed singleton class.
#
# Parameters
# ----------
# cls : type
# Singleton class whose class is this metaclass.
#
# All remaining parameters are passed as is to the superclass
# :meth:`type.__call__` method.
# '''
#
# # If a singleton instance of that class has yet to be instantiated, do
# # so.
# # print(f'!!!!!!!!!!!!! [ in SingletonMeta.__call__({repr(cls)}) ] !!!!!!!!!!!!!!!')
# if cls.__singleton is None:
# cls.__singleton = super().__call__(*args, **kwargs)
# # print(f'!!!!!!!!!!!!! [ instantiating new {repr(cls)} singleton ] !!!!!!!!!!!!!!!')
# # Else, a singleton instance of that class has already been
# # instantiated.
#
# # Return this singleton instance as is.
# return cls.__singleton
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable caching utilities** (i.e., low-level callables
performing general-purpose memoization of function and method calls).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: Generalize @callable_cached to revert to the body of the
#@beartype._util.type.decorator.decmemo.func_cached decorator when the passed
#callable accepts *NO* parameters, which can be trivially decided by inspecting
#the code object of this callable. Why do this? Because the @func_cached
#decorator is *INSANELY* fast for this edge case -- substantially faster than
#the current general-purpose @callable_cached approach.
#FIXME: Generalize @callable_cached to support variadic positional parameters by
#appending to "params_flat":
#1. A placeholder sentinel object after all non-variadic positional parameters.
#2. Those variadic parameters.
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCallableCachedException
from beartype.typing import (
Dict,
TypeVar,
)
from beartype._util.func.arg.utilfuncargtest import (
die_unless_func_args_len_flexible_equal,
is_func_arg_variadic,
)
from beartype._util.text.utiltextlabel import label_callable
from beartype._util.utilobject import SENTINEL
from collections.abc import Callable
from functools import wraps
# ....................{ PRIVATE ~ hints }....................
_CallableT = TypeVar('_CallableT', bound=Callable)
'''
Type variable bound to match *only* callables.
'''
# ....................{ DECORATORS ~ callable }....................
def callable_cached(func: _CallableT) -> _CallableT:
'''
**Memoize** (i.e., efficiently re-raise all exceptions previously raised by
the decorated callable when passed the same parameters (i.e., parameters
that evaluate as equals) as a prior call to that callable if any *or* return
all values previously returned by that callable otherwise rather than
inefficiently recalling that callable) the passed callable.
Specifically, this decorator (in order):
#. Creates:
* A local dictionary mapping parameters passed to this callable with the
values returned by this callable when passed those parameters.
* A local dictionary mapping parameters passed to this callable with the
exceptions raised by this callable when passed those parameters.
#. Creates and returns a closure transparently wrapping this callable with
memoization. Specifically, this wrapper (in order):
#. Tests whether this callable has already been called at least once
with the passed parameters by lookup of those parameters in these
dictionaries.
#. If this callable previously raised an exception when passed these
parameters, this wrapper re-raises the same exception.
#. Else if this callable returned a value when passed these parameters,
this wrapper re-returns the same value.
#. Else, this wrapper:
#. Calls that callable with those parameters.
#. If that call raised an exception:
#. Caches that exception with those parameters in that dictionary.
#. Raises that exception.
#. Else:
#. Caches the value returned by that call with those parameters in
that dictionary.
#. Returns that value.
Caveats
----------
**The decorated callable must accept no keyword parameters.** While this
decorator previously memoized keyword parameters, doing so incurred
significant performance penalties defeating the purpose of caching. This
decorator now intentionally memoizes *only* positional parameters.
**The decorated callable must accept no variadic positional parameters.**
While memoizing variadic parameters would of course be feasible, this
decorator has yet to implement support for doing so.
**The decorated callable should not be a property method** (i.e., either a
property getter, setter, or deleter subsequently decorated by the
:class:`property` decorator). Technically, this decorator *can* be used to
memoize property methods; pragmatically, doing so would be sufficiently
inefficient as to defeat the intention of memoizing in the first place.
Efficiency
----------
For efficiency, consider calling the decorated callable with only:
* **Hashable** (i.e., immutable) arguments. While technically supported,
every call to the decorated callable passed one or more unhashable
arguments (e.g., mutable containers like lists and dictionaries) will
silently *not* be memoized. Equivalently, only calls passed only hashable
arguments will be memoized. This flexibility enables decorated callables
to accept unhashable PEP-compliant type hints. Although *all*
PEP-noncompliant and *most* PEP-compliant type hints are hashable, some
sadly are not. These include:
* :pep:`585`-compliant type hints subscripted by one or more unhashable
objects (e.g., ``collections.abc.Callable[[], str]``, the `PEP
585`_-compliant type hint annotating piths accepting callables
accepting no parameters and returning strings).
* :pep:`586`-compliant type hints subscripted by an unhashable object
(e.g., ``typing.Literal[[]]``, a literal empty list).
* :pep:`593`-compliant type hints subscripted by one or more unhashable
objects (e.g., ``typing.Annotated[typing.Any, []]``, the
:attr:`typing.Any` singleton annotated by an empty list).
**This decorator is intentionally not implemented in terms of the stdlib**
:func:`functools.lru_cache` **decorator,** as that decorator is inefficient
in the special case of unbounded caching with ``maxsize=None``. Why? Because
that decorator insists on unconditionally recording irrelevant statistics
like cache misses and hits. While bounding the number of cached values is
advisable in the general case (e.g., to avoid exhausting memory merely for
optional caching), parameters and returns cached by this package are
sufficiently small in size to render such bounding irrelevant.
Consider the
:func:`beartype._util.hint.pep.utilpeptest.is_hint_pep_type_typing`
function, for example. Each call to that function only accepts a single
class and returns a boolean. Under conservative assumptions of 4 bytes of
storage per class reference and 4 byte of storage per boolean reference,
each call to that function requires caching at most 8 bytes of storage.
Again, under conservative assumptions of at most 1024 unique type
annotations for the average downstream consumer, memoizing that function in
full requires at most 1024 * 8 == 8096 bytes or ~8Kb of storage. Clearly,
8Kb of overhead is sufficiently negligible to obviate any space concerns
that would warrant an LRU cache in the first place.
Parameters
----------
func : _CallableT
Callable to be memoized.
Returns
----------
_CallableT
Closure wrapping this callable with memoization.
Raises
----------
_BeartypeUtilCallableCachedException
If this callable accepts a variadic positional parameter (e.g.,
``*args``).
'''
assert callable(func), f'{repr(func)} not callable.'
# Avoid circular import dependencies.
from beartype._util.func.utilfuncwrap import unwrap_func
# Lowest-level wrappee callable wrapped by this wrapper callable.
func_wrappee = unwrap_func(func)
# If this wrappee accepts variadic arguments, raise an exception.
if is_func_arg_variadic(func_wrappee):
raise _BeartypeUtilCallableCachedException(
f'@callable_cached {label_callable(func)} '
f'variadic arguments uncacheable.'
)
# Else, this wrappee accepts *NO* variadic arguments.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize against the @method_cached_arg_by_id decorator
# below. For speed, this decorator violates DRY by duplicating logic.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Dictionary mapping a tuple of all flattened parameters passed to each
# prior call of the decorated callable with the value returned by that call
# if any (i.e., if that call did *NOT* raise an exception).
args_flat_to_return_value: Dict[tuple, object] = {}
# get() method of this dictionary, localized for efficiency.
args_flat_to_return_value_get = args_flat_to_return_value.get
# Dictionary mapping a tuple of all flattened parameters passed to each
# prior call of the decorated callable with the exception raised by that
# call if any (i.e., if that call raised an exception).
args_flat_to_exception: Dict[tuple, Exception] = {}
# get() method of this dictionary, localized for efficiency.
args_flat_to_exception_get = args_flat_to_exception.get
@wraps(func)
def _callable_cached(*args):
f'''
Memoized variant of the {func.__name__}() callable.
See Also
----------
:func:`callable_cached`
Further details.
'''
# Object representing all passed positional arguments to be used as the
# key of various memoized dictionaries, defined as either...
args_flat = (
# If passed only one positional argument, minimize space consumption
# by flattening this tuple of only that argument into that argument.
# Since tuple items are necessarily hashable, this argument is
# necessarily hashable and thus permissible as a dictionary key;
args[0]
if len(args) == 1 else
# Else, one or more positional arguments are passed. In this case,
# reuse this tuple as is.
args
)
# Attempt to...
try:
# Exception raised by a prior call to the decorated callable when
# passed these parameters *OR* the sentinel placeholder otherwise
# (i.e., if this callable either has yet to be called with these
# parameters *OR* has but failed to raise an exception).
#
# Note that:
# * This statement raises a "TypeError" exception if any item of
# this flattened tuple is unhashable.
# * A sentinel placeholder (e.g., "SENTINEL") is *NOT* needed here.
# The values of the "args_flat_to_exception" dictionary are
# guaranteed to *ALL* be exceptions. Since "None" is *NOT* an
# exception, disambiguation between "None" and valid dictionary
# values is *NOT* needed here. Although a sentinel placeholder
# could still be employed, doing so would slightly reduce
# efficiency for *NO* real-world gain.
exception = args_flat_to_exception_get(args_flat)
# If this callable previously raised an exception when called with
# these parameters, re-raise the same exception.
if exception:
raise exception # pyright: ignore[reportGeneralTypeIssues]
# Else, this callable either has yet to be called with these
# parameters *OR* has but failed to raise an exception.
# Value returned by a prior call to the decorated callable when
# passed these parameters *OR* a sentinel placeholder otherwise
# (i.e., if this callable has yet to be passed these parameters).
return_value = args_flat_to_return_value_get(
args_flat, SENTINEL)
# If this callable has already been called with these parameters,
# return the value returned by that prior call.
if return_value is not SENTINEL:
return return_value
# Else, this callable has yet to be called with these parameters.
# Attempt to...
try:
# Call this parameter with these parameters and cache the value
# returned by this call to these parameters.
return_value = args_flat_to_return_value[args_flat] = func(
*args)
# If this call raised an exception...
except Exception as exception:
# Cache this exception to these parameters.
args_flat_to_exception[args_flat] = exception
# Re-raise this exception.
raise exception
# If one or more objects either passed to *OR* returned from this call
# are unhashable, perform this call as is *WITHOUT* memoization. While
# non-ideal, stability is better than raising a fatal exception.
except TypeError:
#FIXME: If testing, emit a non-fatal warning or possibly even raise
#a fatal exception. In either case, we want our test suite to notify
#us about this.
return func(*args)
# Return this value.
return return_value
# Return this wrapper.
return _callable_cached # type: ignore[return-value]
# ....................{ DECORATORS ~ method }....................
def method_cached_arg_by_id(func: _CallableT) -> _CallableT:
'''
**Memoize** (i.e., efficiently re-raise all exceptions previously raised by
the decorated method when passed the same *exact* parameters (i.e.,
parameters whose object IDs are equals) as a prior call to that method if
any *or* return all values previously returned by that method otherwise
rather than inefficiently recalling that method) the passed method.
Caveats
----------
**This decorator is only intended to decorate bound methods** (i.e., either
class or instance methods bound to a class or instance). This decorator is
*not* intended to decorate functions or static methods.
**This decorator is only intended to decorate a method whose sole argument
is guaranteed to be a memoized singleton** (e.g.,
:class:`beartype.door.TypeHint` singletons). In this case, the object
identifier of that argument uniquely identifies that argument across *all*
calls to that method -- enabling this decorator to memoize that method.
Conversely, if that argument is *not* guaranteed to be a memoized singleton,
this decorator will fail to memoize that method while wasting considerable
space and time attempting to do so. In short, care is warranted.
This decorator is a micro-optimized variant of the more general-purpose
:func:`callable_cached` decorator, which should be preferred in most cases.
This decorator mostly exists for one specific edge case that the
:func:`callable_cached` decorator *cannot* by definition support:
user-defined classes implementing the ``__eq__`` dunder method to internally
call another method decorated by :func:`callable_cached` accepting an
instance of the same class. This design pattern appears astonishingly
frequently, including in our prominent :class:`beartype.door.TypeHint`
class. This edge case provokes infinite recursion. Consider this
minimal-length example (MLE) exhibiting the issue:
.. code-block:: python
from beartype._util.cache.utilcachecall import callable_cached
class MuhClass(object):
def __eq__(self, other: object) -> bool:
return isinstance(other, MuhClass) and self._is_equal(other)
@callable_cached
def _is_equal(self, other: 'MuhClass') -> bool:
return True
:func:`callable_cached` internally caches the ``other`` argument passed to
the ``_is_equal()`` method as keys of various internal dictionaries. When
passed the same ``other`` argument, subsequent calls to that method lookup
that ``other`` argument in those dictionaries. Since dictionary lookups
implicitly call the ``other.__eq__()`` method to resolve key collisions
*and* since the ``__eq__()`` method has been overridden in terms of the
``_is_equal()`` method, infinite recursion results.
This decorator circumvents this issue by internally looking up the object
identifier of the passed argument rather than that argument itself, which
then avoids implicitly calling the ``__eq__()`` method of that argument.
Parameters
----------
func : _CallableT
Callable to be memoized.
Returns
----------
_CallableT
Closure wrapping this callable with memoization.
Raises
----------
_BeartypeUtilCallableCachedException
If this callable accepts either:
* *No* parameters.
* Two or more parameters.
* A variadic positional parameter (e.g., ``*args``).
See Also
----------
:func:`callable_cached`
Further details.
'''
assert callable(func), f'{repr(func)} not callable.'
# Avoid circular import dependencies.
from beartype._util.func.utilfuncwrap import unwrap_func
# Lowest-level wrappee callable wrapped by this wrapper callable.
func_wrappee = unwrap_func(func)
# If this wrappee accepts either zero, one, *OR* three or more flexible
# parameters (i.e., parameters passable as either positional or keyword
# arguments), raise an exception.
die_unless_func_args_len_flexible_equal(
func=func_wrappee,
func_args_len_flexible=2,
exception_cls=_BeartypeUtilCallableCachedException,
# Avoid unnecessary callable unwrapping as a negligible optimization.
is_unwrapping=False,
)
# Else, this wrappee accepts exactly one flexible parameter.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize against the @callable_cached decorator above. For
# speed, this decorator violates DRY by duplicating logic.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# If this wrappee accepts variadic arguments, raise an exception.
if is_func_arg_variadic(func_wrappee):
raise _BeartypeUtilCallableCachedException(
f'@method_cached_arg_by_id {label_callable(func)} '
f'variadic arguments uncacheable.'
)
# Else, this wrappee accepts *NO* variadic arguments.
# Dictionary mapping a tuple of all flattened parameters passed to each
# prior call of the decorated callable with the value returned by that call
# if any (i.e., if that call did *NOT* raise an exception).
args_flat_to_return_value: Dict[tuple, object] = {}
# get() method of this dictionary, localized for efficiency.
args_flat_to_return_value_get = args_flat_to_return_value.get
# Dictionary mapping a tuple of all flattened parameters passed to each
# prior call of the decorated callable with the exception raised by that
# call if any (i.e., if that call raised an exception).
args_flat_to_exception: Dict[tuple, Exception] = {}
# get() method of this dictionary, localized for efficiency.
args_flat_to_exception_get = args_flat_to_exception.get
@wraps(func)
def _method_cached(self_or_cls, arg):
f'''
Memoized variant of the {func.__name__}() callable.
See Also
----------
:func:`callable_cached`
Further details.
'''
# Object identifiers of the sole positional parameters passed to the
# decorated method.
args_flat = (id(self_or_cls), id(arg))
# Attempt to...
try:
# Exception raised by a prior call to the decorated callable when
# passed these parameters *OR* the sentinel placeholder otherwise
# (i.e., if this callable either has yet to be called with these
# parameters *OR* has but failed to raise an exception).
#
# Note that:
# * This statement raises a "TypeError" exception if any item of
# this flattened tuple is unhashable.
# * A sentinel placeholder (e.g., "SENTINEL") is *NOT* needed here.
# The values of the "args_flat_to_exception" dictionary are
# guaranteed to *ALL* be exceptions. Since "None" is *NOT* an
# exception, disambiguation between "None" and valid dictionary
# values is *NOT* needed here. Although a sentinel placeholder
# could still be employed, doing so would slightly reduce
# efficiency for *NO* real-world gain.
exception = args_flat_to_exception_get(args_flat)
# If this callable previously raised an exception when called with
# these parameters, re-raise the same exception.
if exception:
raise exception # pyright: ignore[reportGeneralTypeIssues]
# Else, this callable either has yet to be called with these
# parameters *OR* has but failed to raise an exception.
# Value returned by a prior call to the decorated callable when
# passed these parameters *OR* a sentinel placeholder otherwise
# (i.e., if this callable has yet to be passed these parameters).
return_value = args_flat_to_return_value_get(
args_flat, SENTINEL)
# If this callable has already been called with these parameters,
# return the value returned by that prior call.
if return_value is not SENTINEL:
return return_value
# Else, this callable has yet to be called with these parameters.
# Attempt to...
try:
# Call this parameter with these parameters and cache the value
# returned by this call to these parameters.
return_value = args_flat_to_return_value[args_flat] = func(
self_or_cls, arg)
# If this call raised an exception...
except Exception as exception:
# Cache this exception to these parameters.
args_flat_to_exception[args_flat] = exception
# Re-raise this exception.
raise exception
# If one or more objects either passed to *OR* returned from this call
# are unhashable, perform this call as is *WITHOUT* memoization. While
# non-ideal, stability is better than raising a fatal exception.
except TypeError:
#FIXME: If testing, emit a non-fatal warning or possibly even raise
#a fatal exception. In either case, we want our test suite to notify
#us about this.
return func(self_or_cls, arg)
# Return this value.
return return_value
# Return this wrapper.
return _method_cached # type: ignore[return-value]
# ....................{ DECORATORS ~ property }....................
def property_cached(func: _CallableT) -> _CallableT:
'''
**Memoize** (i.e., efficiently cache and return all previously returned
values of the passed property method as well as all previously raised
exceptions of that method previously rather than inefficiently recalling
that method) the passed **property method method** (i.e., either a property
getter, setter, or deleter subsequently decorated by the :class:`property`
decorator).
On the first access of a property decorated with this decorator (in order):
#. The passed method implementing this property is called.
#. The value returned by this property is internally cached into a private
attribute of the object to which this method is bound.
#. This value is returned.
On each subsequent access of this property, this cached value is returned as
is *without* calling the decorated method. Hence, the decorated method is
called at most once for each object exposing this property.
Caveats
----------
**This decorator must be preceded by an explicit usage of the standard**
:class:`property` **decorator.** Although this decorator could be trivially
refactored to automatically decorate the returned property method by the
:class:`property` decorator, doing so would violate static type-checking
expectations -- introducing far more issues than it would solve.
**This decorator should always be preferred over the standard**
:func:`functools.cached_property` **decorator available under Python >=
3.8.** This decorator is substantially more efficient in both space and time
than that decorator -- which is, of course, the entire point of caching.
**This decorator does not destroy bound property methods.** Technically, the
most efficient means of caching a property value into an instance is to
replace the property method currently bound to that instance with an
instance variable initialized to that value (e.g., as documented by this
`StackOverflow answer`_). Since a property should only ever be treated as an
instance variable, there superficially exists little harm in dynamically
changing the type of the former to the latter. Sadly, doing so introduces
numerous subtle issues with *no* plausible workaround. Notably, replacing
property methods by instance variables:
* Permits callers to erroneously set **read-only properties** (i.e.,
properties lacking setter methods), a profound violation of one of the
principle use cases for properties.
* Prevents pickling logic elsewhere from automatically excluding cached
property values, forcing these values to *always* be pickled to disk.
This is bad. Cached property values are *always* safely recreatable in
memory (and hence need *not* be pickled) and typically space-consumptive
in memory (and hence best *not* pickled). The slight efficiency gain from
replacing property methods by instance variables is hardly worth the
significant space loss from pickling these variables.
.. _StackOverflow answer:
https://stackoverflow.com/a/36684652/2809027
Parameters
----------
func : _CallableT
Property method to be memoized.
'''
assert callable(func), f'{repr(func)} not callable.'
# Name of the private instance variable to which this decorator caches the
# value returned by the decorated property method.
property_var_name = (
_PROPERTY_CACHED_VAR_NAME_PREFIX + func.__name__)
# Raw string of Python statements comprising the body of this wrapper.
#
# Note that this implementation intentionally avoids calling our
# higher-level beartype._util.func.utilfuncmake.make_func() factory function
# for dynamically generating functions. Although this implementation could
# certainly be refactored in terms of that factory, doing so would
# needlessly reduce debuggability and portability for *NO* tangible gain.
func_body = _PROPERTY_CACHED_CODE.format(
property_var_name=property_var_name)
# Dictionary mapping from local attribute names to values. For efficiency,
# only attributes required by the body of this wrapper are copied from the
# current namespace. (See below.)
local_attrs = {'__property_method': func}
# Dynamically define this wrapper as a closure of this decorator. For
# obscure and presumably uninteresting reasons, Python fails to locally
# declare this closure when the locals() dictionary is passed; to capture
# this closure, a local dictionary must be passed instead.
exec(func_body, globals(), local_attrs)
# Return this wrapper method.
return local_attrs['property_method_cached']
# ....................{ PRIVATE ~ constants : var }....................
_CALLABLE_CACHED_VAR_NAME_PREFIX = '_beartype_cached__'
'''
Substring prefixing the names of all private instance variables to which all
caching decorators (e.g., :func:`property_cached`) cache values returned by
decorated callables.
This prefix guarantees uniqueness across *all* instances -- including those
instantiated from official Python and unofficial third-party classes and those
internally defined by this application. Doing so permits logic elsewhere (e.g.,
pickling filtering) to uniquely match and act upon these variables.
'''
_FUNCTION_CACHED_VAR_NAME = (
f'{_CALLABLE_CACHED_VAR_NAME_PREFIX}function_value')
'''
Name of the private instance variable to which the :func:`func_cached`
decorator statically caches the value returned by the decorated function.
'''
_PROPERTY_CACHED_VAR_NAME_PREFIX = (
f'{_CALLABLE_CACHED_VAR_NAME_PREFIX}property_')
'''
Substring prefixing the names of all private instance variables to which the
:func:`property_cached` decorator dynamically caches the value returned by the
decorated property method.
'''
# ....................{ PRIVATE ~ constants : code }....................
_PROPERTY_CACHED_CODE = '''
@wraps(__property_method)
def property_method_cached(self, __property_method=__property_method):
try:
return self.{property_var_name}
except AttributeError:
self.{property_var_name} = __property_method(self)
return self.{property_var_name}
'''
'''
Raw string of Python statements comprising the body of the wrapper function
dynamically generated by the :func:`property_cached` decorator.
These statements include (in order):
* A :mod:`functools.wraps` decoration propagating the name, docstring, and other
identifying metadata of the original function to this wrapper.
* A private ``__property_method`` parameter set to the underlying property
getter method. In theory, the ``func`` parameter passed to the
:func:`property_cached` decorator should be accessible as a closure-style
local in this code. For unknown reasons (presumably, a subtle bug in the
:func:`exec` builtin), this is not the case. Instead, a closure-style local
must be simulated by passing the ``func`` parameter to this function at
function definition time as the default value of an arbitrary parameter.
Design
----------
While there exist numerous alternative implementations for caching properties,
the approach implemented below has been profiled to be the most efficient.
Alternatives include (in order of decreasing efficiency):
* Dynamically getting and setting a property-specific key-value pair of the
internal dictionary for the current object, timed to be approximately 1.5
times as slow as exception handling: e.g.,
.. code-block:: python
if not {property_name!r} in self.__dict__:
self.__dict__[{property_name!r}] = __property_method(self)
return self.__dict__[{property_name!r}]
* Dynamically getting and setting a property-specific attribute of the current
object (e.g., the internal dictionary for the current object), timed to be
approximately 1.5 times as slow as exception handling: e.g.,
.. code-block:: python
if not hasattr(self, {property_name!r}):
setattr(self, {property_name!r}, __property_method(self))
return getattr(self, {property_name!r})
'''
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **unbounded cache** utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.typing import (
Callable,
Dict,
Union,
)
from beartype._util.utilobject import SENTINEL
from collections.abc import Hashable
from contextlib import AbstractContextManager
from threading import Lock
# ....................{ CLASSES }....................
#FIXME: Submit back to StackOverflow, preferably under this question:
# https://stackoverflow.com/questions/1312331/using-a-global-dictionary-with-threads-in-python
class CacheUnboundedStrong(object):
'''
**Thread-safe strongly unbounded cache** (i.e., mapping of unlimited size
from strongly referenced arbitrary keys onto strongly referenced arbitrary
values, whose methods are guaranteed to behave thread-safely).
Design
------
Cache implementations typically employ weak references for safety. Employing
strong references invites memory leaks by preventing objects *only*
referenced by the cache (cache-only objects) from being garbage-collected.
Nonetheless, this cache intentionally employs strong references to persist
these cache-only objects across calls to callables decorated with
:func:`beartype.beartype`. In theory, caching an object under a weak
reference would result in immediate garbage-collection; with *no* external
strong referents, that object would be garbage-collected with all other
short-lived objects in the first generation (i.e., generation 0).
This cache intentionally does *not* adhere to standard mapping semantics by
subclassing a standard mapping API (e.g., :class:`dict`,
:class:`collections.abc.MutableMapping`). Standard mapping semantics are
sufficiently low-level as to invite race conditions between competing
threads concurrently contesting the same instance of this class. For
example, consider the following standard non-atomic logic for caching a new
key-value into this cache:
.. code-block:: python
if key not in cache: # <-- If a context switch happens immediately
# <-- after entering this branch, bad stuff!
cache[key] = value # <-- We may overwrite another thread's work.
Attributes
----------
_key_to_value : dict[Hashable, object]
Internal **backing store** (i.e., thread-unsafe dictionary of unlimited
size mapping from strongly referenced arbitrary keys onto strongly
referenced arbitrary values).
_key_to_value_get : Callable
The :meth:`self._key_to_value.get` method, classified for efficiency.
_key_to_value_set : Callable
The :meth:`self._key_to_value.__setitem__` dunder method, classified
for efficiency.
_lock : AbstractContextManager
**Instance-specific thread lock** (i.e., low-level thread locking
mechanism implemented as a highly efficient C extension, defined as an
instance variable for non-reentrant reuse by the public API of this
class). Although CPython, the canonical Python interpreter, *does*
prohibit conventional multithreading via its Global Interpreter Lock
(GIL), CPython still coercively preempts long-running threads at
arbitrary execution points. Ergo, multithreading concerns are *not*
safely ignorable -- even under CPython.
'''
# ..................{ CLASS VARIABLES }..................
# Slot all instance variables defined on this object to minimize the time
# complexity of both reading and writing variables across frequently called
# @beartype decorations. Slotting has been shown to reduce read and write
# costs by approximately ~10%, which is non-trivial.
__slots__ = (
'_key_to_value',
'_key_to_value_get',
'_key_to_value_set',
'_lock',
)
# ..................{ INITIALIZER }..................
def __init__(
self,
# Optional parameters.
lock_type: Union[type, Callable[[], object]] = Lock,
) -> None:
'''
Initialize this cache to an empty cache.
Parameters
----------
lock_type : Union[type, Callable[[], object]]
Type of thread-safe lock to internally use. Defaults to
:class:`Lock` (i.e., the type of the standard non-reentrant lock)
for efficiency.
'''
# Initialize all instance variables.
self._key_to_value: Dict[Hashable, object] = {}
self._key_to_value_get = self._key_to_value.get
self._key_to_value_set = self._key_to_value.__setitem__
self._lock: AbstractContextManager = lock_type() # type: ignore[assignment]
# ..................{ GETTERS }..................
def cache_or_get_cached_value(
self,
# Mandatory parameters.
key: Hashable,
value: object,
# Hidden parameters, localized for negligible efficiency.
_SENTINEL=SENTINEL,
) -> object:
'''
**Statically** (i.e., non-dynamically, rather than "statically" in the
different semantic sense of "static" methods) associate the passed key
with the passed value if this cache has yet to cache this key (i.e., if
this method has yet to be passed this key) and, in any case, return the
value associated with this key.
Parameters
----------
key : Hashable
**Key** (i.e., arbitrary hashable object) to return the associated
value of.
value : object
**Value** (i.e., arbitrary object) to associate with this key if
this key has yet to be associated with any value.
Returns
----------
object
**Value** (i.e., arbitrary object) associated with this key.
'''
# assert isinstance(key, Hashable), f'{repr(key)} unhashable.'
# Thread-safely (but non-reentrantly)...
with self._lock:
# Value previously cached under this key if any *OR* the sentinel
# placeholder otherwise.
value_old = self._key_to_value_get(key, _SENTINEL)
# If this key has already been cached, return this value as is.
if value_old is not _SENTINEL:
return value_old
# Else, this key has yet to be cached.
# Cache this key with this value.
self._key_to_value_set(key, value)
# Return this value.
return value
#FIXME: Unit test us up.
#FIXME: Generalize to accept a new mandatory "arg: object" parameter and
#then pass rather than forcefully passing the passed key. \o/
def cache_or_get_cached_func_return_passed_arg(
self,
# Mandatory parameters.
key: Hashable,
value_factory: Callable[[object], object],
arg: object,
# Hidden parameters, localized for negligible efficiency.
_SENTINEL=SENTINEL,
) -> object:
'''
Dynamically associate the passed key with the value returned by the
passed **value factory** (i.e., caller-defined function accepting this
key and returning the value to be associated with this key) if this
cache has yet to cache this key (i.e., if this method has yet to be
passed this key) and, in any case, return the value associated with
this key.
Caveats
----------
**This value factory must not recursively call this method.** For
efficiency, this cache is internally locked through a non-reentrant
rather than reentrant thread lock. If this value factory accidentally
recursively calls this method, the active thread will be indefinitely
locked. Welcome to the risky world of high-cost efficiency gains.
Parameters
----------
key : Hashable
**Key** (i.e., arbitrary hashable object) to return the associated
value of.
value_factory : Callable[[object], object]
**Value factory** (i.e., caller-defined function accepting the
passed ``arg`` object and dynamically returning the value to be
associated with this key).
arg : object
Arbitrary object to be passed as is to this value factory.
Returns
----------
object
**Value** (i.e., arbitrary object) associated with this key.
'''
# assert isinstance(key, Hashable), f'{repr(key)} unhashable.'
# assert callable(value_factory), f'{repr(value_factory)} uncallable.'
# Thread-safely (but non-reentrantly)...
with self._lock:
# Value previously cached under this key if any *OR* the sentinel
# placeholder otherwise.
value_old = self._key_to_value_get(key, _SENTINEL)
# If this key has already been cached, return this value as is.
if value_old is not _SENTINEL:
return value_old
# Else, this key has yet to be cached.
# Value created by this factory function, localized for negligible
# efficiency to avoid the unnecessary subsequent dictionary lookup.
value = value_factory(arg)
# Cache this key with this value.
self._key_to_value_set(key, value)
# Return this value.
return value
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Least Recently Used (LRU) cache** utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: The current "CacheLruStrong" implementation is overly low-level and
#thus fundamentally *THREAD-UNSAFE.* The core issue here is that the current
#approach encourages callers to perform thread-unsafe logic resembling:
# if key not in lru_dict: # <-- if a context switch happens here, bad stuff
# lru_dict[key] = value
#
#For thread-safety, the entire "CacheLruStrong" class *MUST* be rethought along
#the manner of the comparable "utilmapbig.CacheUnboundedStrong" class. Notably:
#* "CacheLruStrong" class should *NOT* directly subclass "dict" but instead
# simply contain a "_dict" instance.
#* Thread-unsafe dunder methods (particularly the "__setitem__" method) should
# probably *NOT* be defined at all. Yeah, we know.
#* A new CacheLruStrong.cache_entry() method resembling the existing
# CacheUnboundedStrong.cache_entry() method should be declared.
#* Indeed, we should (arguably) declare a new "CacheStrongABC" base class to
# provide a common API here -- trivializing switching between different
# caching strategies implemented by concrete subclasses.
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCacheLruException
from beartype.typing import Hashable
from threading import Lock
# ....................{ CLASSES }....................
class CacheLruStrong(dict):
'''
**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping
limited to some maximum capacity of strongly referenced arbitrary keys
mapped onto strongly referenced arbitrary values, whose methods are
guaranteed to behave thread-safely).
Design
------
Cache implementations typically employ weak references for safety.
Employing strong references invites memory leaks by preventing objects
*only* referenced by the cache (cache-only objects) from being
garbage-collected. Nonetheless, this cache intentionally employs strong
references to persist these cache-only objects across calls to callables
decorated with :func:`beartype.beartype`. In theory, caching an object
under a weak reference would result in immediate garbage-collection as,
with no external strong referents, the object would get collected with all
other short-lived objects in the first generation (i.e., generation 0).
Note that:
* The equivalent LRU cache employing weak references to keys and/or values
may be trivially implemented by swapping this classes inheritance from
the builtin :class:`dict` to either of the builtin
:class:`weakref.WeakKeyDictionary` or
:class:`weakref.WeakValueDictionary`.
* The standard example of a cache-only object is a container iterator
(e.g., :meth:`dict.items`).
Attributes
----------
_size : int
**Cache capacity** (i.e., maximum number of key-value pairs persisted
by this cache).
_lock : Lock
**Non-reentrant instance-specific thread lock** (i.e., low-level thread
locking mechanism implemented as a highly efficient C extension,
defined as an instance variable for non-reentrant reuse by the public
API of this class). Although CPython, the canonical Python interpreter,
*does* prohibit conventional multithreading via its Global Interpreter
Lock (GIL), CPython still coercively preempts long-running threads at
arbitrary execution points. Ergo, multithreading concerns are *not*
safely ignorable -- even under CPython.
'''
# ..................{ CLASS VARIABLES }..................
# Slot all instance variables defined on this object to minimize the time
# complexity of both reading and writing variables across frequently called
# cache dunder methods. Slotting has been shown to reduce read and write
# costs by approximately ~10%, which is non-trivial.
__slots__ = (
'_size',
'_lock',
)
# ..................{ DUNDERS }..................
def __init__(self, size: int) -> None:
'''
Initialize this cache to an empty cache with a capacity of this size.
Parameters
----------
size : int
**Cache capacity** (i.e., maximum number of key-value pairs held in
this cache).
Raises
------
_BeartypeUtilCacheLruException:
If the capacity is *not* an integer or its a **non-positive
integer** (i.e. less than 1).
'''
super().__init__()
if not isinstance(size, int):
raise _BeartypeUtilCacheLruException(
f'LRU cache capacity {repr(size)} not integer.')
elif size < 1:
raise _BeartypeUtilCacheLruException(
f'LRU cache capacity {size} not positive.')
self._size = size
self._lock = Lock()
def __getitem__(
self,
key: Hashable,
# Superclass methods efficiently localized as default parameters.
__contains=dict.__contains__,
__getitem=dict.__getitem__,
__delitem=dict.__delitem__,
__pushitem=dict.__setitem__,
) -> object:
'''
Return an item previously cached under the passed key *or* raise an
exception otherwise.
This implementation is *practically* identical to
:meth:`self.__contains__` except we return an arbitrary object rather
than a boolean.
Parameters
----------
key : Hashable
Arbitrary hashable key to retrieve the cached value of.
Returns
----------
object
Arbitrary value cached under this key.
Raises
----------
TypeError
If this key is not hashable.
KeyError
If this key isn't cached.
'''
with self._lock:
# Reset this key if it exists.
if __contains(self, key):
val = __getitem(self, key)
__delitem(self, key)
__pushitem(self, key, val)
return val
raise KeyError(f'Key Error: {key}')
def __setitem__(
self,
key: Hashable,
value: object,
# Superclass methods efficiently localized as default parameters.
__contains=dict.__contains__,
__delitem=dict.__delitem__,
__pushitem=dict.__setitem__,
__iter=dict.__iter__,
__len=dict.__len__,
) -> None:
'''
Cache this key-value pair while preserving size constraints.
Parameters
----------
key : Hashable
Arbitrary hashable key to cache this value to.
value : object
Arbitrary value to be cached under this key.
Raises
----------
TypeError
If this key is not hashable.
'''
with self._lock:
if __contains(self, key):
__delitem(self, key)
__pushitem(self, key, value)
# Prune this cache.
if __len(self) > self._size:
__delitem(self, next(__iter(self)))
def __contains__(
self,
key: Hashable,
# Superclass methods efficiently localized as default parameters.
__contains=dict.__contains__,
__getitem=dict.__getitem__,
__delitem=dict.__delitem__,
__pushitem=dict.__setitem__,
) -> bool:
'''
Return a boolean indicating whether this key is cached.
If this key is cached, this method implicitly refreshes this key by
popping and pushing this key back onto the top of this cache.
Parameters
----------
key : Hashable
Arbitrary hashable key to detect the existence of.
Returns
----------
bool
``True`` only if this key is cached.
Raises
----------
TypeError
If this key is unhashable.
'''
with self._lock:
if __contains(self, key):
val = __getitem(self, key)
__delitem(self, key)
__pushitem(self, key, val)
return True
return False
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **key pool type** (i.e., object caching class implemented as a
dictionary of lists of arbitrary objects to be cached, where objects cached to
the same list are typically of the same type).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: Conditionally pass "is_debug=True" to the KeyPool.{acquire,release}()
#methods defined below when the "BeartypeConfig.is_debug" parameter is "True"
#for the current call to the @beartype decorator, please.
#FIXME: Optimize the KeyPool.{acquire,release}() methods defined below. Rather
#than unconditionally wrapping the bodies of each in a thread-safe
#"self._thread_lock" context manager, we might be able to leverage the GIL by
#only doing so "if threading.active_count():". Profile us up, please.
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCachedKeyPoolException
from beartype.typing import (
Dict,
Union,
)
from collections import defaultdict
from collections.abc import Callable, Hashable
from threading import Lock
# ....................{ CLASSES }....................
class KeyPool(object):
'''
Thread-safe **key pool** (i.e., object cache implemented as a dictionary of
lists of arbitrary objects to be cached, where objects cached to the same
list are typically of the same type).
Key pools are thread-safe by design and thus safely usable as module-scoped
globals accessed from module-scoped callables.
Attributes
----------
_key_to_pool : defaultdict
Dictionary mapping from an **arbitrary key** (i.e., hashable object) to
corresponding **pool** (i.e., list of zero or more arbitrary objects
referred to as "pool items" cached under that key). For both efficiency
and simplicity, this dictionary is defined as a :class:`defaultdict`
implicitly initializing missing keys on initial access to the empty
list.
_pool_item_id_to_is_acquired : dict
Dictionary mapping from the unique object identifier of a **pool item**
(i.e., arbitrary object cached under a pool of the :attr:`_key_to_pool`
ditionary) to a boolean that is either:
* `True` if that item is currently **acquired** (i.e., most recently
returned by a call to the :meth:`acquire` method).
* `False` if that item is currently **released** (i.e., most recently
passed to a call to the :meth:`release` method).
_pool_item_maker : Callable
Caller-defined factory callable internally called by the
:meth:`acquire` method on attempting to acquire a non-existent object
from an **empty pool. See :meth:`__init__` for further details.
_thread_lock : Lock
**Non-reentrant instance-specific thread lock** (i.e., low-level thread
locking mechanism implemented as a highly efficient C extension,
defined as an instance variable for non-reentrant reuse by the public
API of this class). Although CPython, the canonical Python interpreter,
*does* prohibit conventional multithreading via its Global Interpreter
Lock (GIL), CPython still coercively preempts long-running threads at
arbitrary execution points. Ergo, multithreading concerns are *not*
safely ignorable -- even under CPython.
'''
# ..................{ CLASS VARIABLES }..................
# Slot all instance variables defined on this object to minimize the time
# complexity of both reading and writing variables across frequently called
# @beartype decorations. Slotting has been shown to reduce read and write
# costs by approximately ~10%, which is non-trivial.
__slots__ = (
'_key_to_pool',
'_pool_item_id_to_is_acquired',
'_pool_item_maker',
'_thread_lock',
)
# ..................{ INITIALIZER }..................
def __init__(
self,
item_maker: Union[type, Callable],
) -> None:
'''
Initialize this key pool with the passed factory callable.
Parameters
----------
item_maker : Union[type, Callable[[Hashable,], Any]]
Caller-defined factory callable internally called by the
:meth:`acquire` method on attempting to acquire a non-existent
object from an **empty pool** (i.e., either a missing key *or* an
empty list of an existing key of the underlying
:attr:`_key_to_pool` dictionary). That method initializes the empty
pool in question by calling this factory with the key associated
with that pool and appending the object created and returned by
this factory to that pool. This factory is thus expected to have a
signature resembling:
.. code-block:: python
from collections.abc import Hashable
def item_maker(key: Hashable) -> object: ...
'''
assert callable(item_maker), f'{repr(item_maker)} not callable.'
# Classify these parameters as instance variables.
self._pool_item_maker = item_maker
# Initialize all remaining instance variables.
#
# Note that "defaultdict" instances *MUST* be initialized with
# positional rather than keyword parameters. For unknown reasons,
# initializing such an instance with a keyword parameter causes that
# instance to silently behave like a standard dictionary instead: e.g.,
#
# >>> dd = defaultdict(default_factory=list)
# >>> dd['ee']
# KeyError: 'ee'
self._key_to_pool: Dict[Hashable, list] = defaultdict(list)
self._pool_item_id_to_is_acquired: Dict[int, bool] = {}
self._thread_lock = Lock()
# ..................{ METHODS }..................
def acquire(
self,
# Optional parameters.
key: Hashable = None,
is_debug: bool = False,
) -> object:
'''
Acquire an arbitrary object associated with the passed **arbitrary
key** (i.e., hashable object).
Specifically, this method tests whether there exists a non-empty list
previously associated with this key. If so, this method pops the last
item from that list and returns that item; else (i.e., if there either
exists no such list or such a list exists but is empty), this method
effectively (in order):
#. If no such list exists, create a new empty list associated with
this key.
#. Create a new object to be returned by calling the user-defined
:meth:`_pool_item_maker` factory callable.
#. Append this object to this list.
#. Add/Update acquisition state of the object to True
#. Returns this object.
Parameters
----------
key : Optional[HashableType]
Hashable object associated with the pool item to be acquired.
Defaults to ``None``.
is_debug : bool, optional
``True`` only if enabling inefficient debugging logic. Notably,
enabling this option notes this item to have now been acquired.
Defaults to ``False``.
Returns
----------
object
Pool item associated with this hashable object.
Raises
----------
TypeError
If this key is unhashable and thus *not* a key.
'''
# In a thread-safe manner...
with self._thread_lock:
#FIXME: This logic can *PROBABLY* be optimized into:
# if not is_debug:
# try:
# return self._key_to_pool[key].pop()
# except IndexError:
# return self._pool_item_maker(key)
# else:
# try:
# pool_item = self._key_to_pool[key].pop()
# except IndexError:
# pool_item = self._pool_item_maker(key)
#
# # Record this item to have now been acquired.
# self._pool_item_id_to_is_acquired[id(pool_item)] = True
#
# return pool_item
#
#That said, this introduces additional complexity that will require
#unit testing. So, only do so if the above is actually profiled as
#being faster. It almost certainly is, but let's be certain please.
# List associated with this key.
#
# If this is the first access of this key, this "defaultdict"
# implicitly creates a new list and associates this key with that
# list; else, this is the list previously associated with this key.
#
# Note that this statement implicitly raises a "TypeError"
# exception if this key is unhashable, which is certainly more
# efficient than our explicitly validating this constraint.
pool = self._key_to_pool[key]
# Pool item associated with this key, defined as either...
pool_item = (
# The last item popped (i.e., removed) from this list...
pool.pop()
# If the list associated with this key is non-empty (i.e., this
# method has been called less frequently than the corresponding
# release() method for this key);
if pool else
# Else, the list associated with this key is empty (i.e., this
# method has been called more frequently than the release()
# method for this key). In this case, an arbitrary object
# associated with this key.
self._pool_item_maker(key)
)
# If debugging, record this item to have now been acquired.
if is_debug:
self._pool_item_id_to_is_acquired[id(pool_item)] = True
# Return this item.
return pool_item
def release(
self,
# Mandatory parameters.
item: object,
# Optional parameters.
key: Hashable = None,
is_debug: bool = False,
) -> None:
'''
Release the passed object acquired by a prior call to the
:meth:`acquire` method passed the same passed **arbitrary key** (i.e.,
hashable object).
Specifically, this method tests whether there exists a list
previously associated with this key. If not, this method creates a new
empty list associated with this key. In either case, this method then
appends this object to this list.
Parameters
----------
item : object
Arbitrary object previously associated with this key.
key : Optional[HashableType]
Hashable object previously associated with this pool item. Defaults
to ``None``.
is_debug : bool, optional
``True`` only if enabling inefficient debugging logic. Notably,
enabling this option raises an exception if this item was *not*
previously acquired. Defaults to ``False``.
Raises
----------
TypeError
If this key is unhashable (i.e. *not* a key).
_BeartypeUtilCachedKeyPoolException
If debugging *and* this pool item was not acquired (i.e., returned
by a prior call to the :meth:`acquire` method), in which case this
item is ineligible for release.
'''
# In a thread-safe manner...
with self._thread_lock:
# If debugging...
if is_debug:
# Integer uniquely identifying this previously acquired pool
# item.
item_id = id(item)
# If this item was *NOT* previously acquired, raise an
# exception.
if not self._pool_item_id_to_is_acquired.get(item_id, False):
raise _BeartypeUtilCachedKeyPoolException(
f'Unacquired key pool item {repr(item)} '
f'not releasable.'
)
# Record this item to have now been released.
self._pool_item_id_to_is_acquired[item_id] = False
# Append this item to the pool associated with this key.
self._key_to_pool[key].append(item)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Fixed list pool** (i.e., submodule whose thread-safe API caches previously
instantiated :class:`list` subclasses constrained to fixed lengths defined at
instantiation time of various lengths for space- and time-efficient reuse
by the :func:`beartype.beartype` decorator across decoration calls).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: Consider submitting the "FixedList" type as a relevant StackOverflow
#answer here:
# https://stackoverflow.com/questions/10617045/how-to-create-a-fix-size-list-in-python
# https://stackoverflow.com/questions/51558015/implementing-efficient-fixed-size-fifo-in-python
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCachedFixedListException
from beartype.typing import NoReturn
from beartype._util.cache.pool.utilcachepool import KeyPool
from beartype._util.text.utiltextrepr import represent_object
# ....................{ CONSTANTS }....................
FIXED_LIST_SIZE_MEDIUM = 256
'''
Reasonably large length to constrain acquired and released fixed lists to.
This constant is intended to be passed to the :func:`acquire_fixed_list`
function, which then returns a fixed list of this length suitable for use in
contexts requiring a "reasonably large" list -- where "reasonably" and "large"
are both subjective but *should* cover 99.9999% of use cases in this codebase.
'''
# ....................{ CLASSES }....................
class FixedList(list):
'''
**Fixed list** (i.e., :class:`list` constrained to a fixed length defined
at instantiation time).**
A fixed list is effectively a mutable tuple. Whereas a tuple is immutable
and thus prohibits changes to its contained items, a fixed list is mutable
and thus *permits* changes to its contained items.
Design
----------
This list enforces this constraint by overriding *all* :class:`list` dunder
and standard methods that would otherwise modify the length of this list
(e.g., :meth:`list.__delitem__`, :meth:`list.append`) to instead
unconditionally raise an :class:`_BeartypeUtilCachedFixedListException`
exception.
'''
# ..................{ CLASS VARIABLES }..................
# Slot all instance variables defined on this object to minimize the time
# complexity of both reading and writing variables across frequently
# called @beartype decorations. Slotting has been shown to reduce read and
# write costs by approximately ~10%, which is non-trivial.
__slots__ = ()
# ..................{ INITIALIZER }..................
def __init__(self, size: int) -> None:
'''
Initialize this fixed list to the passed length and all items of this
fixed list to ``None``.
Parameters
----------
size : IntType
Length to constrain this fixed list to.
Raises
----------
_BeartypeUtilCachedFixedListException
If this length is either not an integer *or* is but is
**non-positive** (i.e., is less than or equal to 0).
'''
# If this length is *NOT* an integer, raise an exception.
if not isinstance(size, int):
raise _BeartypeUtilCachedFixedListException(
f'Fixed list length {repr(size)} not integer.')
# Else, this length is an integer.
# If this length is non-positive, raise an exception.
if size <= 0:
raise _BeartypeUtilCachedFixedListException(
f'Fixed list length {size} <= 0.')
# Else, this length is positive.
# Make it so with the standard Python idiom for preallocating list
# space -- which, conveniently, is also the optimally efficient means
# of doing so. See also the timings in this StackOverflow answer:
# https://stackoverflow.com/a/10617221/2809027
super().__init__([None]*size)
# ..................{ GOOD ~ non-dunders }..................
# Permit non-dunder methods preserving list length but otherwise requiring
# overriding.
def copy(self) -> 'FixedList':
# Nullified fixed list of the same length as this fixed list.
list_copy = FixedList(len(self))
# Slice over the nullified contents of this copy with those of this
# fixed list.
list_copy[:] = self
# Return this copy.
return list_copy
# ..................{ BAD ~ dunders }..................
# Prohibit dunder methods modifying list length by overriding these methods
# to raise exceptions.
def __delitem__(self, index) -> NoReturn:
raise _BeartypeUtilCachedFixedListException(
f'{self._label} index {repr(index)} not deletable.')
def __iadd__(self, value) -> NoReturn: # type: ignore[misc]
raise _BeartypeUtilCachedFixedListException(
f'{self._label} not addable by {represent_object(value)}.')
def __imul__(self, value) -> NoReturn: # type: ignore[misc]
raise _BeartypeUtilCachedFixedListException(
f'{self._label} not multipliable by {represent_object(value)}.')
# ..................{ BAD ~ dunders : setitem }..................
#FIXME: Great idea, if efficiency didn't particularly matter. Since
#efficiency is the entire raison d'etre of this class, however, this method
#has been temporarily and probably permanently disabled. Extensive
#profiling has shown this single method to substantially cost us elsewhere.
#Moreover, this method is only relevant in the context of preventing
#external callers who are *NOT* us from violating class constraints. No
#external callers exist, though! We are it. Since we know better, we won't
#violate class constraints by changing fixed list length with slicing.
#Moreover, it's unlikely we ever even assign list slices anywhere. *sigh*
# def __setitem__(self, index, value):
#
# # If these parameters indicate an external attempt to change the length
# # of this fixed length with slicing, raise an exception.
# self._die_if_slice_len_ne_value_len(index, value)
#
# # If this index is a tuple of 0-based indices and slice objects...
# if isinstance(index, Iterable):
# # For each index or slice in this tuple...
# for subindex in index:
# # If these parameters indicate an external attempt to change
# # the length of this fixed length with slicing, raise an
# # exception.
# self._die_if_slice_len_ne_value_len(subindex, value)
#
# # Else, this list is either not being sliced or is but is being set to
# # an iterable of the same length as that slice. In either case, this
# # operation preserves the length of this list and is thus acceptable.
# return super().__setitem__(index, value)
#FIXME: Disabled as currently only called by __setitem__(). *sigh*
# def _die_if_slice_len_ne_value_len(self, index, value) -> None:
# '''
# Raise an exception only if the passed parameters when passed to the
# parent :meth:`__setitem__` dunder method signify an external attempt to
# change the length of this fixed length with slicing.
#
# This function is intended to be called by the :meth:`__setitem__`
# dunder method to validate the passed parameters.
#
# Parameters
# ----------
# index
# 0-based index, slice object, or tuple of 0-based indices and slice
# objects to index this fixed list with.
# value
# Object to set this index(s) of this fixed list to.
#
# Raises
# ----------
# _BeartypeUtilCachedFixedListException
# If this index is a **slice object** (i.e., :class:`slice` instance
# underlying slice syntax) and this value is either:
#
# * **Unsized** (i.e., unsupported by the :func:`len` builtin).
# * Sized but has a length differing from that of this fixed list.
# '''
#
# # If this index is *NOT* a slice, silently reduce to a noop.
# if not isinstance(index, slice):
# return
# # Else, this index is a slice.
# #
# # If this value is *NOT* a sized container, raise an exception.
# elif not isinstance(value, Sized):
# raise _BeartypeUtilCachedFixedListException(
# f'{self._label} slice {repr(index)} not settable to unsized '
# f'{represent_object(value)}.'
# )
# # Else, this value is a sized container.
#
# # 0-based first and one-past-the-last indices sliced by this slice.
# start, stop_plus_one, _ = index.indices(len(self))
#
# # Number of items of this fixed list sliced by this slice. By
# # definition, this is guaranteed to be a non-negative integer.
# slice_len = stop_plus_one - start
#
# # Number of items of this sized container to set this slice to.
# value_len = len(value)
#
# # If these two lengths differ, raise an exception.
# if slice_len != value_len:
# raise _BeartypeUtilCachedFixedListException(
# f'{self._label} slice {repr(index)} of length {slice_len} not '
# f'settable to {represent_object(value)} of differing '
# f'length {value_len}.'
# )
# ..................{ BAD ~ non-dunders }..................
# Prohibit non-dunder methods modifying list length by overriding these
# methods to raise exceptions.
def append(self, obj) -> NoReturn:
raise _BeartypeUtilCachedFixedListException(
f'{self._label} not appendable by {represent_object(obj)}.')
def clear(self) -> NoReturn:
raise _BeartypeUtilCachedFixedListException(
f'{self._label} not clearable.')
def extend(self, obj) -> NoReturn:
raise _BeartypeUtilCachedFixedListException(
f'{self._label} not extendable by {represent_object(obj)}.')
def pop(self, *args) -> NoReturn:
raise _BeartypeUtilCachedFixedListException(
f'{self._label} not poppable.')
def remove(self, *args) -> NoReturn:
raise _BeartypeUtilCachedFixedListException(
f'{self._label} not removable.')
# ..................{ PRIVATE ~ property }..................
# Read-only properties intentionally prohibiting mutation.
@property
def _label(self) -> str:
'''
Human-readable representation of this fixed list trimmed to a
reasonable length.
This string property is intended to be interpolated into exception
messages and should probably *not* be called in contexts where
efficiency is a valid concern.
'''
# One-liners for magnanimous pusillanimousness.
return f'Fixed list {represent_object(self)}'
# ....................{ PRIVATE ~ factories }....................
_fixed_list_pool = KeyPool(item_maker=FixedList)
'''
Thread-safe **fixed list pool** (i.e., :class:`KeyPool` singleton caching
previously instantiated :class:`FixedList` instances of various lengths).
Caveats
----------
**Avoid accessing this private singleton externally.** Instead, call the public
:func:`acquire_fixed_list` and :func:`release_fixed_list` functions, which
efficiently validate both input *and* output to conform to sane expectations.
'''
# ....................{ (ACQUIRERS|RELEASERS) }....................
def acquire_fixed_list(size: int) -> FixedList:
'''
Acquire an arbitrary **fixed list** (i.e., :class:`list` constrained to a
fixed length defined at instantiation time) with the passed length.
Caveats
----------
**The contents of this list are arbitrary.** Callers should make *no*
assumptions as to this list's initial items, but should instead
reinitialize this list immediately after acquiring this list with standard
list slice syntax: e.g.,
>>> from beartype._util.cache.pool.utilcachepoollistfixed import (
... acquire_fixed_list)
>>> fixed_list = acquire_fixed_list(size=5)
>>> fixed_list[:] = ('Dirty', 'Deads', 'Done', 'Dirt', 'Cheap',)
Parameters
----------
size : int
Length to constrain the fixed list to be acquired to.
Returns
----------
FixedList
Arbitrary fixed list with this length.
Raises
----------
_BeartypeUtilCachedFixedListException
If this length is either not an integer *or* is but is
**non-positive** (i.e., is less than or equal to 0).
'''
# Note that the FixedList.__init__() method already validates this "size"
# parameter to be an integer.
# Thread-safely acquire a fixed list of this length.
fixed_list = _fixed_list_pool.acquire(size)
assert isinstance(fixed_list, FixedList), (
f'{repr(fixed_list)} not fixed list.')
# Return this list.
return fixed_list
def release_fixed_list(fixed_list: FixedList) -> None:
'''
Release the passed fixed list acquired by a prior call to the
:func:`acquire_fixed_list` function.
Caveats
----------
**This list is not safely accessible after calling this function.** Callers
should make *no* attempts to read, write, or otherwise access this list,
but should instead nullify *all* variables referring to this list
immediately after releasing this list (e.g., by setting these variables to
the ``None`` singleton *or* by deleting these variables): e.g.,
>>> from beartype._util.cache.pool.utilcachepoollistfixed import (
... acquire_fixed_list, release_fixed_list)
>>> fixed_list = acquire_fixed_list(size=7)
>>> fixed_list[:] = ('If', 'You', 'Want', 'Blood', "You've", 'Got', 'It',)
>>> release_fixed_list(fixed_list)
# Either do this...
>>> fixed_list = None
# Or do this.
>>> del fixed_list
Parameters
----------
fixed_list : FixedList
Previously acquired fixed list to be released.
'''
assert isinstance(fixed_list, FixedList), (
f'{repr(fixed_list)} not fixed list.')
# Thread-safely release this fixed list.
_fixed_list_pool.release(key=len(fixed_list), item=fixed_list)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Typed object pool** (i.e., submodule whose thread-safe API caches previously
instantiated objects of arbitrary types for space- and time-efficient reuse by
the :func:`beartype.beartype` decorator across decoration calls).
This private submodule is *not* intended for importation by downstream callers.
Caveats
----------
**This submodule only pools objects defining an** ``__init__()`` **method
accepting no parameters.** Why? Because this submodule unconditionally pools
all objects of the same types under those types. This submodule provides *no*
mechanism for pooling objects of the same types under different parameters
instantiated with those parameters and thus only implements a coarse- rather
than fine-grained object cache. If insufficient, consider defining a new
submodule implementing a fine-grained object cache unique to those objects. For
example:
* This submodule unconditionally pools all instances of the
:class:`beartype._check.checkcall.BeartypeCall` class under that type.
* The parallel :mod:`beartype._util.cache.pool.utilcachepoollistfixed`
submodule conditionally pools every instance of the
:class:`beartype._util.cache.pool.utilcachepoollistfixed.FixedList` class of
the same length under that length.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCachedObjectTypedException
from beartype.typing import Any
from beartype._util.cache.pool.utilcachepool import KeyPool
# ....................{ SINGLETONS ~ private }....................
_object_typed_pool = KeyPool(item_maker=lambda cls: cls())
'''
Thread-safe **typed object pool** (i.e., :class:`KeyPool` singleton caching
previously instantiated objects of the same types under those types).
Caveats
----------
**Avoid accessing this private singleton externally.** Instead, call the public
:func:`acquire_object_typed` and :func:`release_object_typed` functions, which
efficiently validate both input *and* output to conform to sane expectations.
'''
# ....................{ (ACQUIRERS|RELEASERS) }....................
def acquire_object_typed(cls: type) -> Any:
'''
Acquire an arbitrary object of the passed type.
Caveats
----------
**The contents of this object are arbitrary.** Callers should make *no*
assumptions as to this object's state, but should instead reinitialize this
object immediately after acquiring this object.
Parameters
----------
cls : type
Type of the object to be acquired.
Returns
----------
object
Arbitrary object of this type.
Raises
----------
_BeartypeUtilCachedObjectTypedException
If this type is *not* actually a type.
'''
# If this type is *NOT* actually a type, raise an exception.
if not isinstance(cls, type):
raise _BeartypeUtilCachedObjectTypedException(
'{!r} not a class.'.format(cls))
# Thread-safely acquire an object of this type.
object_typed = _object_typed_pool.acquire(cls)
assert isinstance(object_typed, cls), (
'{!r} not a {!r}.'.format(object_typed, cls))
# Return this object.
return object_typed
def release_object_typed(obj: Any) -> None:
'''
Release the passed object acquired by a prior call to the
:func:`acquire_object_typed` function.
Caveats
----------
**This object is not safely accessible after calling this function.**
Callers should make *no* attempts to read, write, or otherwise access this
object, but should instead nullify *all* variables referring to this object
immediately after releasing this object (e.g., by setting these variables
to the ``None`` singleton *or* by deleting these variables).
Parameters
----------
obj : object
Previously acquired object to be released.
'''
# Thread-safely release this object.
_object_typed_pool.release(key=obj.__class__, item=obj)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **class testers** (i.e., low-level callables testing and validating
various properties of arbitrary classes).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilTypeException
from beartype._cave._cavefast import TestableTypes as TestableTypesTuple
from beartype._data.cls.datacls import TYPES_BUILTIN_FAKE
from beartype._data.mod.datamodpy import BUILTINS_MODULE_NAME
from beartype._data.datatyping import (
TypeException,
TypeOrTupleTypes,
)
# ....................{ VALIDATORS }....................
def die_unless_type(
# Mandatory parameters.
cls: object,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilTypeException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception of the passed type unless the passed object is a class.
Parameters
----------
cls : object
Object to be validated.
exception_cls : Type[Exception]
Type of exception to be raised. Defaults to
:exc:`_BeartypeUtilTypeException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this object is *not* a class.
'''
# If this object is *NOT* a class, raise an exception.
if not isinstance(cls, type):
assert isinstance(exception_cls, type), (
'f{repr(exception_cls)} not exception class.')
assert isinstance(exception_prefix, str), (
'f{repr(exception_prefix)} not string.')
raise exception_cls(f'{exception_prefix}{repr(cls)} not class.')
#FIXME: Unit test us up.
def die_unless_type_or_types(
# Mandatory parameters.
type_or_types: object,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilTypeException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception of the passed type unless the passed object is either a
class *or* tuple of one or more classes.
Parameters
----------
type_or_types : object
Object to be validated.
exception_cls : Type[Exception]
Type of exception to be raised. Defaults to
:exc:`_BeartypeUtilTypeException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If this object is neither a class *nor* tuple of one or more classes.
'''
# If this object is neither a class *NOR* tuple of one or more classes,
# raise an exception.
if not is_type_or_types(type_or_types):
assert isinstance(exception_cls, type), (
'f{repr(exception_cls)} not exception class.')
assert issubclass(exception_cls, Exception), (
f'{repr(exception_cls)} not exception subclass.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Exception message to be raised below.
exception_message = (
f'{exception_prefix}{repr(type_or_types)} neither '
f'class nor tuple of one or more classes'
)
# If this object is a tuple...
if isinstance(type_or_types, tuple):
# If this tuple is empty, note that.
if not type_or_types:
exception_message += ' (i.e., is empty tuple)'
# Else, this tuple is non-empty. In this case...
else:
# For the 0-based index of each tuple item and that item...
for cls_index, cls in enumerate(type_or_types):
# If this object is *NOT* a class...
if not isinstance(cls, type):
# Note this.
exception_message += (
f' (i.e., tuple item {cls_index} '
f'{repr(cls)} not class)'
)
# Halt iteration.
break
# Else, this object is a class. Continue to the next item.
# Else, this object is a non-tuple. In this case, the general-purpose
# exception message suffices.
# Raise this exception.
raise exception_cls(f'{exception_message}.')
# ....................{ TESTERS }....................
def is_type_or_types(type_or_types: object) -> bool:
'''
``True`` only if the passed object is either a class *or* tuple of one or
more classes.
Parameters
----------
type_or_types : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is either a class *or* tuple of one or
more classes.
'''
# Return true only if either...
return (
# This object is a class *OR*...
isinstance(type_or_types, type) or
(
# This object is a tuple *AND*...
isinstance(type_or_types, tuple) and
# This tuple is non-empty *AND*...
bool(type_or_types) and
# This tuple contains only classes.
all(isinstance(cls, type) for cls in type_or_types)
)
)
def is_type_builtin(
# Mandatory parameters.
cls: type,
# Optional parameters.
is_ignore_fake: bool = True,
) -> bool:
'''
``True`` only if the passed class is **builtin** (i.e., globally accessible
C-based type requiring *no* explicit importation).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
cls : type
Class to be inspected.
is_ignore_fake : bool
``True`` only if this tester intentionally ignores **fake builtin
types** (i.e., types that are *not* builtin but nonetheless erroneously
masquerade as being builtin, which includes the type of the :data:`None`
singleton). Defaults to ``True``.
Returns
----------
bool
``True`` only if this class is builtin.
Raises
----------
_BeartypeUtilTypeException
If this object is *not* a class.
'''
assert isinstance(is_ignore_fake, bool), (
f'{repr(is_ignore_fake)} not boolean.')
# Avoid circular import dependencies.
from beartype._util.mod.utilmodget import (
get_object_type_module_name_or_none)
# If this object is *NOT* a type, raise an exception.
die_unless_type(cls)
# Else, this object is a type.
# If ignoring fake builtin types *AND* this type is such a type, this type
# is *NOT* a builtin. In this case, silently reject this type.
if is_ignore_fake and cls in TYPES_BUILTIN_FAKE:
return False
# Else, this type is *NOT* a fake builtin.
# Fully-qualified name of the module defining this type if this type is
# defined by a module *OR* "None" otherwise (i.e., if this type is
# dynamically defined in-memory).
cls_module_name = get_object_type_module_name_or_none(cls)
# This return true only if this name is that of the "builtins" module
# declaring all builtin types.
return cls_module_name == BUILTINS_MODULE_NAME
# ....................{ TESTERS ~ subclass }....................
def is_type_subclass(
cls: object, base_classes: TypeOrTupleTypes) -> bool:
'''
``True`` only if the passed object is an inclusive subclass of the passed
superclass(es).
Specifically, this tester returns ``True`` only if either:
* If ``base_classes`` is a single superclass, the passed class is either:
* That superclass itself *or*...
* A subclass of that superclass.
* Else, ``base_classes`` is a tuple of one or more superclasses. In this
case, the passed class is either:
* One of those superclasses themselves *or*...
* A subclass of one of those superclasses.
Caveats
----------
**This higher-level tester should always be called in lieu of the
lower-level** :func:`issubclass` **builtin,** which raises an undescriptive
exception when the first passed parameter is *not* a class: e.g.,
.. code-block:: python
>>> issubclass(object(), type)
TypeError: issubclass() arg 1 must be a class
This tester suffers no such deficits, instead safely returning ``False``
when the first passed parameter is *not* a class.
Parameters
----------
obj : object
Object to be inspected.
base_classes : TestableTypes
Superclass(es) to test whether this object is a subclass of defined as
either:
* A single class.
* A tuple of one or more classes.
Returns
----------
bool
``True`` only if this object is an inclusive subclass of these
superclass(es).
'''
assert isinstance(base_classes, TestableTypesTuple), (
f'{repr(base_classes)} neither class nor tuple of classes.')
# Return true only if...
return (
# This object is a class *AND*...
isinstance(cls, type) and
# This class either is this superclass(es) or a subclass of this
# superclass(es).
issubclass(cls, base_classes)
)
#FIXME: Unit test us up, please.
def is_type_subclass_proper(
cls: object, base_classes: TypeOrTupleTypes) -> bool:
'''
``True`` only if the passed object is a proper subclass of the passed
superclass(es).
Specifically, this tester returns ``True`` only if either:
* If ``base_classes`` is a single superclass, the passed class is a subclass
of that superclass (but *not* that superclass itself).
* Else, ``base_classes`` is a tuple of one or more superclasses. In this
case, the passed class is a subclass of one of those superclasses (but
*not* one of those superclasses themselves).
Parameters
----------
obj : object
Object to be inspected.
base_classes : TestableTypes
Superclass(es) to test whether this object is a subclass of defined as
either:
* A single class.
* A tuple of one or more classes.
Returns
----------
bool
``True`` only if this object is a proper subclass of these
superclass(es).
'''
assert isinstance(base_classes, TestableTypesTuple), (
f'{repr(base_classes)} neither class nor tuple of classes.')
# Return true only if...
return (
# This object is a class *AND*...
isinstance(cls, type) and
# This class either is this superclass(es) or a subclass of this
# superclass(es) *AND*...
issubclass(cls, base_classes) and
# It is *NOT* the case that...
not (
# If the caller passed a tuple of one or more superclasses, this
# class is one of these superclasses themselves;
cls in base_classes
if isinstance(base_classes, tuple) else
# Else, the caller passed a single superclass. In this case, this
# class is this superclass itself.
cls is base_classes
)
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **class getters** (i.e., low-level callables querying for various
properties of arbitrary classes).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilTypeException
from beartype._data.datatyping import (
LexicalScope,
TypeException,
)
# ....................{ VALIDATORS }....................
#FIXME: Unit test us up, please.
def get_type_locals(
# Mandatory parameters.
cls: type,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilTypeException,
) -> LexicalScope:
'''
**Local scope** (i.e., dictionary mapping from the name to value of each
attribute directly declared by that class) for the passed class.
Caveats
----------
**This getter returns an immutable rather than mutable mapping.** Callers
requiring the latter are encouraged to manually coerce the immutable mapping
returned by this getter into a mutable mapping (e.g., by passing the former
to the :class:`dict` constructor as is).
Design
----------
This getter currently reduces to a trivial one-liner returning
``cls.__dict__`` and has thus been defined mostly just for orthogonality
with the comparable
:func:`beartype._util.func.utilfuncscope.get_func_locals` getter. That said,
:pep:`563` suggests this non-trivial heuristic for computing the local scope
of a given class:
For classes, localns can be composed by chaining vars of the given class
and its base classes (in the method resolution order). Since slots can
only be filled after the class was defined, we don’t need to consult
them for this purpose.
We fail to grok that suggestion, because we lack a galactic brain. A
minimal length example (MLE) refutes all of the above by demonstrating that
superclass attributes are *not* local to subclasses:
.. code-block:: python
>>> class Superclass(object):
... my_int = int
>>> class Subclass(Superclass):
... def get_str(self) -> my_int:
... return 'Oh, Gods.'
NameError: name 'my_int' is not defined
We are almost certainly confused about what :pep:`563` is talking about, but
we are almost certain that :pep:`536` is also confused about what :pep:`563`
is talking about. That said, the standard :func:`typing.get_type_hints`
getter implements that suggestion with iteration over the method-resolution
order (MRO) of the passed class resembling:
.. code-block:: python
for base in reversed(obj.__mro__):
...
base_locals = dict(vars(base)) if localns is None else localns
The standard :func:`typing.get_type_hints` getter appears to recursively
retrieve all type hints annotating both the passed class and all
superclasses of that class. Why? We have no idea, frankly. We're unconvinced
that is useful in practice. We prefer a trivial one-liner, which behaves
exactly as advertised and efficiently at decoration-time.
Parameters
----------
cls : type
Class to be inspected.
exception_cls : Type[Exception]
Type of exception to be raised. Defaults to
:exc:`_BeartypeUtilTypeException`.
Returns
----------
LexicalScope
Local scope for this class.
Raises
----------
:exc:`exception_cls`
If the next non-ignored frame following the last ignored frame is *not*
the parent callable or module directly declaring the passed callable.
'''
assert isinstance(cls, type), f'{repr(cls)} not type.'
# Return the dictionary of class attributes bundled with this class.
return cls.__dict__ # type: ignore[return-value]
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`3119`-compliant **class detectors** (i.e., callables
validating and testing various properties of arbitrary classes standardized by
:pep:`3119`).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeDecorHintPep3119Exception
from beartype._data.datatyping import (
TypeException,
TypeOrTupleTypes,
)
# ....................{ VALIDATORS ~ instance }....................
def die_unless_type_isinstanceable(
# Mandatory parameters.
cls: type,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep3119Exception,
exception_prefix: str = '',
) -> None:
'''
Raise an exception of the passed type unless the passed object is an
**isinstanceable class** (i.e., class whose metaclass does *not* define an
``__instancecheck__()`` dunder method that raises an exception).
Classes that are *not* isinstanceable include most PEP-compliant type
hints, notably:
* **Generic aliases** (i.e., subscriptable classes overriding the
``__class_getitem__()`` class dunder method standardized by :pep:`560`
subscripted by an arbitrary object) under Python >= 3.9, whose
metaclasses define an ``__instancecheck__()`` dunder method to
unconditionally raise an exception. Generic aliases include:
* :pep:`484`-compliant **subscripted generics.**
* :pep:`585`-compliant type hints.
* User-defined classes whose metaclasses define an ``__instancecheck__()``
dunder method to unconditionally raise an exception, including:
* :pep:`544`-compliant protocols *not* decorated by the
:func:`typing.runtime_checkable` decorator.
Motivation
----------
When a class whose metaclass defines an ``__instancecheck__()`` dunder
method is passed as the second parameter to the :func:`isinstance` builtin,
that builtin defers to that method rather than testing whether the first
parameter passed to that builtin is an instance of that class. If that
method raises an exception, that builtin raises the same exception,
preventing callers from deciding whether arbitrary objects are instances
of that class. For brevity, we refer to that class as "non-isinstanceable."
Most classes are isinstanceable, because deciding whether arbitrary objects
are instances of those classes is a core prerequisite for object-oriented
programming. Most classes that are also PEP-compliant type hints, however,
are *not* isinstanceable, because they're *never* intended to be
instantiated into objects (and typically prohibit instantiation in various
ways); they're only intended to be referenced as type hints annotating
callables, an arguably crude form of callable markup.
:mod:`beartype`-decorated callables typically check the types of arbitrary
objects at runtime by passing those objects and types as the first and
second parameters to the :func:`isinstance` builtin. If those types are
non-isinstanceable, those type-checks will typically raise
non-human-readable exceptions (e.g., ``"TypeError: isinstance() argument 2
cannot be a parameterized generic"`` for :pep:`585`-compliant type hints).
This is non-ideal both because those exceptions are non-human-readable
*and* because those exceptions are raised at call rather than decoration
time, where users expect the :mod:`beartype.beartype` decorator to raise
exceptions for erroneous type hints.
Thus the existence of this function, which the :mod:`beartype.beartype`
decorator calls to validate the usability of type hints that are classes
*before* checking objects against those classes at call time.
Parameters
----------
cls : object
Object to be validated.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep3119Exception`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintPep3119Exception
If this object is *not* an isinstanceable class.
See Also
----------
:func:`die_unless_type_isinstanceable`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.cls.utilclstest import die_unless_type
# If this object is *NOT* a class, raise an exception.
die_unless_type(
cls=cls,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this object is a class.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with the is_type_or_types_isinstanceable() tester.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# If this class is *NOT* isinstanceable, raise an exception.
try:
isinstance(None, cls) # type: ignore[arg-type]
except Exception as exception:
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not exception class.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
#FIXME: Uncomment after we uncover why doing so triggers an
#infinite circular exception chain when "hint" is a "GenericAlias".
#It's clearly the is_hint_pep544_protocol() call, but why? In any
#case, the simplest workaround would just be to inline the logic of
#is_hint_pep544_protocol() here directly. Yes, we know. *shrug*
# # Human-readable exception message to be raised as either...
# exception_message = (
# # If this class is a PEP 544-compliant protocol, a message
# # documenting this exact issue and how to resolve it;
# (
# f'{exception_prefix}PEP 544 protocol {hint} '
# f'uncheckable at runtime (i.e., '
# f'not decorated by @typing.runtime_checkable).'
# )
# if is_hint_pep544_protocol(hint) else
# # Else, a fallback message documenting this general issue.
# (
# f'{exception_prefix}type {hint} uncheckable at runtime (i.e., '
# f'not passable as second parameter to isinstance() '
# f'due to raising "{exception}" from metaclass '
# f'__instancecheck__() method).'
# )
# )
# Exception message to be raised.
exception_message = (
f'{exception_prefix}{repr(cls)} uncheckable at runtime '
f'(i.e., not passable as second parameter to isinstance(), '
f'due to raising "{exception}" from metaclass '
f'__instancecheck__() method).'
)
# Raise this exception chained onto this lower-level exception.
raise exception_cls(exception_message) from exception
#FIXME: Unit test us up.
def die_unless_type_or_types_isinstanceable(
# Mandatory parameters.
type_or_types: TypeOrTupleTypes,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep3119Exception,
exception_prefix: str = '',
) -> None:
'''
Raise an exception of the passed type unless the passed object is either an
**isinstanceable class** (i.e., class whose metaclass does *not* define an
``__instancecheck__()`` dunder method that raises an exception) *or* tuple
of one or more isinstanceable classes.
Parameters
----------
type_or_types : object
Object to be validated.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep3119Exception`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintPep3119Exception
If this object is neither:
* An isinstanceable class.
* A tuple containing only isinstanceable classes.
'''
# Avoid circular import dependencies.
from beartype._util.cls.utilclstest import die_unless_type_or_types
# If this object is neither a class nor tuple of classes, raise an
# exception.
die_unless_type_or_types(
type_or_types=type_or_types,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this object is either a class or tuple of classes.
# If this object is a class...
if isinstance(type_or_types, type):
# If this class is *NOT* isinstanceable, raise an exception.
die_unless_type_isinstanceable(
cls=type_or_types,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this class is isinstanceable.
# Else, this object *MUST* (by process of elimination and the above
# validation) be a tuple of classes. In this case...
else:
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with the is_type_or_types_isinstanceable() tester.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# If this tuple of classes is *NOT* isinstanceable, raise an exception.
try:
isinstance(None, type_or_types) # type: ignore[arg-type]
except Exception as exception:
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not exception class.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Exception message to be raised.
exception_message = (
f'{exception_prefix}{repr(type_or_types)} '
f'uncheckable at runtime'
)
# For the 0-based index of each tuple class and that class...
for cls_index, cls in enumerate(type_or_types):
# If this class is *NOT* isinstanceable, raise an exception.
die_unless_type_isinstanceable(
cls=cls,
exception_cls=exception_cls,
exception_prefix=(
f'{exception_message}, as tuple item {cls_index} '),
)
# Else, this class is isinstanceable. Continue to the next.
# Raise this exception chained onto this lower-level exception.
# Although this should *NEVER* happen (as we should have already
# raised an exception above), we nonetheless do so for safety.
raise exception_cls(f'{exception_message}.') from exception
# ....................{ VALIDATORS ~ subclass }....................
def die_unless_type_issubclassable(
# Mandatory parameters.
cls: type,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep3119Exception,
exception_prefix: str = '',
) -> None:
'''
Raise an exception of the passed type unless the passed object is an
**issubclassable class** (i.e., class whose metaclass does *not* define a
``__subclasscheck__()`` dunder method that raises an exception).
Classes that are *not* issubclassable include most PEP-compliant type
hints, notably:
* **Generic aliases** (i.e., subscriptable classes overriding the
``__class_getitem__()`` class dunder method standardized by :pep:`560`
subscripted by an arbitrary object) under Python >= 3.9, whose
metaclasses define an ``__subclasscheck__()`` dunder method to
unconditionally raise an exception. Generic aliases include:
* :pep:`484`-compliant **subscripted generics.**
* :pep:`585`-compliant type hints.
* User-defined classes whose metaclasses define a ``__subclasscheck__()``
dunder method to unconditionally raise an exception, including:
* :pep:`544`-compliant protocols *not* decorated by the
:func:`typing.runtime_checkable` decorator.
Motivation
----------
When a class whose metaclass defines a ``__subclasscheck__()`` dunder
method is passed as the second parameter to the :func:`issubclass` builtin,
that builtin defers to that method rather than testing whether the first
parameter passed to that builtin is an subclass of that class. If that
method raises an exception, that builtin raises the same exception,
preventing callers from deciding whether arbitrary objects are subclasses
of that class. For brevity, we refer to that class as "non-issubclassable."
Most classes are issubclassable, because deciding whether arbitrary classes
are subclasses of those classes is a core prerequisite for object-oriented
programming. Most classes that are also PEP-compliant type hints, however,
are *not* issubclassable, because they're *never* intended to be
instantiated into objects (and typically prohibit instantiation in various
ways); they're only intended to be referenced as type hints annotating
callables, an arguably crude form of callable markup.
:mod:`beartype`-decorated callables typically check the superclasses of
arbitrary classes at runtime by passing those classes and superclasses as
the first and second parameters to the :func:`issubclass` builtin. If those
types are non-issubclassable, those type-checks will typically raise
non-human-readable exceptions (e.g., ``"TypeError: issubclass() argument 2
cannot be a parameterized generic"`` for :pep:`585`-compliant type hints).
This is non-ideal both because those exceptions are non-human-readable
*and* because those exceptions are raised at call rather than decoration
time, where users expect the :mod:`beartype.beartype` decorator to raise
exceptions for erroneous type hints.
Thus the existence of this function, which the :mod:`beartype.beartype`
decorator calls to validate the usability of type hints that are classes
*before* checking objects against those classes at call time.
Parameters
----------
cls : object
Object to be validated.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep3119Exception`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
BeartypeDecorHintPep3119Exception
If this object is *not* an issubclassable class.
'''
# Avoid circular import dependencies.
from beartype._util.cls.utilclstest import die_unless_type
# If this hint is *NOT* a class, raise an exception.
die_unless_type(
cls=cls,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this hint is a class.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with the is_type_or_types_issubclassable() tester.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
try:
issubclass(type, cls) # type: ignore[arg-type]
except Exception as exception:
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not exception class.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Exception message to be raised.
exception_message = (
f'{exception_prefix}{repr(cls)} uncheckable at runtime '
f'(i.e., not passable as second parameter to issubclass(), '
f'due to raising "{exception}" from metaclass '
f'__subclasscheck__() method).'
)
# Raise this exception chained onto this lower-level exception.
raise exception_cls(exception_message) from exception
#FIXME: Unit test us up.
def die_unless_type_or_types_issubclassable(
# Mandatory parameters.
type_or_types: TypeOrTupleTypes,
# Optional parameters.
exception_cls: TypeException = BeartypeDecorHintPep3119Exception,
exception_prefix: str = '',
) -> None:
'''
Raise an exception of the passed type unless the passed object is either an
**issubclassable class** (i.e., class whose metaclass does *not* define an
``__subclasscheck__()`` dunder method that raises an exception) *or* tuple
of one or more issubclassable classes.
Parameters
----------
type_or_types : object
Object to be validated.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:exc:`BeartypeDecorHintPep3119Exception`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`BeartypeDecorHintPep3119Exception`
If this object is neither:
* An issubclassable class.
* A tuple containing only issubclassable classes.
'''
# Avoid circular import dependencies.
from beartype._util.cls.utilclstest import die_unless_type_or_types
# If this object is neither a class nor tuple of classes, raise an
# exception.
die_unless_type_or_types(
type_or_types=type_or_types,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this object is either a class or tuple of classes.
# If this object is a class...
if isinstance(type_or_types, type):
# If this class is *NOT* issubclassable, raise an exception.
die_unless_type_issubclassable(
cls=type_or_types,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this class is issubclassable.
# Else, this object *MUST* (by process of elimination and the above
# validation) be a tuple of classes. In this case...
else:
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with the is_type_or_types_issubclassable() tester.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# If this tuple of classes is *NOT* issubclassable, raise an exception.
try:
issubclass(type, type_or_types) # type: ignore[arg-type]
except Exception as exception:
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not exception class.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Exception message to be raised.
exception_message = (
f'{exception_prefix}{repr(type_or_types)} '
f'uncheckable at runtime'
)
# For the 0-based index of each tuple class and that class...
for cls_index, cls in enumerate(type_or_types):
# If this class is *NOT* issubclassable, raise an exception.
die_unless_type_issubclassable(
cls=cls,
exception_cls=exception_cls,
exception_prefix=(
f'{exception_message}, as tuple item {cls_index} '),
)
# Else, this class is issubclassable. Continue to the next.
# Raise this exception chained onto this lower-level exception.
# Although this should *NEVER* happen (as we should have already
# raised an exception above), we nonetheless do so for safety.
raise exception_cls(f'{exception_message}.') from exception
# ....................{ TESTERS }....................
def is_type_or_types_isinstanceable(cls: object) -> bool:
'''
``True`` only if the passed object is either an **isinstanceable class**
(i.e., class whose metaclass does *not* define an ``__instancecheck__()``
dunder method that raises an exception) *or* tuple containing only
isinstanceable classes.
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator). Although the implementation does *not*
trivially reduce to an efficient one-liner, the inefficient branch of this
implementation *only* applies to erroneous edge cases resulting in raised
exceptions and is thus largely ignorable.
Caveats
----------
**This tester may return false positives in unlikely edge cases.**
Internally, this tester tests whether this class is isinstanceable by
detecting whether passing the ``None`` singleton and this class to the
:func:`isinstance` builtin raises an exception. If that call raises *no*
exception, this class is probably but *not* necessarily isinstanceable.
Since the metaclass of this class could define an ``__instancecheck__()``
dunder method to conditionally raise exceptions *except* when passed the
``None`` singleton, there exists *no* perfect means of deciding whether an
arbitrary class is fully isinstanceable in the general sense. Since most
classes that are *not* isinstanceable are unconditionally isinstanceable
(i.e., the metaclasses of those classes define an ``__instancecheck__()``
dunder method to unconditionally raise exceptions), this distinction is
generally meaningless in the real world. This test thus generally suffices.
Parameters
----------
cls : object
Object to be tested.
Returns
----------
bool
``True`` only if this object is either:
* An isinstanceable class.
* A tuple containing only isinstanceable classes.
See Also
----------
:func:`die_unless_type_isinstanceable`
Further details.
'''
# If this object is *NOT* a class, immediately return false.
if not isinstance(cls, type):
return False
# Else, this object is a class.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with die_unless_type_isinstanceable().
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Attempt to pass this class as the second parameter to the isinstance()
# builtin to decide whether or not this class is safely usable as a
# standard class or not.
#
# Note that this leverages an EAFP (i.e., "It is easier to ask forgiveness
# than permission") approach and thus imposes a minor performance penalty,
# but that there exists *NO* faster alternative applicable to arbitrary
# user-defined classes, whose metaclasses may define an __instancecheck__()
# dunder method to raise exceptions and thus prohibit being passed as the
# second parameter to the isinstance() builtin, the primary means employed
# by @beartype wrapper functions to check arbitrary types.
try:
isinstance(None, cls) # type: ignore[arg-type]
# If the prior function call raised *NO* exception, this class is
# probably but *NOT* necessarily isinstanceable.
return True
# If the prior function call raised an exception, this class is *NOT*
# isinstanceable. In this case, return false.
except:
return False
def is_type_or_types_issubclassable(cls: object) -> bool:
'''
``True`` only if the passed object is either an **issubclassable class**
(i.e., class whose metaclass does *not* define a ``__subclasscheck__()``
dunder method that raises an exception) *or* tuple containing only
issubclassable classes.
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator). Although the implementation does *not*
trivially reduce to an efficient one-liner, the inefficient branch of this
implementation *only* applies to erroneous edge cases resulting in raised
exceptions and is thus largely ignorable.
Caveats
----------
**This tester may return false positives in unlikely edge cases.**
Internally, this tester tests whether this class is issubclassable by
detecting whether passing the :class:`type` superclass and this class to
the :func:`issubclass` builtin raises an exception. If that call raises
*no* exception, this class is probably but *not* necessarily
issubclassable. Since the metaclass of this class could define a
``__subclasscheck__()`` dunder method to conditionally raise exceptions
*except* when passed the :class:`type` superclass, there exists *no* perfect
means of deciding whether an arbitrary class is fully issubclassable in the
general sense. Since most classes that are *not* issubclassable are
unconditionally issubclassable (i.e., the metaclasses of those classes
define an ``__subclasscheck__()`` dunder method to unconditionally raise
exceptions), this distinction is generally meaningless in the real world.
This test thus generally suffices.
Parameters
----------
cls : object
Object to be tested.
Returns
----------
bool
``True`` only if this object is either:
* An issubclassable class.
* A tuple containing only issubclassable classes.
See Also
----------
:func:`die_unless_type_issubclassable`
Further details.
'''
# If this object is *NOT* a class, immediately return false.
if not isinstance(cls, type):
return False
# Else, this object is a class.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with die_unless_type_issubclassable().
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Attempt to pass this class as the second parameter to the issubclass()
# builtin to decide whether or not this class is safely usable as a
# standard class or not.
#
# Note that this leverages an EAFP (i.e., "It is easier to ask forgiveness
# than permission") approach and thus imposes a minor performance penalty,
# but that there exists *NO* faster alternative applicable to arbitrary
# user-defined classes, whose metaclasses may define a __subclasscheck__()
# dunder method to raise exceptions and thus prohibit being passed as the
# second parameter to the issubclass() builtin, the primary means employed
# by @beartype wrapper functions to check arbitrary types.
try:
issubclass(type, cls) # type: ignore[arg-type]
# If the prior function call raised *NO* exception, this class is
# probably but *NOT* necessarily issubclassable.
return True
# If the prior function call raised an exception, this class is *NOT*
# issubclassable. In this case, return false.
except:
return False
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`557`-compliant **class tester** (i.e., callable testing
various properties of dataclasses standardized by :pep:`557`) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_8
# ....................{ TESTERS }....................
# If the active Python interpreter targets Python >= 3.8 and thus supports PEP
# 557-compliant dataclasses, define this tester properly.
if IS_PYTHON_AT_LEAST_3_8:
# Defer version-specific imports.
from dataclasses import is_dataclass
def is_type_pep557(cls: type) -> bool:
# Avoid circular import dependencies.
from beartype._util.cls.utilclstest import die_unless_type
# If this object is *NOT* a type, raise an exception.
die_unless_type(cls)
# Else, this object is a type.
# Return true only if this type is a dataclass.
#
# Note that the is_dataclass() tester was intentionally implemented
# ambiguously to return true for both actual dataclasses *AND*
# instances of dataclasses. Since the prior validation omits the
# latter, this call unambiguously returns true *ONLY* if this object is
# an actual dataclass. (Dodged a misfired bullet there, folks.)
return is_dataclass(cls)
# Else, the active Python interpreter targets Python < 3.8 and thus fails to
# support PEP 557-compliant dataclasses. In this case, reduce this tester to
# unconditionally return false.
else:
def is_type_pep557(cls: type) -> bool:
# Avoid circular import dependencies.
from beartype._util.cls.utilclstest import die_unless_type
# If this object is *NOT* a type, raise an exception.
die_unless_type(cls)
# Else, this object is a type.
# Unconditionally return false.
return False
is_type_pep557.__doc__ = '''
``True`` only if the passed class is a **dataclass** (i.e.,
:pep:`557`-compliant class decorated by the standard
:func:`dataclasses.dataclass` decorator introduced by Python 3.8.0).
This tester is intentionally *not* memoized (e.g., by the
:func:`callable_cached` decorator), as the implementation trivially reduces
to an efficient one-liner.
Parameters
----------
cls : type
Class to be inspected.
Returns
----------
bool
``True`` only if this class is a dataclass.
Raises
----------
_BeartypeUtilTypeException
If this object is *not* a class.
'''
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **dictionary** utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilMappingException
from beartype.typing import (
AbstractSet,
Sequence,
)
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9
from beartype._util.text.utiltextrepr import represent_object
from collections.abc import (
Sequence as SequenceABC,
Hashable,
Mapping,
MutableMapping,
Set,
)
# from threading import Lock
# ....................{ VALIDATORS }....................
def die_if_mappings_two_items_collide(
mapping_a: Mapping, mapping_b: Mapping) -> None:
'''
Raise an exception if the two passed mappings contain a **key-value
collision** (i.e., the same key such that the values associated with that
key in these mappings differ).
A key-value collision occurs when any key ``ka`` and associated value
``va`` of the first mapping and any key ``kb`` and associated value ``vb``
of the second mapping satisfy ``ka == kb && va != vb``. Equivalently, a
key-value collision occurs when any common keys shared between both
mappings are associated with different values.
Parameters
----------
mapping_a: Mapping
First mapping to be inspected.
mapping_b: Mapping
Second mapping to be inspected.
Raises
----------
_BeartypeUtilMappingException
If these mappings contain one or more key-value collisions.
'''
assert isinstance(mapping_a, Mapping), f'{repr(mapping_a)} not mapping.'
assert isinstance(mapping_b, Mapping), f'{repr(mapping_b)} not mapping.'
# For each key of the first mapping...
for mapping_a_key in mapping_a:
# If...
#
# Note this simplistic detection logic has been exhaustively optimized
# with iterative profiling to be the most performant solution. Notably,
# alternative solutions calling dictionary methods (e.g., dict.items(),
# dict.get()) are *DRAMATICALLY* slower -- which is really fascinating.
# CPython appears to have internally optimized pure dictionary syntax.
if (
# This key resides in the second mapping as well *AND*...
mapping_a_key in mapping_b and
# This key unsafely maps to a different value in the second
# mapping...
mapping_a[mapping_a_key] is not mapping_b[mapping_a_key]
):
# Immediately short-circuit this iteration to raise an exception below.
# Merging these mappings would silently and thus unsafely override the
# values associated with these keys in the first mapping with the
# values associated with these keys in the second mapping.
break
# Else, all key collisions are safe (i.e., all shared keys are associated
# with the same values in both mappings). Since merging these mappings as
# is will *NOT* silently and thus unsafely override any values of either
# mapping, accept these mappings as is.
#
# Note that this awkward branching structure has been profiled to be
# optimally efficient, for reasons that honestly elude us. Notably, this
# structure is faster than:
# * The equivalent "any(...)" generator comprehension -- suggesting we
# should similarly unroll *ALL* calls to the any() and all() builtins in
# our critical performance path. Thanks, CPython.
# * The equivalent test against items intersection, which has the
# additional caveat of raising an exception when one or more mapping
# items are unhashable and is thus substantially more fragile: e.g.,
# if len(mapping_keys_shared) == len(mapping_a.items() & mapping_b.items()):
# return
else:
return
# Set of all key collisions (i.e., keys residing in both mappings). Since
# keys are necessarily hashable, this set intersection is guaranteed to be
# safe and thus *NEVER* raise a "TypeError" exception.
#
# Note that omitting the keys() method call on the latter but *NOT* former
# mapping behaves as expected and offers a helpful microoptimization.
mapping_keys_shared = mapping_a.keys() & mapping_b # type: ignore[operator]
# Set of all keys in all item collisions (i.e., items residing in both
# mappings). Equivalently, this is the set of all safe key collisions (i.e.,
# all shared keys associated with the same values in both mappings).
#
# Ideally, we would efficiently intersect these items as follows:
# mapping_items_shared = mapping_a.items() & mapping_b.items()
# Sadly, doing so raises a "TypeError" if one or more values of these
# mappings are unhashable -- as they typically are in common use cases
# throughout this codebase. Ergo, we fallback to a less efficient but
# considerably more robust alternative supporting unhashable values.
mapping_keys_shared_safe = {
# For each possibly unsafe key collision (i.e., shared key associated
# with possibly different values in both mappings), this key...
mapping_key_shared
for mapping_key_shared in mapping_keys_shared
# If this key maps to the same value in both mappings and is thus safe.
if (
mapping_a[mapping_key_shared] is
mapping_b[mapping_key_shared]
)
}
# Dictionary of all unsafe key-value pairs (i.e., pairs such that merging
# these keys would silently override the values associated with these keys
# in either the first or second mappings) from these mappings.
mapping_a_unsafe = dict(
(key_shared_unsafe, mapping_a[key_shared_unsafe])
for key_shared_unsafe in mapping_keys_shared
if key_shared_unsafe not in mapping_keys_shared_safe
)
mapping_b_unsafe = dict(
(key_shared_unsafe, mapping_b[key_shared_unsafe])
for key_shared_unsafe in mapping_keys_shared
if key_shared_unsafe not in mapping_keys_shared_safe
)
# Raise a human-readable exception.
exception_message = (
f'Mappings not safely mergeable due to key-value collisions:\n'
f'~~~~[ mapping_a collisions ]~~~~\n{repr(mapping_a_unsafe)}\n'
f'~~~~[ mapping_b collisions ]~~~~\n{repr(mapping_b_unsafe)}'
)
# print(exception_message)
raise _BeartypeUtilMappingException(exception_message)
# ....................{ TESTERS }....................
#FIXME: Unit test us up, please.
def is_mapping_keys_all(
mapping: Mapping, keys: AbstractSet[Hashable]) -> bool:
'''
``True`` only if the passed mapping contains *all* of the passed keys.
Parameters
----------
mapping: Mapping
Mapping to be tested.
keys: AbstractSet[Hashable]
Set of one or more keys to test this mapping against.
Returns
----------
bool
``True`` only if this mapping contains *all* of these keys.
'''
assert isinstance(mapping, Mapping), f'{repr(mapping)} not mapping.'
assert isinstance(keys, Set), f'{repr(keys)} not set.'
assert bool(keys), 'Keys empty.'
# Return true only if this mapping contains *ALL* of these keys,
# equivalent to efficiently testing whether this set of one or more keys is
# a strict subset of the set of all keys in this mapping.
#
# Note that we intentionally do *NOT* call the set.issubclass() method here.
# Even standard set types that otherwise satisfy the "collections.abc.Set"
# protocol do *NOT* necessarily define that method.
return keys <= mapping.keys()
#FIXME: Unit test us up, please.
def is_mapping_keys_any(
mapping: Mapping, keys: AbstractSet[Hashable]) -> bool:
'''
``True`` only if the passed mapping contains *any* (i.e., one or more, at
least one) of the passed keys.
Parameters
----------
mapping: Mapping
Mapping to be tested.
keys: AbstractSet[Hashable]
Set of one or more keys to test this mapping against.
Returns
----------
bool
``True`` only if this mapping contains *any* of these keys.
'''
assert isinstance(mapping, Mapping), f'{repr(mapping)} not mapping.'
assert isinstance(keys, Set), f'{repr(keys)} not set.'
assert bool(keys), 'Keys empty.'
# Return true only if this mapping contains one or more of these keys,
# equivalent to efficiently testing whether the set intersection between
# this set of one or more keys *AND* the set of all keys in this mapping is
# a non-empty set.
return bool(keys & mapping.keys())
# ....................{ MERGERS }....................
def merge_mappings(*mappings: Mapping) -> Mapping:
'''
Safely merge all passed mappings if these mappings contain no **key-value
collisions** (i.e., if these mappings either contain different keys *or*
share one or more key-value pairs) *or* raise an exception otherwise (i.e.,
if these mappings contain one or more key-value collisions).
Since this function only safely merges mappings and thus *never* silently
overrides any key-value pair of either mapping, order is insignificant;
this function returns the same mapping regardless of the order in which
these mappings are passed.
Caveats
----------
This function creates and returns a new mapping of the same type as that of
the first mapping. That type *must* define an ``__init__()`` method with
the same signature as the standard :class:`dict` type; if this is *not* the
case, an exception is raised.
Parameters
----------
mappings: Tuple[Mapping]
Tuple of two or more mappings to be safely merged.
Returns
----------
Mapping
Mapping of the same type as that of the first mapping created by safely
merging these mappings.
Raises
----------
_BeartypeUtilMappingException
If either:
* No mappings are passed.
* Only one mappings are passed.
* Two or more mappings are passed, but these mappings contain one or
more key-value collisions.
See Also
----------
:func:`die_if_mappings_two_items_collide`
Further details.
'''
# Return either...
return (
# If only two mappings are passed, defer to a function optimized for
# merging two mappings.
merge_mappings_two(mappings[0], mappings[1])
if len(mappings) == 2 else
# Else, three or more mappings are passed. In this case, defer to a
# function optimized for merging three or more mappings.
merge_mappings_two_or_more(mappings)
)
def merge_mappings_two(mapping_a: Mapping, mapping_b: Mapping) -> Mapping:
'''
Safely merge the two passed mappings if these mappings contain no key-value
collisions *or* raise an exception otherwise.
Parameters
----------
mapping_a: Mapping
First mapping to be merged.
mapping_b: Mapping
Second mapping to be merged.
Returns
----------
Mapping
Mapping of the same type as that of the first mapping created by safely
merging these mappings.
Raises
----------
_BeartypeUtilMappingException
If these mappings contain one or more key-value collisions.
See Also
----------
:func:`die_if_mappings_two_items_collide`
Further details.
'''
# If the first mapping is empty, return the second mapping as is.
if not mapping_a:
return mapping_b
# Else, the first mapping is non-empty.
#
# If the second mapping is empty, return the first mapping as is.
elif not mapping_b:
return mapping_a
# Else, both mappings are non-empty.
# If these mappings contain a key-value collision, raise an exception.
die_if_mappings_two_items_collide(mapping_a, mapping_b)
# Else, these mappings contain *NO* key-value collisions.
# Merge these mappings. Since no unsafe collisions exist, the order in
# which these mappings are merged is irrelevant.
return (
# If the active Python interpreter targets Python >= 3.9 and thus
# supports "PEP 584 -- Add Union Operators To dict", merge these
# mappings with the faster and terser dict union operator.
mapping_a | mapping_b # type: ignore[operator]
if IS_PYTHON_AT_LEAST_3_9 else
# Else, merge these mappings by creating and returning a new mapping of
# the same type as that of the first mapping initialized from a slower
# and more verbose dict unpacking operation.
type(mapping_a)(mapping_a, **mapping_b) # type: ignore[call-arg]
)
def merge_mappings_two_or_more(mappings: Sequence[Mapping]) -> Mapping:
'''
Safely merge the one or more passed mappings if these mappings contain no
key-value collisions *or* raise an exception otherwise.
Parameters
----------
mappings: SequenceABC[Mapping]
SequenceABC of two or more mappings to be safely merged.
Returns
----------
Mapping
Mapping of the same type as that of the first mapping created by safely
merging these mappings.
Raises
----------
_BeartypeUtilMappingException
If these mappings contain one or more key-value collisions.
See Also
----------
:func:`die_if_mappings_two_items_collide`
Further details.
'''
assert isinstance(mappings, SequenceABC), f'{repr(mappings)} not sequence.'
# Number of passed mappings.
MAPPINGS_LEN = len(mappings)
# If less than two mappings are passed, raise an exception.
if MAPPINGS_LEN < 2:
# If only one mapping is passed, raise an appropriate exception.
if MAPPINGS_LEN == 1:
raise _BeartypeUtilMappingException(
f'Two or more mappings expected, but only one mapping '
f'{represent_object(mappings[0])} passed.')
# Else, no mappings are passed. Raise an appropriate exception.
else:
raise _BeartypeUtilMappingException(
'Two or more mappings expected, but no mappings passed.')
# Else, two or more mappings are passed.
assert isinstance(mappings[0], Mapping), (
f'First mapping {repr(mappings[0])} not mapping.')
# Merged mapping to be returned, initialized to the merger of the first two
# passed mappings.
mapping_merged = merge_mappings_two(mappings[0], mappings[1])
# If three or more mappings are passed...
if MAPPINGS_LEN > 2:
# For each of the remaining mappings...
for mapping in mappings[2:]:
# Merge this mapping into the merged mapping to be returned.
mapping_merged = merge_mappings_two(mapping_merged, mapping)
# Return this merged mapping.
return mapping_merged
# ....................{ UPDATERS }....................
def update_mapping(mapping_trg: MutableMapping, mapping_src: Mapping) -> None:
'''
Safely update in-place the first passed mapping with all key-value pairs of
the second passed mapping if these mappings contain no **key-value
collisions** (i.e., if these mappings either only contain different keys
*or* share one or more key-value pairs) *or* raise an exception otherwise
(i.e., if these mappings contain one or more of the same keys associated
with different values).
Parameters
----------
mapping_trg: MutableMapping
Target mapping to be safely updated in-place with all key-value pairs
of ``mapping_src``. This mapping is modified by this function and
*must* thus be mutable.
mapping_src: Mapping
Source mapping to be safely merged into ``mapping_trg``. This mapping
is *not* modified by this function and may thus be immutable.
Raises
----------
_BeartypeUtilMappingException
If these mappings contain one or more key-value collisions.
See Also
----------
:func:`die_if_mappings_two_items_collide`
Further details.
'''
assert isinstance(mapping_trg, MutableMapping), (
f'{repr(mapping_trg)} not mutable mapping.')
assert isinstance(mapping_src, Mapping), (
f'{repr(mapping_src)} not mapping.')
# If the second mapping is empty, silently reduce to a noop.
if not mapping_src:
return
# Else, the second mapping is non-empty.
# If these mappings contain a key-value collision, raise an exception.
die_if_mappings_two_items_collide(mapping_trg, mapping_src)
# Else, these mappings contain *NO* key-value collisions.
# Update the former mapping from the latter mapping. Since no unsafe
# collisions exist, this update is now guaranteed to be safe.
mapping_trg.update(mapping_src)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **TTY** (i.e., interactive terminal expected to be reasonably
POSIX-compliant, which even recent post-Windows 10 terminals now guarantee)
utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
import sys
# ....................{ TESTERS }....................
#FIXME: Unit test us up, please.
def is_stdout_terminal() -> bool:
'''
``True`` only if standard output is currently attached to a **TTY** (i.e.,
interactive terminal).
If this tester returns ``True``, the TTY to which standard output is
currently attached may be safely assumed to support **ANSI escape
sequences** (i.e., POSIX-compliant colour codes). This assumption even holds
under platforms that are otherwise *not* POSIX-compliant, including:
* All popular terminals (including the stock Windows Terminal) and
interactive development environments (IDEs) (including VSCode) bundled
with Microsoft Windows, beginning at Windows 10.
Caveats
----------
**This tester is intentionally not memoized** (i.e., via the
:func:`beartype._util.cache.utilcachecall.callable_cached` decorator), as
external callers can and frequently do monkey-patch or otherwise modify the
value of the global :attr:`sys.stdout` output stream.
See Also
----------
https://stackoverflow.com/questions/3818511/how-to-tell-if-python-script-is-being-run-in-a-terminal-or-via-gui
StackOverflow thread strongly inspiring this implementation.
'''
# print(f'sys.stdout: {repr(sys.stdout)} [{type(sys.stdout)}]')
# print(f'sys.stderr: {repr(sys.stderr)} [{type(sys.stderr)}]')
# One-liners for great justice.
#
# Note that:
# * Input and output streams are *NOT* guaranteed to define the isatty()
# method. For safety, we defensively test for the existence of that method
# before deferring to that method.
# * All popular terminals under Windows >= 10 -- including terminals bundled
# out-of-the-box with Windows -- now support ANSII escape sequences. Since
# older Windows versions are compelling security risks and thus ignorable
# for contemporary purposes, Windows no longer needs to be excluded from
# ANSII-based colourization. All praise Satya Nadella. \o/
return hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
# return hasattr(sys.stdin, 'isatty') and sys.stdin.isatty()
# return hasattr(sys.stderr, 'isatty') and sys.stderr.isatty()
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **platform tester** (i.e., functions detecting the current
platform the active Python interpreter is running under) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._util.cache.utilcachecall import callable_cached
from platform import system as platform_system
from sys import platform as sys_platform
# ....................{ TESTERS }....................
@callable_cached
def is_os_linux() -> bool:
'''
``True`` only if the current platform is a **Linux distribution.**
This tester is memoized for efficiency.
'''
return platform_system() == 'Linux'
@callable_cached
def is_os_macos() -> bool:
'''
``True`` only if the current platform is **Apple macOS**, the operating
system previously known as "OS X."
This tester is memoized for efficiency.
'''
return platform_system() == 'Darwin'
@callable_cached
def is_os_windows_vanilla() -> bool:
'''
``True`` only if the current platform is **vanilla Microsoft Windows**
(i.e., *not* running the Cygwin POSIX compatibility layer).
This tester is memoized for efficiency.
'''
return sys_platform == 'win32'
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **string joining utilities** (i.e., callables joining passed
strings into new strings delimited by passed substring delimiters).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.typing import Iterable as typing_Iterable
from beartype._data.datatyping import IterableStrs
from collections.abc import Iterable, Sequence
# ....................{ JOINERS }....................
def join_delimited(
strs: IterableStrs,
delimiter_if_two: str,
delimiter_if_three_or_more_nonlast: str,
delimiter_if_three_or_more_last: str
) -> str:
'''
Concatenate the passed iterable of zero or more strings delimited by the
passed delimiter (conditionally depending on both the length of this
sequence and index of each string in this sequence), yielding a
human-readable string listing arbitrarily many substrings.
Specifically, this function returns either:
* If this iterable contains no strings, the empty string.
* If this iterable contains one string, this string as is is unmodified.
* If this iterable contains two strings, these strings delimited by the
passed ``delimiter_if_two`` delimiter.
* If this iterable contains three or more strings, a string listing these
contained strings such that:
* All contained strings except the last two are suffixed by the passed
``delimiter_if_three_or_more_nonlast`` delimiter.
* The last two contained strings are delimited by the passed
``delimiter_if_three_or_more_last`` separator.
Parameters
----------
strs : Iterable[str]
Iterable of all strings to be joined.
delimiter_if_two : str
Substring separating each string contained in this iterable if this
iterable contains exactly two strings.
delimiter_if_three_or_more_nonlast : str
Substring separating each string *except* the last two contained in
this iterable if this iterable contains three or more strings.
delimiter_if_three_or_more_last : str
Substring separating each string the last two contained in this
iterable if this iterable contains three or more strings.
Returns
----------
str
Concatenation of these strings.
Examples
----------
>>> join_delimited(
... strs=('Fulgrim', 'Perturabo', 'Angron', 'Mortarion'),
... delimiter_if_two=' and ',
... delimiter_if_three_or_more_nonlast=', ',
... delimiter_if_three_or_more_last=', and '
... )
'Fulgrim, Perturabo, Angron, and Mortarion'
'''
assert isinstance(strs, Iterable) and not isinstance(strs, str), (
f'{repr(strs)} not non-string iterable.')
assert isinstance(delimiter_if_two, str), (
f'{repr(delimiter_if_two)} not string.')
assert isinstance(delimiter_if_three_or_more_nonlast, str), (
f'{repr(delimiter_if_three_or_more_nonlast)} not string.')
assert isinstance(delimiter_if_three_or_more_last, str), (
f'{repr(delimiter_if_three_or_more_last)} not string.')
# If this iterable is *NOT* a sequence, internally coerce this iterable
# into a sequence for subsequent indexing purposes.
if not isinstance(strs, Sequence):
strs = tuple(strs)
# Number of strings in this sequence.
num_strs = len(strs)
# If no strings are passed, return the empty string.
if num_strs == 0:
return ''
# If one string is passed, return this string as is.
elif num_strs == 1:
# This is clearly a string, yet mypy thinks it's Any
return strs[0] # type: ignore[no-any-return]
# If two strings are passed, return these strings delimited appropriately.
elif num_strs == 2:
return f'{strs[0]}{delimiter_if_two}{strs[1]}'
# Else, three or more strings are passed.
# All such strings except the last two, delimited appropriately.
strs_nonlast = delimiter_if_three_or_more_nonlast.join(strs[0:-2])
# The last two such strings, delimited appropriately.
strs_last = f'{strs[-2]}{delimiter_if_three_or_more_last}{strs[-1]}'
# Return these two substrings, delimited appropriately.
return f'{strs_nonlast}{delimiter_if_three_or_more_nonlast}{strs_last}'
# ....................{ JOINERS ~ disjunction }....................
def join_delimited_disjunction(strs: IterableStrs) -> str:
'''
Concatenate the passed iterable of zero or more strings delimited by commas
and/or the disjunction "or" (conditionally depending on both the length of
this iterable and index of each string in this iterable), yielding a
human-readable string listing arbitrarily many substrings disjunctively.
Specifically, this function returns either:
* If this iterable contains no strings, the empty string.
* If this iterable contains one string, this string as is is unmodified.
* If this iterable contains two strings, these strings delimited by the
disjunction "or".
* If this iterable contains three or more strings, a string listing these
contained strings such that:
* All contained strings except the last two are suffixed by commas.
* The last two contained strings are delimited by the disjunction "or".
Parameters
----------
strs : Iterable[str]
Iterable of all strings to be concatenated disjunctively.
Returns
----------
str
Disjunctive concatenation of these strings.
'''
# He will join us or die, master.
return join_delimited(
strs=strs,
delimiter_if_two=' or ',
delimiter_if_three_or_more_nonlast=', ',
delimiter_if_three_or_more_last=', or '
)
def join_delimited_disjunction_types(types: typing_Iterable[type]) -> str:
'''
Concatenate the human-readable classname of each class in the passed
iterable delimited by commas and/or the disjunction "or" (conditionally
depending on both the length of this iterable and index of each string in
this iterable), yielding a human-readable string listing arbitrarily many
classnames disjunctively.
Parameters
----------
types : Iterable[type]
Iterable of all classes whose human-readable classnames are to be
concatenated disjunctively.
Returns
----------
str
Disjunctive concatenation of these classnames.
'''
# Avoid circular import dependencies.
from beartype._util.text.utiltextlabel import label_type
# Make it so, ensign.
return join_delimited_disjunction(label_type(cls) for cls in types)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Python identifier** (i.e., attribute, callable, class, module,
or variable name) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
# ....................{ TESTERS }....................
def is_identifier(text: str) -> bool:
'''
``True`` only if the passed string is the ``.``-delimited concatenation of
one or more :pep:`3131`-compliant syntactically valid **Python
identifiers** (i.e., attribute, callable, class, module, or variable name),
suitable for testing whether this string is the fully-qualified name of an
arbitrary Python object.
Caveats
----------
**This tester is mildly slow,** due to unavoidably splitting this string on
``.`` delimiters and iteratively passing each of the split substrings to
the :meth:`str.isidentifier` builtin. Due to the following caveat, this
inefficiency is unavoidable.
**This tester is not optimizable with regular expressions** -- at least,
not trivially. Technically, this tester *can* be optimized by leveraging
the "General Category" of Unicode filters provided by the third-party
:mod:`regex` package. Practically, doing so would require the third-party
:mod:`regex` package and would still almost certainly fail in edge cases.
Why? Because Python 3 permits Python identifiers to contain Unicode letters
and digits in the "General Category" of Unicode code points, which is
highly non-trivial to match with the standard :mod:`re` module.
Parameters
----------
text : string
String to be inspected.
Returns
----------
bool
``True`` only if this string is the ``.``-delimited concatenation of
one or more syntactically valid Python identifiers.
'''
assert isinstance(text, str), f'{repr(text)} not string.'
# Return either...
return (
# If this text contains *NO* "." delimiters and is thus expected to be
# an unqualified Python identifier, true only if this is the case;
text.isidentifier()
if '.' not in text else
# Else, this text contains one or more "." delimiters and is thus
# expected to be a qualified Python identifier. In this case, true only
# if *ALL* "."-delimited substrings split from this string are valid
# unqualified Python identifiers.
#
# Note that:
# * Regular expressions report false negatives. See the docstring.
# * There exists an alternative and significantly more computationally
# expensive means of testing this condition, employed by the
# typing.ForwardRef.__init__() method to valid the validity of the
# passed relative classname:
# # Needless to say, we'll never be doing this.
# try:
# all(
# compile(identifier, '<string>', 'eval')
# for identifier in text.split('.')
# )
# return True
# except SyntaxError:
# return False
all(identifier.isidentifier() for identifier in text.split('.'))
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype string testing utilities** (i.e., callables testing whether passed
strings satisfy various conditions).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
# ....................{ TESTERS }....................
def is_str_float_or_int(text: str) -> bool:
'''
``True`` only if the passed string is a valid machine-readable
representation of either an integer or finite floating-point number.
Caveats
----------
This tester intentionally returns ``False`` for non-standard floating-point
pseudo-numbers that have no finite value, including:
* Not-a-numbers (i.e., ``float('NaN')`` values).
* Negative infinity (i.e., ``float('-inf')`` values).
* Positive infinity (i.e., ``float('inf')`` values).
Parameters
----------
text : str
String to be inspected.
Returns
----------
bool
``True`` only if this string is a valid machine-readable representation
of either an integer or finite floating-point number.
'''
assert isinstance(text, str), f'{repr(text)} not string.'
# Return true only if this text represents a finite number. See also:
# s.lstrip('-').replace('.','',1).replace('e-','',1).replace('e','',1).isdigit()
return text.lstrip(
'-').replace('.','',1).replace('e-','',1).replace('e','',1).isdigit()
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **text label** (i.e., human-readable strings describing prominent
objects or types, typically interpolated into error messages) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.typing import Optional
from beartype._util.utilobject import (
get_object_name,
get_object_type_name,
)
from collections.abc import Callable
# ....................{ LABELLERS ~ callable }....................
def label_callable(
# Mandatory parameters.
func: Callable,
# Optional parameters.
is_contextualized: Optional[bool] = None,
) -> str:
'''
Human-readable label describing the passed **callable** (e.g., function,
method, property).
Parameters
----------
func : Callable
Callable to be labelled.
is_contextualized : Optional[bool] = None
Either:
* ``True``, in which case this label is suffixed by additional metadata
contextually disambiguating that callable, including:
* The line number of the first line declaring that callable in its
underlying source code module file.
* The absolute filename of that file.
* ``False``, in which case this label is *not* suffixed by such
metadata.
* ``None``, in which case this label is conditionally suffixed by such
metadata only if that callable is a lambda function and thus
ambiguously lacks any semblance of an innate context.
Defaults to ``None``.
Returns
----------
str
Human-readable label describing this callable.
'''
assert callable(func), f'{repr(func)} uncallable.'
# Avoid circular import dependencies.
from beartype._util.func.arg.utilfuncargget import (
get_func_args_len_flexible)
from beartype._util.func.utilfuncfile import get_func_filename_or_none
from beartype._util.func.utilfunccodeobj import get_func_codeobj
from beartype._util.func.utilfunctest import (
is_func_lambda,
is_func_coro,
is_func_async_generator,
is_func_sync_generator,
)
from beartype._util.mod.utilmodget import (
get_object_module_line_number_begin)
# Substring prefixing the string to be returned, typically identifying the
# specialized type of that callable if that callable has a specialized type.
func_label_prefix = ''
# Substring suffixing the string to be returned, typically contextualizing
# that callable with respect to its on-disk code module file.
func_label_suffix = ''
# If the passed callable is a pure-Python lambda function, that callable
# has *NO* unique fully-qualified name. In this case, return a string
# uniquely identifying this lambda from various code object metadata.
if is_func_lambda(func):
# Code object underlying this lambda.
func_codeobj = get_func_codeobj(func)
# Substring preceding the string to be returned.
func_label_prefix = (
f'lambda function of '
f'{get_func_args_len_flexible(func_codeobj)} argument(s)'
)
# If the caller failed to request an explicit contextualization, default
# to contextualizing this lambda function.
if is_contextualized is None:
is_contextualized = True
# Else, the caller requested an explicit contextualization. In this
# case, preserve that contextualization as is.
# Else, the passed callable is *NOT* a pure-Python lambda function and thus
# has a unique fully-qualified name.
else:
# If that callable is a synchronous generator, return this string
# prefixed by a substring emphasizing that fact.
if is_func_sync_generator(func):
func_label_prefix = 'generator '
# Else, that callable is *NOT* a synchronous generator.
#
# If that callable is an asynchronous coroutine, return this string
# prefixed by a substring emphasizing that fact.
elif is_func_coro(func):
func_label_prefix = 'coroutine '
# Else, that callable is *NOT* an asynchronous coroutine.
#
# If that callable is an asynchronous generator, return this string
# prefixed by a substring emphasizing that fact.
elif is_func_async_generator(func):
func_label_prefix = 'asynchronous generator '
# Else, that callable is *NOT* an asynchronous generator.
# If contextualizing that callable...
if is_contextualized:
# Absolute filename of the source module file defining that callable if
# that callable was defined on-disk *OR* "None" otherwise (i.e., if that
# callable was defined in-memory).
func_filename = get_func_filename_or_none(func)
# Line number of the first line declaring that callable in that file.
func_lineno = get_object_module_line_number_begin(func)
# If that callable was defined on-disk, describe the location of that
# callable in that file.
if func_filename:
func_label_suffix += (
f' declared on line {func_lineno} of file "{func_filename}" ')
# Else, that callable was defined in-memory. In this case, avoid
# attempting to uselessly contextualize that callable.
# Return that prefix followed by the fully-qualified name of that callable.
return f'{func_label_prefix}{get_object_name(func)}(){func_label_suffix}'
# ....................{ LABELLERS ~ type }....................
def label_obj_type(obj: object) -> str:
'''
Human-readable label describing the class of the passed object.
Parameters
----------
obj : object
Object whose class is to be labelled.
Returns
----------
str
Human-readable label describing the class of this object.
'''
# Tell me why, why, why I curse the sky! ...no, srsly.
return label_type(type(obj))
def label_type(cls: type) -> str:
'''
Human-readable label describing the passed class.
Parameters
----------
cls : type
Class to be labelled.
Returns
----------
str
Human-readable label describing this class.
'''
assert isinstance(cls, type), f'{repr(cls)} not class.'
# Avoid circular import dependencies.
from beartype._util.cls.utilclstest import is_type_builtin
from beartype._util.hint.pep.proposal.utilpep544 import (
is_hint_pep544_protocol)
# Label to be returned, initialized to this class' fully-qualified name.
classname = get_object_type_name(cls)
# print(f'cls {cls} classname: {classname}')
# If this name contains *NO* periods, this class is actually a builtin type
# (e.g., "list"). Since builtin types are well-known and thus
# self-explanatory, this name requires no additional labelling. In this
# case, return this name as is.
if '.' not in classname:
pass
# Else, this name contains one or more periods but could still be a
# builtin indirectly accessed via the standard "builtins" module.
#
# If this name is that of a builtin type uselessly prefixed by the name of
# the module declaring all builtin types (e.g., "builtins.list"), reduce
# this name to the unqualified basename of this type (e.g., "list").
elif is_type_builtin(cls):
classname = cls.__name__
# Else, this is a non-builtin class. Non-builtin classes are *NOT*
# well-known and thus benefit from additional labelling.
#
# If this class is a PEP 544-compliant protocol supporting structural
# subtyping, label this protocol.
elif is_hint_pep544_protocol(cls):
# print(f'cls {cls} is protocol!')
classname = f'<protocol "{classname}">'
# Else if this class is a standard abstract base class (ABC) defined by a
# stdlib submodule also known to support structural subtyping (e.g.,
# "collections.abc.Hashable", "contextlib.AbstractContextManager"),
# label this ABC as a protocol.
#
# Note that user-defined ABCs do *NOT* generally support structural
# subtyping. Doing so requires esoteric knowledge of undocumented and
# mostly private "abc.ABCMeta" metaclass internals unlikely to be
# implemented by third-party developers. Thanks to the lack of both
# publicity and standardization, there exists *NO* general-purpose means of
# detecting whether an arbitrary class supports structural subtyping.
elif (
classname.startswith('collections.abc.') or
classname.startswith('contextlib.')
):
classname = f'<protocol ABC "{classname}">'
# Else, this is a standard class. In this case, label this class as such.
else:
classname = f'<class "{classname}">'
# Return this labelled classname.
return classname
# ....................{ LABELLERS ~ exception }....................
def label_exception(exception: Exception) -> str:
'''
Human-readable label describing the passed exception.
Caveats
----------
**The label returned by this function does not describe the traceback
originating this exception.** To do so, consider calling the standard
:func:`traceback.format_exc` function instead.
Parameters
----------
exception : Exception
Exception to be labelled.
Returns
----------
str
Human-readable label describing this exception.
'''
assert isinstance(exception, Exception), (
f'{repr(exception)} not exception.')
# Return this exception's label.
return f'{exception.__class__.__qualname__}: {str(exception)}'
# ....................{ PREFIXERS ~ callable }....................
def prefix_callable(func: Callable) -> str:
'''
Human-readable label describing the passed **callable** (e.g., function,
method, property) suffixed by delimiting whitespace.
Parameters
----------
func : Callable
Callable to be labelled.
Returns
----------
str
Human-readable label describing this callable.
'''
assert callable(func), f'{repr(func)} uncallable.'
# Testify, beartype!
return f'{label_callable(func)} '
def prefix_callable_decorated(func: Callable) -> str:
'''
Human-readable label describing the passed **decorated callable** (i.e.,
callable wrapped by the :func:`beartype.beartype` decorator with a wrapper
function type-checking that callable) suffixed by delimiting whitespace.
Parameters
----------
func : Callable
Decorated callable to be labelled.
Returns
----------
str
Human-readable label describing this decorated callable.
'''
# Create and return this label.
return f'@beartyped {prefix_callable(func)}'
def prefix_callable_decorated_pith(
func: Callable, pith_name: str) -> str:
'''
Human-readable label describing either the parameter with the passed name
*or* return value if this name is ``return`` of the passed **decorated
callable** (i.e., callable wrapped by the :func:`beartype.beartype`
decorator with a wrapper function type-checking that callable) suffixed by
delimiting whitespace.
Parameters
----------
func : Callable
Decorated callable to be labelled.
pith_name : str
Name of the parameter or return value of this callable to be labelled.
Returns
----------
str
Human-readable label describing either the name of this parameter *or*
this return value.
'''
assert isinstance(pith_name, str), f'{repr(pith_name)} not string.'
# Return a human-readable label describing either...
return (
# If this name is "return", the return value of this callable.
prefix_callable_decorated_return(func)
if pith_name == 'return' else
# Else, the parameter with this name of this callable.
prefix_callable_decorated_arg(func=func, arg_name=pith_name)
)
# ....................{ PREFIXERS ~ callable : param }....................
def prefix_callable_decorated_arg(
func: Callable, arg_name: str) -> str:
'''
Human-readable label describing the parameter with the passed name of the
passed **decorated callable** (i.e., callable wrapped by the
:func:`beartype.beartype` decorator with a wrapper function type-checking
that callable) suffixed by delimiting whitespace.
Parameters
----------
func : Callable
Decorated callable to be labelled.
arg_name : str
Name of the parameter of this callable to be labelled.
Returns
----------
str
Human-readable label describing this parameter's name.
'''
assert isinstance(arg_name, str), f'{repr(arg_name)} not string.'
# Create and return this label.
return f'{prefix_callable_decorated(func)}parameter "{arg_name}" '
# ....................{ PREFIXERS ~ callable : return }....................
def prefix_callable_decorated_return(func: Callable) -> str:
'''
Human-readable label describing the return of the passed **decorated
callable** (i.e., callable wrapped by the :func:`beartype.beartype`
decorator with a wrapper function type-checking that callable) suffixed by
delimiting whitespace.
Parameters
----------
func : Callable
Decorated callable to be labelled.
Returns
----------
str
Human-readable label describing this return.
'''
# Create and return this label.
return f'{prefix_callable_decorated(func)}return '
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype string getting utilities** (i.e., callables getting substrings of
passed strings, typically prefixes and suffixes satisfying various conditions).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
# from beartype.roar._roarexc import _BeartypeUtilTextException
# ....................{ GETTERS }....................
#FIXME: Uncomment if ever needed.
# def get_str_prefix_greedy(text: str, anchor: str) -> str:
# '''
# **Greedily anchored prefix** (i.e., substring ranging from the first
# character to the last instance of the passed substring) of the passed
# string if any *or* raise an exception otherwise (i.e., if this string
# contains no such substring).
#
# Parameters
# ----------
# text : str
# String to be searched.
# anchor: str
# Substring to search this string for.
#
# Returns
# ----------
# str
# Prefix of this string preceding the last instance of this substring.
#
# Raises
# ----------
# _BeartypeUtilTextException
# If this string contains *no* instance of this substring.
#
# See Also
# ----------
# :func:`get_str_prefix_greedy_or_none`
# Further details.
# '''
#
# # Greedily anchored prefix of this string if any *OR* "None" otherwise.
# text_prefix_greedy = get_str_prefix_greedy_or_none(text, anchor)
#
# # If this string contains *NO* such prefix, raise an exception.
# if text_prefix_greedy is None:
# raise _BeartypeUtilTextException(
# f'String "{text}" substring "{anchor}" not found.')
#
# # Else, return this prefix.
# return text_prefix_greedy
#FIXME: Uncomment if ever needed.
# def get_str_prefix_greedy_or_none(text: str, anchor: str) -> 'Optional[str]':
# '''
# **Greedily anchored prefix** (i.e., substring ranging from the first
# character to the last instance of the passed substring) of the passed
# string if any *or* ``None`` otherwise (i.e., if this string contains no
# such substring).
#
# Parameters
# ----------
# text : str
# String to be searched.
# anchor: str
# Substring to search this string for.
#
# Returns
# ----------
# Optional[str]
# Either:
#
# * If this string contains this substring, the prefix of this string
# preceding the last instance of this substring.
# * Else, ``None``.
#
# Examples
# ----------
# >>> from beartype._util.text.utiltextget import (
# ... get_str_prefix_greedy_or_none)
# >>> get_str_prefix_greedy_or_none(
# ... text='Opposition...contradiction...premonition...compromise.',
# ... anchor='.')
# Opposition...contradiction...premonition...compromise
# >>> get_str_prefix_greedy_or_none(
# ... text='This is an anomaly. Disabled. What is true?',
# ... anchor='!')
# None
# '''
# assert isinstance(text, str), f'{repr(text)} not string.'
# assert isinstance(anchor, str), f'{repr(anchor)} not string.'
#
# # Return either...
# return (
# # If this string contains this substring, the substring of this string
# # preceding the last instance of this substring in this string.
# text[:text.rindex(anchor)]
# if anchor in text else
# # Else, "None".
# None
# )
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **magic strings** (i.e., globally applicable string constants).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
# ....................{ CODE ~ indent }....................
CODE_INDENT_1 = ' '
'''
PEP-agnostic code snippet expanding to a single level of indentation.
'''
CODE_INDENT_2 = CODE_INDENT_1*2
'''
PEP-agnostic code snippet expanding to two levels of indentation.
'''
CODE_INDENT_3 = CODE_INDENT_2 + CODE_INDENT_1
'''
PEP-agnostic code snippet expanding to three levels of indentation.
'''
# ....................{ CODE ~ operator }....................
LINE_RSTRIP_INDEX_AND = -len(' and')
'''
Negative index relative to the end of any arbitrary newline-delimited Python
code string suffixed by the boolean operator ``" and"`` required to strip that
suffix from that substring.
'''
LINE_RSTRIP_INDEX_OR = -len(' or')
'''
Negative index relative to the end of any arbitrary newline-delimited Python
code string suffixed by the boolean operator ``" or"`` required to strip that
suffix from that substring.
'''
|
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **ANSI utilities** (i.e., low-level callables handling ANSI escape
sequences colouring arbitrary strings).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from re import compile as re_compile
# ....................{ CONSTANTS }....................
ANSI_RESET = '\033[0m'
'''
ANSI escape sequence resetting the effect of all prior ANSI sequence sequences,
effectively "undoing" all colors and styles applied by those sequences.
'''
# ....................{ CONSTANTS ~ color }....................
COLOR_GREEN = '\033[92m'
'''
ANSI escape sequence colouring all subsequent characters as green.
'''
COLOR_RED = '\033[31m'
'''
ANSI escape sequence colouring all subsequent characters as red.
'''
COLOR_BLUE = '\033[34m'
'''
ANSI escape sequence colouring all subsequent characters as blue.
'''
COLOR_YELLOW = '\033[33m'
'''
ANSI escape sequence colouring all subsequent characters as yellow.
'''
# ....................{ CONSTANTS ~ style }....................
STYLE_BOLD = '\033[1m'
'''
ANSI escape sequence stylizing all subsequent characters as bold.
'''
# ....................{ TESTERS }....................
#FIXME: Unit test us up, please.
def is_text_ansi(text: str) -> bool:
'''
``True`` if the passed text contains one or more ANSI escape sequences.
Parameters
----------
text : str
Text to be tested for ANSI.
Returns
----------
bool
``True`` only if this text contains one or more ANSI escape sequences.
'''
assert isinstance(text, str), f'{repr(text)} not string.'
# Return true only this compiled regex matching ANSI escape sequences
# returns a non-"None" match object when passed this text.
return _ANSI_REGEX.search(text) is not None
# ....................{ STRIPPERS }....................
#FIXME: Unit test us up, please.
def strip_text_ansi(text: str) -> str:
'''
Strip all ANSI escape sequences from the passed string.
Parameters
----------
text : str
Text to be stripped of ANSI.
Returns
----------
str
This text stripped of ANSI.
'''
assert isinstance(text, str), f'{repr(text)} not string.'
# Glory be to the one liner that you are about to read.
return _ANSI_REGEX.sub('', text)
# ....................{ PRIVATE ~ constants }....................
_ANSI_REGEX = re_compile(r'\033\[[0-9;?]*[A-Za-z]')
'''
Compiled regular expression matching a single ANSI escape sequence.
'''
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
"""
**Beartype string munging utilities** (i.e., callables transforming passed
strings into new strings with generic string operations).
This private submodule is *not* intended for importation by downstream callers.
"""
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilTextException
# ....................{ CASERS }....................
def uppercase_char_first(text: str) -> str:
"""
Uppercase *only* the first character of the passed string.
Whereas the standard :meth:`str.capitalize` method both uppercases the
first character of this string *and* lowercases all remaining characters,
this function *only* uppercases the first character. All remaining
characters remain unmodified.
Parameters
----------
text : str
String whose first character is to be uppercased.
Returns
----------
str
This string with the first character uppercased.
"""
assert isinstance(text, str), f'{repr(text)} not string.'
# For great justice!
return text[0].upper() + text[1:] if text else ''
# ....................{ NUMBERERS }....................
def number_lines(text: str) -> str:
"""
Passed string munged to prefix each line of this string with the 1-based
number of that line padded by zeroes out to four digits for alignment.
Parameters
----------
text : str
String whose lines are to be numbered.
Returns
----------
str
This string with all lines numbered.
"""
assert isinstance(text, str), f'{repr(text)} not string.'
# For radical benevolence!
return '\n'.join(
'(line {:0>4d}) {}'.format(text_line_number, text_line)
for text_line_number, text_line in enumerate(
text.splitlines(), start=1)
)
# ....................{ REPLACERS }....................
def replace_str_substrs(text: str, old: str, new: str) -> str:
"""
Passed string with all instances of the passed source substring globally
replaced by the passed target substring if this string contains at least
one such instance *or* raise an exception otherwise (i.e., if this string
contains *no* such instance).
Caveats
----------
**This higher-level function should always be called in lieu of the
lower-level** :meth:`str.replace` method, which unconditionally succeeds
regardless of whether this subject string contains at least one instance of
this source substring or not.
Parameters
----------
text : str
Subject string to perform this global replacement on.
old : str
Source substring of this subject string to be globally replaced.
new : str
Target substring to globally replace this source substring with in this
subject string.
Returns
----------
str
Subject string with all instances of this source substring globally
replaced by this target substring.
Raises
----------
_BeartypeUtilTextException
If this subject string contains *no* instances of this source
substring.
Examples
----------
>>> from beartype._util.text.utiltextmunge import replace_str_substrs
>>> replace_str_substrs(
... text='And now the STORM-BLAST came, and he',
... old='he', new='hat')
And now that STORM-BLAST came, and hat
>>> replace_str_substrs(
... text='I shot the ALBATROSS.', old='dross', new='drat')
beartype.roar._BeartypeUtilTextException: String "I shot the
ALBATROSS." substring "dross" not found.
"""
assert isinstance(text, str), f'{repr(text)} not string.'
assert isinstance(old, str), f'{repr(old)} not string.'
assert isinstance(new, str), f'{repr(new)} not string.'
# If this subject contains *NO* instances of this substring, raise an
# exception.
if old not in text:
raise _BeartypeUtilTextException(
f'String "{text}" substring "{old}" not found.')
# Else, this subject contains one or more instances of this substring.
# Return this subject with all instances of this source substring globally
# replaced by this target substring.
return text.replace(old, new)
# ....................{ SUFFIXERS }....................
def suffix_unless_suffixed(text: str, suffix: str) -> str:
"""
Passed string either suffixed by the passed suffix if this string is not
yet suffixed by this suffix *or* this string as is otherwise (i.e., if this
string is already suffixed by this suffix).
Parameters
----------
text : str
String to be conditionally suffixed.
suffix : str
Suffix to be conditionally appended to this string.
Returns
----------
str
Either:
* If this string is *not* yet suffixed by this suffix, this string
suffixed by this suffix.
* Else, this string as is.
"""
assert isinstance(text, str), f'{repr(text)} not string.'
assert isinstance(suffix, str), f'{repr(suffix)} not string.'
# Suffix us up the redemption arc.
return text if text.endswith(suffix) else text + suffix
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
"""
Project-wide **string munging** (i.e., generic low-level operations
transforming strings into new derivative strings) utilities.
This private submodule is *not* intended for importation by downstream callers.
"""
# ....................{ IMPORTS }....................
from beartype.roar._roarwarn import _BeartypeUtilCallableWarning
from beartype.typing import Dict
from beartype._data.datatyping import TypeWarning
from beartype._cave._cavefast import NumberType
from beartype._util.utilobject import get_object_basename_scoped
from collections.abc import Callable
from string import punctuation
# ....................{ PRIVATE ~ cache }....................
_MAX_LEN_TO_MAX_CHARS_REGEX: Dict[int, str] = {}
'''
Non-thread-safe global dictionary cache mapping from each **maximum length**
(i.e., ``max_len`` parameter previously passed to the :func:`represent_object`
function) to a compiled regular expression grouping zero or more leading
characters preceding this maximum length *and* zero or more trailing
delimiters.
Caveats
----------
**This cache is intentionally non-thread-safe.** Although rendering this cache
thread-safe would be trivial (e.g., via the
:class:`beartype._util.cache.map.utilmapbig.CacheUnboundedStrong` class), doing
so would both reduce efficiency *and* be ineffectual. Since this cache is
*only* used to amortize the costs of regular expression compilation, violating
thread-safety has *no* harmful side effects (aside from recompiling a
previously compiled regular expression in unlikely edge cases).
'''
# ....................{ PRIVATE ~ frozen }....................
_CHARS_PUNCTUATION = frozenset(punctuation)
'''
Frozen set of all **ASCII punctuation characters** (i.e., non-Unicode
characters satisfying the conventional definition of English punctuation).
Note that the :attr:`string.punctuation` object is actually an inefficient
string of these characters rather than an efficient collection. Ergo, this set
should *ALWAYS* be accessed in lieu of that string.
'''
_TYPES_UNQUOTABLE = (
# Byte strings, whose representations are already quoted as "b'...'".
bytes,
# Numbers, whose representations are guaranteed to both contain *NO*
# whitespace and be sufficiently terse as to benefit from *NO* quoting.
NumberType,
)
'''
**Unquotable tuple union** (i.e., isinstancable tuple of all classes such that
the :func:`represent_object` function intentionally avoids double-quoting the
machine-readable representations all instances of these classes, typically due
to these representations either being effectively quoted already *or*
sufficiently terse as to not benefit from being quoted).
'''
# ....................{ REPRESENTERS }....................
def represent_object(
# Mandatory parameters.
obj: object,
# Optional parameters.
max_len: int = 96,
) -> str:
"""
Pretty-printed quasi-human-readable variant of the string returned by the
non-pretty-printed machine-readable :meth:`obj.__repr__` dunder method of
the passed object, truncated to the passed maximum string length.
Specifically, this function (in order):
#. Obtains this object's representation by calling ``repr(object)``.
#. If this representation is neither suffixed by a punctuation character
(i.e., character in the standard :attr:`string.punctuation` set) *nor*
representing a byte-string whose representations are prefixed by ``b'``
and suffixed by ``'`` (e.g., ``b'Check, mate.'``), double-quotes this
representation for disambiguity with preceding characters -- notably,
sequence indices. Since strings returned by this function commonly
follow sequence indices in error messages, failing to disambiguate the
two produces non-human-readable output:
>>> def wat(mate: typing.List[str]) -> int: return len(mate)
>>> get_beartype_violation(
... func=muh_func, pith_name='mate', pith_value=[7,])
beartype.roar.BeartypeCallHintParamViolation: @beartyped wat()
parameter mate=[7] violates PEP type hint typing.List[str], as list
item 0 value 7 not a str.
Note the substring "item 0 value 7", which misreads like a blatant bug.
Double-quoting the "7" suffices to demarcate values from indices.
#. If this representation exceeds the passed maximum length, replaces the
suffix of this representation exceeding this length with an ellipses
(i.e., ``"..."`` substring).
Caveats
----------
**This function is unavoidably slow and should thus not be called from
optimized performance-critical code.** This function internally performs
mildly expensive operations, including regular expression-based matching
and substitution. Ideally, this function should *only* be called to create
user-oriented exception messages where performance is a negligible concern.
**This function preserves all quote-protected newline characters** (i.e.,
``"\\n"``) **in this representation.** Since the :meth:`str.__repr__`
dunder method implicitly quote-protects all newlines in the original
string, this function effectively preserves all newlines in strings.
Parameters
----------
obj : object
Object to be represented.
max_len: int, optional
Maximum length of the string to be returned. Defaults to a standard
line length of 100 characters minus output indentation of 4 characters.
Returns
----------
str
Pretty-printed quasi-human-readable variant of this object's
non-pretty-printed machine-readable representation.
"""
assert isinstance(max_len, int), f'{repr(max_len)} not integer.'
#FIXME: Render this safe against infinitely recursive data structures.
#Unfortunately, we *CANNOT* call the standard pprint.saferepr() function to
#do so, as that function is *OUTRAGEOUSLY* slow on worst-case edge cases.
#Instead, we'll need to implement our own performant saferepr()
#alternative. Fortunately, note that someone's already done so: the popular
#BSD-licensed Celerity project, whose celerity.utils.saferepr.saferepr()
#function claims to actually be faster than the repr() builtin under
#certain circumstances. While impressive, repurposing Celerity's saferepr()
#implementation for @beartype will be non-trivial; that function internally
#leverages a number of non-trivial internal functions, including a
#streaming iterator that appears to be performing some sort of ad-hoc
#tokenization (!) on the input object's string representation. Although
#that submodule is less than 300 lines, that's 300 *INTENSE* lines.
#Nonetheless, we'll need to do this sooner or later. Currently, later. By
#the time you read this next, probably sooner. Until someone pounds their
#fists on our issue tracker, let's pretend this isn't a compelling concern.
#See also:
# https://github.com/celery/celery/blob/master/celery/utils/saferepr.py
# String describing this object. Note that:
# * This representation quote-protects all newlines in this representation.
# Ergo, "\n" *MUST* be matched as r"\n" instead below.
# * For debuggability, the verbose (albeit less readable) output of repr()
# is preferred to the terse (albeit more readable) output of str().
# * For safety, the pprint.saferepr() function explicitly protected against
# recursive data structures *WOULD* typically be preferred to the unsafe
# repr() builtin *NOT* protected against such recursion. Sadly,
# pprint.saferepr() is extremely unoptimized and thus susceptible to
# extreme performance regressions when passed a worst-case object (e.g.,
# deeply nested container).
obj_repr = repr(obj)
#FIXME: Uncomment to exhibit a performance regression.
# from pprint import saferepr
# obj_repr = saferepr(obj)
# If this representation is empty, return empty double-quotes. Although
# most objects (including outlier singletons like "None" and the empty
# string) have non-empty representations, caller-defined classes may
# maliciously override the __repr__() dunder method to return an empty
# string rather than the representation of an empty string (i.e., '""').
if not obj_repr:
return '""'
# Else, this representation is non-empty.
#
# If this representation is neither...
elif not (
# Prefixed by punctuation *NOR*...
obj_repr[0] in _CHARS_PUNCTUATION or
# An instance of a class whose representations do *NOT* benefit from
# explicit quoting...
isinstance(obj, _TYPES_UNQUOTABLE)
):
# Then this representation is *NOT* demarcated from preceding characters in
# the parent string embedding this representation. In this case,
# double-quote this representation for disambiguity with preceding
# characters (e.g., sequence indices).
obj_repr = f'"{obj_repr}"'
# If this representation exceeds this maximum length...
if len(obj_repr) > max_len:
# If this maximum length is long enough to at least allow truncation to
# ellipses (i.e., a substring of length 3)...
if max_len > 3:
# Last character of this representation.
obj_repr_char_last = obj_repr[max_len-1]
# If this character is punctuation, preserve this punctuation by
# replacing the trailing portion of this representation up to but
# *NOT* including this punctuation with an ellipses.
if obj_repr_char_last in _CHARS_PUNCTUATION:
obj_repr = f'{obj_repr[:max_len-4]}...{obj_repr_char_last}'
# Else, this character is *NOT* punctuation. In this case, replace
# the trailing portion of this representation (including this
# character) with an ellipses.
else:
obj_repr = f'{obj_repr[:max_len-3]}...'
# Else, this maximum length is *NOT* long enough to at least allow
# truncation to ellipses (i.e., a substring of length 3). In this case,
# truncate this string to this length *WITHOUT* ellipses.
else:
obj_repr = obj_repr[:max_len]
# print(f'obj repr truncated: {obj_repr}')
# Return this representation.
return obj_repr
# ....................{ REPRESENTER ~ callable }....................
def represent_func(
# Mandatory parameters.
func: Callable,
# Optional parameters.
warning_cls: TypeWarning = _BeartypeUtilCallableWarning,
) -> str:
'''
Machine-readable representation of the passed callable.
Caveats
----------
**This function is unavoidably slow and should thus not be called from
optimized performance-critical code.** This function internally performs
extremely expensive operations, including abstract syntax tree (AST)-based
parsing of Python scripts and modules deserialized from disk. Ideally, this
function should *only* be called to create user-oriented exception messages
where performance is a negligible concern.
Parameters
----------
func : Callable
Callable to be represented.
warning_cls : TypeWarning, optional
Type of warning to be emitted in the event of a non-fatal error.
Defaults to :class:`_BeartypeUtilCallableWarning`.
Warns
----------
:class:`warning_cls`
If this callable is a pure-Python lambda function whose definition is
*not* parsable from the script or module defining that lambda.
'''
assert callable(func), f'{repr(func)} not callable.'
# Avoid circular import dependencies.
from beartype._util.func.utilfunccode import get_func_code_or_none
from beartype._util.func.utilfunctest import is_func_lambda
# If this callable is a pure-Python lambda function, return either:
# * If this lambda is defined by an on-disk script or module source file,
# the exact substring of that file defining this lambda.
# * Else (e.g., if this lambda is dynamically defined in-memory), a
# placeholder string.
if is_func_lambda(func):
return (
get_func_code_or_none(func=func, warning_cls=warning_cls) or
'<lambda>'
)
# Else, this callable is *NOT* a pure-Python lambda function.
# Return the fully-qualified name of this non-lambda function.
return get_object_basename_scoped(func)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype exception handling utilities.**
This private submodule implements supplementary exception-handling utility
functions required by various :mod:`beartype` facilities, including callables
generating code for the :func:`beartype.beartype` decorator.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ CONSTANTS }....................
EXCEPTION_PLACEHOLDER = '$%ROOT_PITH_LABEL/~'
'''
Non-human-readable source substring to be globally replaced by a human-readable
target substring in the messages of memoized exceptions passed to the
:func:`reraise_exception` function.
This substring prefixes most exception messages raised by memoized callables,
including code generation factories memoized on passed PEP-compliant type hints
(e.g., the :mod:`beartype._check` and :mod:`beartype._decor` submodules). The
:func:`beartype._util.error.utilerror.reraise_exception_placeholder` function
then dynamically replaces this prefix of the message of the passed exception
with a human-readable synopsis of the current unmemoized exception context,
including the name of both the currently decorated callable *and* the currently
iterated parameter or return of that callable for aforementioned code generation
factories.
Usage
----------
This substring is typically hard-coded into non-human-readable exception
messages raised by low-level callables memoized with the
:func:`beartype._util.cache.utilcachecall.callable_cached` decorator. Why?
Memoization prohibits those callables from raising human-readable exception
messages. Why? Doing so would require those callables to accept fine-grained
parameters unique to each call to those callables, which those callables would
then dynamically format into human-readable exception messages raised by those
callables. The standard example would be a ``exception_prefix`` parameter
labelling the human-readable category of type hint being inspected by the
current call (e.g., ``@beartyped muh_func() parameter "muh_param" PEP type hint
"List[int]"`` for a ``List[int]`` type hint on the `muh_param` parameter of a
``muh_func()`` function decorated by the :func:`beartype.beartype` decorator).
Since the whole point of memoization is to cache callable results between calls,
any callable accepting any fine-grained parameter unique to each call to that
callable is effectively *not* memoizable in any meaningful sense of the
adjective "memoizable." Ergo, memoized callables *cannot* raise human-readable
exception messages unique to each call to those callables.
This substring indirectly solves this issue by inverting the onus of human
readability. Rather than requiring memoized callables to raise human-readable
exception messages unique to each call to those callables (which we've shown
above to be pragmatically infeasible), memoized callables instead raise
non-human-readable exception messages containing this substring where they
instead would have contained the human-readable portions of their messages
unique to each call to those callables. This indirection renders exceptions
raised by memoized callables generic between calls and thus safely memoizable.
This indirection has the direct consequence, however, of shifting the onus of
human readability from those lower-level memoized callables onto higher-level
non-memoized callables -- which are then required to explicitly (in order):
#. Catch exceptions raised by those lower-level memoized callables.
#. Call the :func:`reraise_exception_placeholder` function with those
exceptions and desired human-readable substrings. That function then:
#. Replaces this magic substring hard-coded into those exception messages
with those human-readable substring fragments.
#. Reraises the original exceptions in a manner preserving their original
tracebacks.
Unsurprisingly, as with most inversion of control schemes, this approach is
non-intuitive. Surprisingly, however, the resulting code is actually *more*
elegant than the standard approach of raising human-readable exceptions from
low-level callables. Why? Because the standard approach percolates
human-readable substring fragments from the higher-level callables defining
those fragments to the lower-level callables raising exception messages
containing those fragments. The indirect approach avoids percolation, thus
streamlining the implementations of all callables involved. Phew!
'''
# ....................{ RAISERS }....................
def reraise_exception_placeholder(
# Mandatory parameters.
exception: Exception,
target_str: str,
# Optional parameters.
source_str: str = EXCEPTION_PLACEHOLDER,
) -> None:
'''
Reraise the passed exception in a safe manner preserving both this
exception object *and* the original traceback associated with this
exception object, but globally replacing all instances of the passed source
substring hard-coded into this exception's message with the passed target
substring.
Parameters
----------
exception : Exception
Exception to be reraised.
target_str : str
Target human-readable format substring to replace the passed source
substring previously hard-coded into this exception's message.
source_str : Optional[str]
Source non-human-readable substring previously hard-coded into this
exception's message to be replaced by the passed target substring.
Defaults to :data:`EXCEPTION_PLACEHOLDER`.
Raises
----------
exception
The passed exception, globally replacing all instances of this source
substring in this exception's message with this target substring.
See Also
----------
:data:`EXCEPTION_PLACEHOLDER`
Further commentary on usage and motivation.
https://stackoverflow.com/a/62662138/2809027
StackOverflow answer mildly inspiring this implementation.
Examples
----------
>>> from beartype.roar import BeartypeDecorHintPepException
>>> from beartype._util.cache.utilcachecall import callable_cached
>>> from beartype._util.error.utilerror import (
... reraise_exception_placeholder, EXCEPTION_PLACEHOLDER)
>>> from random import getrandbits
>>> @callable_cached
... def portend_low_level_winter(is_winter_coming: bool) -> str:
... if is_winter_coming:
... raise BeartypeDecorHintPepException(
... '{} intimates that winter is coming.'.format(
... EXCEPTION_PLACEHOLDER))
... else:
... return 'PRAISE THE SUN'
>>> def portend_high_level_winter() -> None:
... try:
... print(portend_low_level_winter(is_winter_coming=False))
... print(portend_low_level_winter(is_winter_coming=True))
... except BeartypeDecorHintPepException as exception:
... reraise_exception_placeholder(
... exception=exception,
... target_str=(
... 'Random "Song of Fire and Ice" spoiler' if getrandbits(1) else
... 'Random "Dark Souls" plaintext meme'
... ))
>>> portend_high_level_winter()
PRAISE THE SUN
Traceback (most recent call last):
File "<input>", line 30, in <module>
portend_high_level_winter()
File "<input>", line 27, in portend_high_level_winter
'Random "Dark Souls" plaintext meme'
File "/home/leycec/py/beartype/beartype._util.error.utilerror.py", line 225, in reraise_exception_placeholder
raise exception.with_traceback(exception.__traceback__)
File "<input>", line 20, in portend_high_level_winter
print(portend_low_level_winter(is_winter_coming=True))
File "/home/leycec/py/beartype/beartype/_util/cache/utilcachecall.py", line 296, in _callable_cached
raise exception
File "/home/leycec/py/beartype/beartype/_util/cache/utilcachecall.py", line 289, in _callable_cached
*args, **kwargs)
File "<input>", line 13, in portend_low_level_winter
EXCEPTION_PLACEHOLDER))
beartype.roar.BeartypeDecorHintPepException: Random "Song of Fire and Ice" spoiler intimates that winter is coming.
'''
assert isinstance(exception, Exception), (
f'{repr(exception)} not exception.')
assert isinstance(source_str, str), f'{repr(source_str)} not string.'
assert isinstance(target_str, str), f'{repr(target_str)} not string.'
# If...
if (
# Exception arguments are a tuple (as is typically but not necessarily
# the case) *AND*...
isinstance(exception.args, tuple) and
# This tuple is non-empty (as is typically but not necessarily the
# case) *AND*...
exception.args and
# The first item of this tuple is a string providing this exception's
# message (as is typically but not necessarily the case)...
isinstance(exception.args[0], str)
# Then this is a conventional exception. In this case...
):
# Munged exception message globally replacing all instances of this
# source substring with this target substring.
#
# Note that we intentionally call the lower-level str.replace() method
# rather than the higher-level
# beartype._util.text.utiltextmunge.replace_str_substrs() function
# here, as the latter unnecessarily requires this exception message to
# contain one or more instances of this source substring.
exception_message = exception.args[0].replace(source_str, target_str)
# If doing so actually changed this message...
if exception_message != exception.args[0]:
# Reconstitute this exception argument tuple from this message.
#
# Note that if this tuple contains only this message, this slice
# "exception.args[1:]" safely yields the empty tuple. Go, Python!
exception.args = (exception_message,) + exception.args[1:]
# Else, this message remains preserved as is.
# Else, this is an unconventional exception. In this case, preserve this
# exception as is.
# Re-raise this exception while preserving its original traceback.
raise exception.with_traceback(exception.__traceback__)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Python module getter** (i.e., callables dynamically retrieving
modules and/or attributes in modules) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilModuleException
from beartype.typing import Optional
from inspect import findsource
from types import ModuleType
# ....................{ GETTERS ~ object : line }....................
def get_object_module_line_number_begin(obj: object) -> int:
'''
**Line number** (i.e., 1-based index) of the first line of the source code
of the module declaring the passed object if this object is either a
callable or class *or* raise an exception otherwise (i.e., if this object is
neither a callable nor class).
Parameters
----------
obj : object
Object to be inspected.
Returns
----------
int
1-based index of the first line of the source code of the module
declaring the passed object.
Raises
----------
_BeartypeUtilModuleException
If this object is neither a callable nor class.
'''
# If this object is a class, defer to the standard "inspect" module.
#
# Note that:
# * Deciding whether an object is a class is slightly faster than deciding
# whether an object is a callable. The former trivially reduces to a
# single isinstance() call against a single superclass; the latter is
# considerably less trivial. Ergo, this object is tested as a class first.
# * Deciding the line number of the first line declaring an arbitrary class
# in its underlying source code module file is highly non-trivial (and in
# fact requires extremely slow AST-based parsing). For maintainability and
# robustness, we defer to the well-tested standard "inspect" module
# despite the performance hit in doing so.
if isinstance(obj, type):
_, cls_source_line_number_start = findsource(obj)
return cls_source_line_number_start
# Else, this object is *NOT* a class.
# Avoid circular import dependencies.
from beartype._util.func.utilfunccodeobj import get_func_codeobj_or_none
# Code object underlying this object if this object is a pure-Python
# callable *OR* "None" otherwise.
#
# Note this is the canonical means of deciding whether an arbitrary object
# is a pure-Python callable, as our is_func_python() function demonstrates.
func_codeobj = get_func_codeobj_or_none(obj)
# If this object is a pure-Python callable, return the line number of the
# first line declaring this object in its underlying source code file.
if func_codeobj is not None:
return func_codeobj.co_firstlineno
# Else, this object is neither a pure-Python callable *NOR* a class.
# In this case, raise an exception.
raise _BeartypeUtilModuleException(
f'{repr(obj)} neither callable nor class.')
# ....................{ GETTERS ~ object : name }....................
def get_object_module_name(obj: object) -> str:
'''
**Fully-qualified name** (i.e., ``.``-delimited name prefixed by the
declaring package) of the module declaring the passed object if this
object defines the ``__module__`` dunder instance variable *or* ``None``
otherwise.
Parameters
----------
obj : object
Object to be inspected.
Returns
----------
str
Fully-qualified name of the module declaring this object.
Raises
----------
_BeartypeUtilModuleException
If this object does *not* define the ``__module__`` dunder instance
variable.
'''
# Fully-qualified name of the module declaring this object if this object
# defines the "__module__" dunder instance variable *OR* "None" otherwise.
module_name = get_object_module_name_or_none(obj)
# If this object defines *NO* "__module__" dunder instance variable, raise
# an exception.
if module_name is None:
raise _BeartypeUtilModuleException(
f'{repr(obj)} "__module__" dunder attribute undefined '
f'(e.g., due to being neither class nor callable).'
)
# Else, this fully-qualified module name exists.
# Return this name.
return module_name
def get_object_module_name_or_none(obj: object) -> Optional[str]:
'''
**Fully-qualified name** (i.e., ``.``-delimited name prefixed by the
declaring package) of the module declaring the passed object if this object
defines the ``__module__`` dunder instance variable *or* ``None``
otherwise.
Parameters
----------
obj : object
Object to be inspected.
Returns
----------
Optional[str]
Either:
* Fully-qualified name of the module declaring this object if this
object declares a ``__module__`` dunder attribute.
* ``None`` otherwise.
'''
# Let it be, speaking one-liners of wisdom.
return getattr(obj, '__module__', None)
def get_object_type_module_name_or_none(obj: object) -> Optional[str]:
'''
**Fully-qualified name** (i.e., ``.``-delimited name prefixed by the
declaring package) of the module declaring either the passed object if this
object is a class *or* the class of this object otherwise (i.e., if this
object is *not* a class) if this class declares the ``__module__`` dunder
instance variable *or* ``None`` otherwise.
Parameters
----------
obj : object
Object to be inspected.
Returns
----------
Optional[str]
Either:
* Fully-qualified name of the module declaring the type of this object
if this type declares a ``__module__`` dunder attribute.
* ``None`` otherwise.
'''
# Avoid circular import dependencies.
from beartype._util.utilobject import get_object_type_unless_type
# Make it so, ensign.
return get_object_module_name_or_none(get_object_type_unless_type(obj))
# ....................{ GETTERS ~ module : file }....................
#FIXME: Unit test us up.
def get_module_filename(module: ModuleType) -> str:
'''
Absolute filename of the passed module if this module is physically defined
on disk *or* raise an exception otherwise (i.e., if this module is
abstractly defined in memory).
Parameters
----------
module : ModuleType
Module to be inspected.
Returns
----------
str
Absolute filename of this on-disk module.
Raises
----------
_BeartypeUtilModuleException
If this module *only* resides in memory.
'''
# Absolute filename of this module if on-disk *OR* "None" otherwise.
module_filename = get_module_filename_or_none(module)
# If this module resides *ONLY* in memory, raise an exception.
if module_filename is None:
raise _BeartypeUtilModuleException(
f'Module {repr(module)} not on disk.')
# Else, this module resides on disk.
# Return this filename.
return module_filename
#FIXME: Unit test us up.
def get_module_filename_or_none(module: ModuleType) -> Optional[str]:
'''
Absolute filename of the passed module if this module is physically defined
on disk *or* ``None`` otherwise (i.e., if this module is abstractly defined
in memory).
Parameters
----------
module : ModuleType
Module to be inspected.
Returns
----------
Optional[str]
Either:
* Absolute filename of this module if this module resides on disk.
* ``None`` if this module *only* resides in memory.
'''
# Thus spake Onelinerthustra.
return getattr(module, '__file__', None)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Python module deprecation** utilities (i.e., callables
deprecating arbitrary module attributes in a reusable fashion).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# WARNING: To avoid circular import dependencies, avoid importing from *ANY*
# package-specific submodule either here or in the body of any callable defined
# by this submodule. This submodule is typically called from the "__init__"
# submodules of public subpackages.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
from beartype.typing import Any, Dict
from beartype._util.utilobject import SENTINEL
from warnings import warn
# ....................{ IMPORTERS }....................
def deprecate_module_attr(
attr_deprecated_name: str,
attr_deprecated_name_to_nondeprecated_name: Dict[str, str],
attr_nondeprecated_name_to_value: Dict[str, Any],
) -> object:
'''
Dynamically retrieve a deprecated attribute with the passed unqualified
name mapped by the passed dictionary to a corresponding non-deprecated
attribute from the submodule with the passed dictionary of globally scoped
attributes and emit a non-fatal deprecation warning on each
such retrieval if that submodule defines this attribute *or* raise an
exception otherwise.
This function is intended to be called by :pep:`562`-compliant globally
scoped ``__getattr__()`` dunder functions, which the Python interpreter
implicitly calls under Python >= 3.7 *after* failing to directly retrieve
an explicit attribute with this name from that submodule.
Parameters
----------
attr_deprecated_name : str
Unqualified name of the deprecated attribute to be retrieved.
attr_deprecated_name_to_nondeprecated_name : Dict[str, str]
Dictionary mapping from the unqualified name of each deprecated
attribute retrieved by this function to either:
* If that submodule defines a corresponding non-deprecated attribute,
the unqualified name of that attribute.
* If that submodule is deprecating that attribute *without* defining a
corresponding non-deprecated attribute, ``None``.
attr_nondeprecated_name_to_value : Dict[str, object]
Dictionary mapping from the unqualified name to value of each
module-scoped attribute defined by the caller's submodule, typically
passed as the ``globals()`` builtin. This function intentionally does
*not* implicitly inspect this dictionary from the call stack, as call
stack inspection is non-portable under Python.
Returns
----------
object
Value of this deprecated attribute.
Warns
----------
DeprecationWarning
If this attribute is deprecated.
Raises
----------
AttributeError
If this attribute is unrecognized and thus erroneous.
ImportError
If the passed ``attr_nondeprecated_name_to_value`` dictionary fails to
define the non-deprecated variant of the passed deprecated attribute
mapped to by the passed ``attr_deprecated_name_to_nondeprecated_name``
dictionary.
See Also
----------
https://www.python.org/dev/peps/pep-0562/#id8
:pep:`562`-compliant dunder function inspiring this implementation.
'''
assert isinstance(attr_deprecated_name, str), (
f'{repr(attr_deprecated_name)} not string.')
assert isinstance(attr_deprecated_name_to_nondeprecated_name, dict), (
f'{repr(attr_deprecated_name_to_nondeprecated_name)} not dictionary.')
assert isinstance(attr_nondeprecated_name_to_value, dict), (
f'{repr(attr_nondeprecated_name_to_value)} not dictionary.')
# Fully-qualified name of the caller's submodule. Since all physical
# submodules (i.e., those defined on-disk) define this dunder attribute
# *AND* this function is only ever called by such submodules, this
# attribute is effectively guaranteed to exist.
MODULE_NAME = attr_nondeprecated_name_to_value['__name__']
# Unqualified name of the non-deprecated attribute originating this
# deprecated attribute if this attribute is deprecated *OR* the sentinel.
attr_nondeprecated_name = attr_deprecated_name_to_nondeprecated_name.get(
attr_deprecated_name, SENTINEL)
# If this attribute is deprecated...
if attr_nondeprecated_name is not SENTINEL:
assert isinstance(attr_nondeprecated_name, str), (
f'{repr(attr_nondeprecated_name)} not string.')
# Value of the non-deprecated attribute originating this deprecated
# attribute if the former exists *OR* the sentintel.
attr_nondeprecated_value = attr_nondeprecated_name_to_value.get(
attr_nondeprecated_name, SENTINEL)
# If that module fails to define this non-deprecated attribute, raise
# an exception.
#
# Note that:
# * This should *NEVER* happen but surely will. In fact, this just did.
# * This intentionally raises an beartype-agnostic "ImportError"
# exception rather than a beartype-specific exception. Why? Because
# this function is *ONLY* ever called by the module-scoped
# __getattr__() dunder function in the "__init__.py" submodules
# defining public namespaces of public packages. In turn, that
# __getattr__() dunder function is only ever implicitly called by
# Python's non-trivial import machinery. For unknown reasons, that
# machinery silently ignores *ALL* exceptions raised by that
# __getattr__() dunder function and thus raised by this function
# *EXCEPT* "ImportError" exceptions. Of necessity, we have *NO*
# recourse but to defer to Python's poorly documented API constraints.
if attr_nondeprecated_value is SENTINEL:
raise ImportError(
f'Deprecated attribute '
f'"{attr_deprecated_name}" in submodule "{MODULE_NAME}" '
f'originates from missing non-deprecated attribute '
f'"{attr_nondeprecated_name}" not defined by that submodule.'
)
# Else, that module defines this non-deprecated attribute.
# Substring suffixing the warning message emitted below.
warning_suffix = ''
# If this deprecated attribute originates from a public non-deprecated
# attribute, inform users of the existence of the latter.
if not attr_nondeprecated_name.startswith('_'):
warning_suffix = (
f' Please globally replace all references to this '
f'attribute with its non-deprecated equivalent '
f'"{attr_nondeprecated_name}" from the same submodule.'
)
# Else, this deprecated attribute originates from a private
# non-deprecated attribute. In this case, avoid informing users of the
# existence of the latter.
# Emit a non-fatal warning of the standard "DeprecationWarning"
# category, which CPython filters (ignores) by default.
#
# Note that we intentionally do *NOT* emit a non-fatal warning of our
# non-standard "BeartypeDecorHintPepDeprecationWarning" category, which
# applies *ONLY* to PEP-compliant type hint deprecations.
warn(
(
f'Deprecated attribute '
f'"{attr_deprecated_name}" in submodule "{MODULE_NAME}" '
f'scheduled for removal under a future release.'
f'{warning_suffix}'
),
DeprecationWarning,
)
# Return the value of this deprecated attribute.
return attr_nondeprecated_value
# Else, this attribute is *NOT* deprecated. Since Python called this dunder
# function, this attribute is undefined and thus erroneous.
# Raise the same exception raised by Python on accessing a non-existent
# attribute of a module *NOT* defining this dunder function.
#
# Note that Python's non-trivial import machinery silently coerces this
# "AttributeError" exception into an "ImportError" exception. Just do it!
raise AttributeError(
f"module '{MODULE_NAME}' has no attribute '{attr_deprecated_name}'")
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Python module tester** (i.e., callables dynamically testing
modules and/or attributes in modules) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.meta import _convert_version_str_to_tuple
from beartype.roar._roarexc import _BeartypeUtilModuleException
from beartype._data.datatyping import TypeException
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_8
# ....................{ VALIDATORS }....................
def die_unless_module_attr_name(
# Mandatory parameters.
module_attr_name: str,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilModuleException,
exception_prefix: str = 'Module attribute name ',
) -> None:
'''
Raise an exception unless the passed string is the fully-qualified
syntactically valid name of a **module attribute** (i.e., object declared
at module scope by a module) that may or may not actually exist.
This validator does *not* validate this attribute to actually exist -- only
that the name of this attribute is syntactically valid.
Parameters
----------
module_attr_name : str
Fully-qualified name of the module attribute to be validated.
exception_cls : type, optional
Type of exception to be raised. Defaults to
:class:`_BeartypeUtilModuleException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to something reasonably sane.
Raises
----------
:exc:`exception_cls`
If either:
* This name is *not* a string.
* This name is a string containing either:
* *No* ``.`` characters and thus either:
* Is relative to the calling subpackage and thus *not*
fully-qualified (e.g., ``muh_submodule``).
* Refers to a builtin object (e.g., ``str``). While technically
fully-qualified, the names of builtin objects are *not*
explicitly importable as is. Since these builtin objects are
implicitly imported everywhere, there exists *no* demonstrable
reason to even attempt to import them anywhere.
* One or more ``.`` characters but syntactically invalid as an
identifier (e.g., ``0h!muh?G0d.``).
'''
assert isinstance(exception_cls, type), f'{repr(exception_cls)} not type.'
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Avoid circular import dependencies.
from beartype._util.text.utiltextident import is_identifier
# If this object is *NOT* a string, raise an exception.
if not isinstance(module_attr_name, str):
raise exception_cls(
f'{exception_prefix}{repr(module_attr_name)} not string.')
# Else, this object is a string.
#
# If this string contains *NO* "." characters and thus either is relative
# to the calling subpackage or refers to a builtin object, raise an
# exception.
elif '.' not in module_attr_name:
raise exception_cls(
f'{exception_prefix}"{module_attr_name}" '
f'relative or refers to builtin object '
f'(i.e., due to containing no "." characters).'
)
# Else, this string contains one or more "." characters and is thus the
# fully-qualified name of a non-builtin type.
#
# If this string is syntactically invalid as a fully-qualified module
# attribute name, raise an exception.
elif not is_identifier(module_attr_name):
raise exception_cls(
f'{exception_prefix}"{module_attr_name}" '
f'syntactically invalid as module attribute name.'
)
# Else, this string is syntactically valid as a fully-qualified module
# attribute name.
# ....................{ TESTERS }....................
def is_module(module_name: str) -> bool:
'''
``True`` only if the module or C extension with the passed fully-qualified
name is importable under the active Python interpreter.
Caveats
----------
**This tester dynamically imports this module as an unavoidable side effect
of performing this test.**
Parameters
----------
module_name : str
Fully-qualified name of the module to be imported.
Returns
----------
bool
``True`` only if this module is importable.
Warns
----------
BeartypeModuleUnimportableWarning
If a module with this name exists *but* that module is unimportable
due to raising module-scoped exceptions at importation time.
'''
# Avoid circular import dependencies.
from beartype._util.mod.utilmodimport import import_module_or_none
# Module with this name if this module is importable *OR* "None" otherwise.
module = import_module_or_none(module_name)
# Return true only if this module is importable.
return module is not None
#FIXME: Unit test us up against "setuptools", the only third-party package
#*BASICALLY* guaranteed to be importable.
def is_module_version_at_least(module_name: str, version_minimum: str) -> bool:
'''
``True`` only if the module or C extension with the passed fully-qualified
name is both importable under the active Python interpreter *and* at least
as new as the passed version.
Caveats
----------
**This tester dynamically imports this module as an unavoidable side effect
of performing this test.**
Parameters
----------
module_name : str
Fully-qualified name of the module to be imported.
version_minimum : str
Minimum version to test this module against as a dot-delimited
:pep:`440`-compliant version specifier (e.g., ``42.42.42rc42.post42``).
Returns
----------
bool
``True`` only if:
* This module is importable.
* This module's version is at least the passed version.
Warns
----------
BeartypeModuleUnimportableWarning
If a module with this name exists *but* that module is unimportable
due to raising module-scoped exceptions at importation time.
'''
# If it is *NOT* the case that...
if not (
# This module is importable *AND*...
is_module(module_name) and
# Either...
(
# The active Python interpreter targets Python >= 3.8 and thus
# provides the "importlib.metadata" API required to portably
# inspect module versions without requiring obsolete third-party
# packages (e.g., "pkg_resources") *OR*...
IS_PYTHON_AT_LEAST_3_8 or
# The active Python interpreter targets Python < 3.8 but the
# obsolete third-party package "pkg_resources" is importable...
is_package('pkg_resources')
)
):
# Then this module is either unimportable *OR* no API capable of inspecting
# module versions is importable. In either case, return false to avoid
# returning false positives.
return False
assert isinstance(version_minimum, str), (
f'{repr(version_minimum)} not string.')
# If the active Python interpreter targets Python >= 3.8...
if IS_PYTHON_AT_LEAST_3_8:
# Defer version-specific imports.
from importlib.metadata import version as get_module_version # type: ignore[attr-defined]
# Current version of this module installed under the active Python
# interpreter if any *OR* raise an exception otherwise (which should
# *NEVER* happen by prior logic testing this module to be importable).
version_actual = get_module_version(module_name)
# Tuples of version parts parsed from version strings.
version_actual_parts = _convert_version_str_to_tuple(version_actual)
version_minimum_parts = _convert_version_str_to_tuple(version_minimum)
# Return true only if this module's version satisfies this minimum.
return version_actual_parts >= version_minimum_parts
# Else, the active Python interpreter targets Python < 3.8 but the obsolete
# third-party package "pkg_resources" is importable by the above logic. In
# this case...
else:
# Defer imports from optional third-party dependencies.
from pkg_resources import (
DistributionNotFound,
UnknownExtra,
VersionConflict,
get_distribution,
parse_requirements,
)
# Setuptools-specific requirements string constraining this module.
module_requirement_str = f'{module_name} >= {version_minimum}'
# Setuptools-specific requirements object parsed from this string. Yes,
# setuptools insanely requires this parsing to be performed through a
# generator -- even when only parsing a single requirements string.
module_requirement = None
for module_requirement in parse_requirements(module_requirement_str):
break
# Attempt to...
try:
# Setuptools-specific object describing the current version of the
# module satisfying this requirement if any *OR* "None" if this
# requirement cannot be guaranteed to be unsatisfied.
module_distribution = get_distribution(module_requirement) # pyright: ignore[reportGeneralTypeIssues]
# If setuptools fails to find this requirement, this does *NOT*
# necessarily imply this requirement to be unimportable as a package.
# Rather, this only implies this requirement was *NOT* installed as a
# setuptools-managed egg. This requirement is still installable and
# hence importable (e.g., by manually copying this requirement's
# package into the "site-packages" subdirectory of the top-level
# directory for this Python interpreter). However, does this edge-case
# actually occur in reality? *YES.* PyInstaller-frozen applications
# embed requirements without corresponding setuptools-managed eggs.
# Hence, this edge-case *MUST* be handled.
except DistributionNotFound:
module_distribution = None
# If setuptools fails to find the distribution-packaged version of this
# requirement (e.g., due to having been editably installed with "sudo
# python3 setup.py develop"), this version may still be manually
# parseable from this requirement's package. Since setuptools fails to
# raise an exception whose type is unique to this error condition, the
# contents of this exception are parsed to distinguish this expected
# error condition from other unexpected error conditions. In the former
# case, a non-human-readable exception resembling the following is
# raised:
# ValueError: "Missing 'Version:' header and/or PKG-INFO file",
# networkx [unknown version] (/home/leycec/py/networkx)
except ValueError as version_missing:
# If this exception was...
if (
# ...instantiated with two arguments...
len(version_missing.args) == 2 and
# ...whose second argument is suffixed by a string indicating
# the version of this distribution to have been ignored rather
# than recorded during installation...
str(version_missing.args[1]).endswith(' [unknown version]')
# ...this exception indicates an expected ignorable error
# condition. Silently ignore this edge case.
):
module_distribution = None
# Else, this exception indicates an unexpected and thus unignorable
# error condition.
# Reraise this exception, please.
raise
# If setuptools found only requirements of insufficient version, all
# currently installed versions of this module fail to satisfy this
# requirement. In this case, immediately return false.
except (UnknownExtra, VersionConflict):
return False
# If any other exception is raised, expose this exception as is.
# Return true only if this requirement is satisfied.
return module_distribution is not None
# ....................{ TESTERS ~ package }....................
#FIXME: Unit test us up, please.
def is_package(package_name: str) -> bool:
'''
``True`` only if the package with the passed fully-qualified name is
importable under the active Python interpreter.
Caveats
----------
**This tester dynamically imports this module as an unavoidable side effect
of performing this test.**
Parameters
----------
package_name : str
Fully-qualified name of the package to be imported.
Returns
----------
bool
``True`` only if this package is importable.
Warns
----------
:class:`BeartypeModuleUnimportableWarning`
If a package with this name exists *but* that package is unimportable
due to raising module-scoped exceptions from the top-level `__init__`
submodule of this package at importation time.
'''
# Be the one liner you want to see in the world.
return is_module(f'{package_name}.__init__')
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Python module importer** utilities (i.e., callables dynamically
importing modules and/or attributes from modules).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar import BeartypeModuleUnimportableWarning
from beartype.roar._roarexc import _BeartypeUtilModuleException
from beartype.typing import (
Any,
Optional,
)
from beartype._data.datatyping import TypeException
from importlib import import_module as importlib_import_module
from sys import modules as sys_modules
from types import ModuleType
from warnings import warn
# ....................{ IMPORTERS }....................
#FIXME: Preserved until requisite, which shouldn't be long.
#FIXME: Unit test us up.
# def import_module(
# # Mandatory parameters.
# module_name: str,
#
# # Optional parameters.
# exception_cls: TypeException = _BeartypeUtilModuleException,
# ) -> ModuleType:
# '''
# Dynamically import and return the module, package, or C extension with the
# passed fully-qualified name if importable *or* raise an exception
# otherwise (i.e., if that module, package, or C extension is unimportable).
#
# Parameters
# ----------
# module_name : str
# Fully-qualified name of the module to be imported.
# exception_cls : type
# Type of exception to be raised by this function. Defaults to
# :class:`_BeartypeUtilModuleException`.
#
# Raises
# ----------
# exception_cls
# If no module with this name exists.
# Exception
# If a module with this name exists *but* that module is unimportable
# due to raising module-scoped exceptions at importation time. Since
# modules may perform arbitrary Turing-complete logic at module scope,
# callers should be prepared to handle *any* possible exception.
# '''
# assert isinstance(exception_cls, type), (
# f'{repr(exception_cls)} not type.')
#
# # Module with this name if this module is importable *OR* "None" otherwise.
# module = import_module_or_none(module_name)
#
# # If this module is unimportable, raise an exception.
# if module is None:
# raise exception_cls(
# f'Module "{module_name}" not found.') from exception
# # Else, this module is importable.
#
# # Return this module.
# return module
def import_module_or_none(module_name: str) -> Optional[ModuleType]:
'''
Dynamically import and return the module, package, or C extension with the
passed fully-qualified name if importable *or* return ``None`` otherwise
(i.e., if that module, package, or C extension is unimportable).
For safety, this function also emits a non-fatal warning when that module,
package, or C extension exists but is still unimportable (e.g., due to
raising an exception at module scope).
Parameters
----------
module_name : str
Fully-qualified name of the module to be imported.
Warns
----------
BeartypeModuleUnimportableWarning
If a module with this name exists *but* that module is unimportable
due to raising module-scoped exceptions at importation time.
'''
assert isinstance(module_name, str), f'{repr(module_name)} not string.'
# Module cached with "sys.modules" if this module has already been imported
# elsewhere under the active Python interpreter *OR* "None" otherwise.
module = sys_modules.get(module_name)
# If this module has already been imported, return this cached module.
if module is not None:
return module
# Else, this module has yet to be imported.
# Attempt to dynamically import and return this module.
try:
return importlib_import_module(module_name)
# If this module does *NOT* exist, return "None".
except ModuleNotFoundError:
pass
# If this module exists but raises unexpected exceptions from module scope,
# first emit a non-fatal warning notifying the user and then return "None".
except Exception as exception:
warn(
(
f'Ignoring module "{module_name}" importation exception '
f'{exception.__class__.__name__}: {exception}'
),
BeartypeModuleUnimportableWarning,
)
# Inform the caller this module is unimportable.
return None
# ....................{ IMPORTERS ~ attr }....................
def import_module_attr(
# Mandatory parameters.
module_attr_name: str,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilModuleException,
exception_prefix: str = 'Module attribute ',
) -> Any:
'''
Dynamically import and return the **module attribute** (i.e., object
declared at module scope) with the passed fully-qualified name if
importable *or* raise an exception otherwise.
Parameters
----------
module_attr_name : str
Fully-qualified name of the module attribute to be imported.
exception_cls : Type[Exception]
Type of exception to be raised by this function. Defaults to
:class:`_BeartypeUtilModuleException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Returns
----------
object
The module attribute with this fully-qualified name.
Raises
----------
:exc:`exception_cls`
If either:
* This name is syntactically invalid.
* *No* module prefixed this name exists.
* A module prefixed by this name exists *but* that module declares no
attribute by this name.
Warns
----------
:class:`BeartypeModuleUnimportableWarning`
If a module prefixed by this name exists *but* that module is
unimportable due to module-scoped side effects at importation time.
See Also
----------
:func:`import_module_attr_or_none`
Further commentary.
'''
# Module attribute with this name if that module declares this attribute
# *OR* "None" otherwise.
module_attr = import_module_attr_or_none(
module_attr_name=module_attr_name,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# If this module declares *NO* such attribute, raise an exception.
if module_attr is None:
raise exception_cls(
f'{exception_prefix}"{module_attr_name}" unimportable.')
# Else, this module declares this attribute.
# Else, return this attribute.
return module_attr
def import_module_attr_or_none(
# Mandatory parameters.
module_attr_name: str,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilModuleException,
exception_prefix: str = 'Module attribute ',
) -> Any:
'''
Dynamically import and return the **module attribute** (i.e., object
declared at module scope) with the passed fully-qualified name if
importable *or* return ``None`` otherwise.
Parameters
----------
module_attr_name : str
Fully-qualified name of the module attribute to be imported.
exception_cls : Type[Exception]
Type of exception to be raised by this function. Defaults to
:class:`_BeartypeUtilModuleException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Returns
----------
object
Either:
* If *no* module prefixed this name exists, ``None``.
* If a module prefixed by this name exists *but* that module declares
no attribute by this name, ``None``.
* Else, the module attribute with this fully-qualified name.
Raises
----------
:exc:`exception_cls`
If this name is syntactically invalid.
Warns
----------
:class:`BeartypeModuleUnimportableWarning`
If a module with this name exists *but* that module is unimportable
due to raising module-scoped exceptions at importation time.
'''
# Avoid circular import dependencies.
from beartype._util.mod.utilmodtest import die_unless_module_attr_name
# If this object is *NOT* the fully-qualified syntactically valid name of a
# module attribute that may or may not actually exist, raise an exception.
die_unless_module_attr_name(
module_attr_name=module_attr_name,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this object is the fully-qualified syntactically valid name of a
# module attribute. In particular, this implies this name to contain one or
# more "." delimiters.
# Fully-qualified name of the module declaring this attribute *AND* the
# unqualified name of this attribute relative to this module, efficiently
# split from the passed name. By the prior validation, this split is
# guaranteed to be safe.
module_name, _, module_attr_basename = module_attr_name.rpartition('.')
# That module if importable *OR* "None" otherwise.
module = import_module_or_none(module_name)
# Return either...
return (
# If that module is importable, the module attribute with this name
# if that module declares this attribute *OR* "None" otherwise;
getattr(module, module_attr_basename, None)
if module is not None else
# Else, that module is unimportable. In this case, "None".
None
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **typing module** utilities (i.e., callables dynamically testing
and importing attributes declared at module scope by either the standard
:mod:`typing` or third-party :mod:`typing_extensions` modules).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilModuleException
from beartype.typing import Any
from beartype._data.datatyping import TypeException
from beartype._util.cache.utilcachecall import callable_cached
# ....................{ TESTERS }....................
#FIXME: Unit test us up, please.
def is_typing_attr(
# Mandatory parameters.
typing_attr_basename: str,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilModuleException,
) -> bool:
'''
``True`` only if a **typing attribute** (i.e., object declared at module
scope by either the :mod:`typing` or :mod:`typing_extensions` modules) with
the passed unqualified name is importable from one or more of these
modules.
This function is effectively memoized for efficiency.
Parameters
----------
typing_attr_basename : str
Unqualified name of the attribute to be imported from a typing module.
Returns
----------
bool
``True`` only if the :mod:`typing` or :mod:`typing_extensions` modules
declare an attribute with this name.
exception_cls : Type[Exception]
Type of exception to be raised by this function. Defaults to
:class:`_BeartypeUtilModuleException`.
Raises
----------
:exc:`exception_cls`
If this name is syntactically invalid.
Warns
----------
BeartypeModuleUnimportableWarning
If any of these modules raise module-scoped exceptions at importation
time. That said, the :mod:`typing` and :mod:`typing_extensions` modules
are scrupulously tested and thus unlikely to raise such exceptions.
'''
# Return true only if an attribute with this name is importable from either
# the "typing" *OR* "typing_extensions" modules.
#
# Note that positional rather than keyword arguments are intentionally
# passed to optimize memoization efficiency.
return import_typing_attr_or_none(
typing_attr_basename, exception_cls) is not None
# ....................{ IMPORTERS }....................
def import_typing_attr(
# Mandatory parameters.
typing_attr_basename: str,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilModuleException,
) -> Any:
'''
Dynamically import and return the **typing attribute** (i.e., object
declared at module scope by either the :mod:`typing` or
:mod:`typing_extensions` modules) with the passed unqualified name if
importable from one or more of these modules *or* raise an exception
otherwise (i.e., if this attribute is *not* importable from these modules).
This function is effectively memoized for efficiency.
Parameters
----------
typing_attr_basename : str
Unqualified name of the attribute to be imported from a typing module.
exception_cls : Type[Exception]
Type of exception to be raised by this function. Defaults to
:class:`_BeartypeUtilModuleException`.
Returns
----------
object
Attribute with this name dynamically imported from a typing module.
Raises
----------
:exc:`exception_cls`
If either:
* This name is syntactically invalid.
* Neither the :mod:`typing` nor :mod:`typing_extensions` modules
declare an attribute with this name.
Warns
----------
BeartypeModuleUnimportableWarning
If any of these modules raise module-scoped exceptions at importation
time. That said, the :mod:`typing` and :mod:`typing_extensions` modules
are scrupulously tested and thus unlikely to raise such exceptions.
See Also
----------
:func:`import_module_typing_any_attr_or_none`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.mod.utilmodtest import is_module
# Attribute with this name imported from either the "typing" or
# "typing_extensions" modules if one or more of these modules declare this
# attribute *OR* "None" otherwise.
#
# Note that positional rather than keyword arguments are intentionally
# passed to optimize memoization efficiency.
typing_attr = import_typing_attr_or_none(
typing_attr_basename, exception_cls)
# If none of these modules declare this attribute...
if typing_attr is None:
# Substrings prefixing and suffixing exception messages raised below.
EXCEPTION_PREFIX = (
f'Typing attributes "typing.{typing_attr_basename}" and '
f'"typing_extensions.{typing_attr_basename}" not found. '
)
EXCEPTION_SUFFIX = (
'We apologize for the inconvenience and hope you had a '
'great dev cycle flying with Air Beartype, '
'"Your Grizzled Pal in the Friendly Skies."'
)
# If the "typing_extensions" module is importable, raise an
# appropriate exception.
if is_module('typing_extensions'):
raise exception_cls(
f'{EXCEPTION_PREFIX} Please either '
f'(A) update the "typing_extensions" package or '
f'(B) update to a newer Python version. {EXCEPTION_SUFFIX}'
)
# Else, the "typing_extensions" module is unimportable. In this
# case, raise an appropriate exception.
else:
raise exception_cls(
f'{EXCEPTION_PREFIX} Please either '
f'(A) install the "typing_extensions" package or '
f'(B) update to a newer Python version. {EXCEPTION_SUFFIX}'
)
# Else, one or more of these modules declare this attribute.
# Return this attribute.
return typing_attr
#FIXME: Unit test us up, please.
def import_typing_attr_or_none(
# Mandatory parameters.
typing_attr_basename: str,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilModuleException,
) -> Any:
'''
Dynamically import and return the **typing attribute** (i.e., object
declared at module scope by either the :mod:`typing` or
:mod:`typing_extensions` modules) with the passed unqualified name if
importable from one or more of these modules *or* ``None`` otherwise
otherwise (i.e., if this attribute is *not* importable from these modules).
This function is effectively memoized for efficiency.
Parameters
----------
typing_attr_basename : str
Unqualified name of the attribute to be imported from a typing module.
exception_cls : Type[Exception]
Type of exception to be raised by this function. Defaults to
:class:`_BeartypeUtilModuleException`.
Returns
----------
object
Attribute with this name dynamically imported from a typing module.
Raises
----------
:exc:`exception_cls`
If this name is syntactically invalid.
Warns
----------
BeartypeModuleUnimportableWarning
If any of these modules raise module-scoped exceptions at importation
time. That said, the :mod:`typing` and :mod:`typing_extensions` modules
are scrupulously tested and thus unlikely to raise exceptions.
See Also
----------
:func:`import_typing_attr_or_fallback`
Further details.
'''
# One-liners in the rear view mirror may be closer than they appear.
#
# Note that parameters are intentionally passed positionally rather than by
# keyword for memoization efficiency.
return import_typing_attr_or_fallback(
typing_attr_basename, None, exception_cls)
#FIXME: Unit test us up, please.
#FIXME: Leverage above, please.
@callable_cached
def import_typing_attr_or_fallback(
# Mandatory parameters.
typing_attr_basename: str,
fallback: object,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilModuleException,
) -> Any:
'''
Dynamically import and return the **typing attribute** (i.e., object
declared at module scope by either the :mod:`typing` or
:mod:`typing_extensions` modules) with the passed unqualified name if
importable from one or more of these modules *or* the passed fallback
otherwise otherwise (i.e., if this attribute is *not* importable from these
modules).
Specifically, this function (in order):
#. If the official :mod:`typing` module bundled with the active Python
interpreter declares that attribute, dynamically imports and returns
that attribute from that module.
#. Else if the third-party (albeit quasi-official) :mod:`typing_extensions`
module requiring external installation under the active Python
interpreter declares that attribute, dynamically imports and returns
that attribute from that module.
#. Else, returns the passed fallback value.
This function is memoized for efficiency.
Parameters
----------
typing_attr_basename : str
Unqualified name of the attribute to be imported from a typing module.
fallback : object
Arbitrary value to be returned as a last-ditch fallback if *no* typing
module declares this attribute.
exception_cls : Type[Exception]
Type of exception to be raised by this function. Defaults to
:class:`_BeartypeUtilModuleException`.
Returns
----------
object
Attribute with this name dynamically imported from a typing module.
Raises
----------
:exc:`exception_cls`
If this name is syntactically invalid.
Warns
----------
BeartypeModuleUnimportableWarning
If any of these modules raise module-scoped exceptions at importation
time. That said, the :mod:`typing` and :mod:`typing_extensions` modules
are scrupulously tested and thus unlikely to raise exceptions.
'''
# Avoid circular import dependencies.
from beartype._util.mod.utilmodimport import import_module_attr_or_none
# Attribute with this name imported from the "typing" module if that module
# declares this attribute *OR* "None" otherwise.
typing_attr = import_module_attr_or_none(
module_attr_name=f'typing.{typing_attr_basename}',
exception_cls=exception_cls,
exception_prefix='Typing attribute ',
)
# If the "typing" module does *NOT* declare this attribute...
if typing_attr is None:
# Attribute with this name imported from the "typing_extensions" module
# if that module declares this attribute *OR* "None" otherwise.
typing_attr = import_module_attr_or_none(
module_attr_name=f'typing_extensions.{typing_attr_basename}',
exception_cls=exception_cls,
exception_prefix='Typing attribute ',
)
# If the "typing_extensions" module also does *NOT* declare this
# attribute, fallback to the passed fallback value.
if typing_attr is None:
typing_attr = fallback
# Else, the "typing_extensions" module declares this attribute.
# Else, the "typing" module declares this attribute.
# Return either this attribute if one or more of these modules declare this
# attribute *OR* this fallback otherwise.
return typing_attr
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **Sphinx** utilities (i.e., callables handling the third-party
:mod:`sphinx` package as an optional runtime dependency of this project).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# WARNING: To prevent this project from accidentally requiring third-party
# packages as mandatory runtime dependencies, avoid importing from *ANY* such
# package via a module-scoped import. These imports should be isolated to the
# bodies of callables declared below.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
from beartype._util.func.utilfuncframe import iter_frames
from sys import modules as module_imported_names
# ....................{ PRIVATE ~ magic }....................
_SPHINX_AUTODOC_SUBPACKAGE_NAME = 'sphinx.ext.autodoc'
'''
Fully-qualified name of the subpackage providing the ``autodoc`` extension
bundled with Sphinx.
'''
# ....................{ TESTERS }....................
def is_sphinx_autodocing() -> bool:
'''
``True`` only if Sphinx is currently **autogenerating documentation**
(i.e., if this function has been called from a Python call stack invoked by
the ``autodoc`` extension bundled with the optional third-party build-time
:mod:`sphinx` package).
'''
# If the "autodoc" extension has *NOT* been imported, Sphinx by definition
# *CANNOT* be autogenerating documentation. In this case, return false.
#
# Note this technically constitutes an optional (albeit pragmatically
# critical) optimization. This test is O(1) with negligible constants,
# whereas the additional test below is O(n) with non-negligible constants.
# Ergo, this efficient test short-circuits the inefficient test below.
if _SPHINX_AUTODOC_SUBPACKAGE_NAME not in module_imported_names:
return False
# Else, the "autodoc" extension has been imported. Since this does *NOT*
# conclusively imply that Sphinx is currently autogenerating documentation,
# further testing is required to avoid returning false positives (and thus
# erroneously reducing @beartype to a noop, which would be horrifying).
#
# Specifically, we iteratively search up the call stack for a stack frame
# originating from the "autodoc" extension. If we find such a stack frame,
# Sphinx is currently autogenerating documentation; else, Sphinx is not.
#FIXME: Refactor this to leverage a genuinely valid working solution
#hopefully provided out-of-the-box by some hypothetical new bleeding-edge
#version of Sphinx *AFTER* they resolve our feature request for this:
# https://github.com/sphinx-doc/sphinx/issues/9805
# For each stack frame on the call stack, ignoring the stack frame
# encapsulating the call to this tester...
for frame in iter_frames(func_stack_frames_ignore=1):
# Fully-qualified name of this scope's module if this scope defines
# this name *OR* "None" otherwise.
frame_module_name = frame.f_globals.get('__name__')
# print(f'Visiting frame (module: "{func_frame_module_name}")...')
# If this scope's module is the "autodoc" extension, Sphinx is
# currently autogenerating documentation. In this case, return true.
if (
frame_module_name and
frame_module_name.startswith(_SPHINX_AUTODOC_SUBPACKAGE_NAME)
):
return True
# Else, this scope's module is *NOT* the "autodoc" extension.
# Else, *NO* scope's module is the "autodoc" extension. Return false.
return False
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable getters** (i.e., utility functions dynamically
querying and retrieving various properties of passed callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCallableException
from beartype.typing import (
Any,
Callable,
)
from beartype._data.datatyping import TypeException
# ....................{ GETTERS ~ descriptor }....................
def get_func_classmethod_wrappee(
# Mandatory parameters.
func: Any,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilCallableException,
exception_prefix: str = '',
) -> Callable:
'''
Pure-Python unbound function wrapped by the passed **C-based unbound class
method descriptor** (i.e., method decorated by the builtin
:class:`classmethod` decorator, yielding a non-callable instance of that
:class:`classmethod` decorator class implemented in low-level C and
accessible via the low-level :attr:`object.__dict__` dictionary rather than
as class or instance attributes).
Parameters
----------
func : object
Object to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:static:`_BeartypeUtilCallableException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Returns
----------
Callable
Pure-Python unbound function wrapped by this class method descriptor.
Raises
----------
:exc:`exception_cls`
If the passed object is *not* a class method descriptor.
See Also
----------
:func:`beartype._util.func.utilfunctest.is_func_classmethod`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.func.utilfunctest import die_unless_func_classmethod
# If this object is *NOT* a class method descriptor, raise an exception.
die_unless_func_classmethod(
func=func,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this object is a class method descriptor.
# Return the pure-Python function wrapped by this descriptor. Just do it!
return func.__func__
def get_func_staticmethod_wrappee(
# Mandatory parameters.
func: Any,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilCallableException,
exception_prefix: str = '',
) -> Callable:
'''
Pure-Python unbound function wrapped by the passed **C-based unbound static
method descriptor** (i.e., method decorated by the builtin
:class:`staticmethod` decorator, yielding a non-callable instance of that
:class:`staticmethod` decorator class implemented in low-level C and
accessible via the low-level :attr:`object.__dict__` dictionary rather than
as class or instance attributes).
Parameters
----------
func : object
Object to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:static:`_BeartypeUtilCallableException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Returns
----------
Callable
Pure-Python unbound function wrapped by this static method descriptor.
Raises
----------
:exc:`exception_cls`
If the passed object is *not* a static method descriptor.
See Also
----------
:func:`beartype._util.func.utilfunctest.is_func_staticmethod`
Further details.
'''
# Avoid circular import dependencies.
from beartype._util.func.utilfunctest import die_unless_func_staticmethod
# If this object is *NOT* a static method descriptor, raise an exception.
die_unless_func_staticmethod(
func=func,
exception_cls=exception_cls,
exception_prefix=exception_prefix,
)
# Else, this object is a static method descriptor.
# Return the pure-Python function wrapped by this descriptor. Just do it!
return func.__func__
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable source code** (i.e., file providing the uncompiled
pure-Python source code from which a compiled callable originated) utilities.
This private submodule implements supplementary callable-specific utility
functions required by various :mod:`beartype` facilities, including callables
generated by the :func:`beartype.beartype` decorator.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: *FILE UPSTREAM CPYTHON ISSUES.* Unfortunately, this submodule exposed a
#number of significant issues in the CPython stdlib -- all concerning parsing
#of lambda functions. These include:
#
#1. The inspect.getsourcelines() function raises unexpected
# "tokenize.TokenError" exceptions when passed lambda functions preceded by
# one or more triple-quoted strings: e.g.,
# >>> import inspect
# >>> built_to_fail = (
# ... ('''Uh-oh.
# ... ''', lambda obj: 'Oh, Gods above and/or below!'
# ... )
# ... )
# >>> inspect.getsourcelines(built_to_fail[1])}
# tokenize.TokenError: ('EOF in multi-line string', (323, 8))
#2. The "func.__code__.co_firstlineno" attribute is incorrect for syntactic
# constructs resembling:
# assert is_hint_pep593_beartype(Annotated[ # <--- line 1
# str, Is[lambda text: bool(text)]]) is True # <--- line 2
# Given such a construct, the nested lambda function should have a
# "func.__code__.co_firstlineno" attribute whose value is "2". Instead, that
# attribute's value is "1". This then complicates detection of lambda
# functions, which are already non-trivial enough to detect. Specifically,
# this causes the inspect.findsource() function to either raise an unexpected
# "OSError" *OR* return incorrect source when passed a file containing the
# above snippet. In either case, that is bad. *sigh*
#3. Introspecting the source code for two or more lambdas defined on the same
# line is infeasible, because code objects only record line numbers rather
# than both line and column numbers. Well, that's unfortunate.
# ^--- Actually, we're *PRETTY* sure that Python 3.11 has finally resolved
# this by now recording column numbers with code objects. So, let's
# improve the logic below to handle this edge case under Python >= 3.11.
#FIXME: Contribute get_func_code_or_none() back to this StackOverflow question
#as a new answer, as this is highly non-trivial, frankly:
# https://stackoverflow.com/questions/59498679/how-can-i-get-exactly-the-code-of-a-lambda-function-in-python/64421174#64421174
# ....................{ IMPORTS }....................
from ast import (
NodeVisitor,
parse as ast_parse,
)
from beartype.roar._roarwarn import _BeartypeUtilCallableWarning
from beartype.typing import (
List,
Optional,
)
from beartype._data.datatyping import TypeWarning
from beartype._util.func.utilfunccodeobj import get_func_codeobj
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9
from collections.abc import Callable
from inspect import findsource, getsource
from traceback import format_exc
from warnings import warn
# ....................{ GETTERS ~ code : lines }....................
#FIXME: Unit test us up.
def get_func_code_lines_or_none(
# Mandatory parameters.
func: Callable,
# Optional parameters.
warning_cls: TypeWarning = _BeartypeUtilCallableWarning,
) -> Optional[str]:
'''
**Line-oriented callable source code** (i.e., string concatenating the
subset of all lines of the on-disk Python script or module declaring the
passed pure-Python callable) if that callable was declared on-disk *or*
``None`` otherwise (i.e., if that callable was dynamically declared
in-memory).
Caveats
----------
**The higher-level** :func:`get_func_code_or_none` **getter should
typically be called instead.** Why? Because this lower-level getter
inexactly returns all lines embedding the declaration of the passed
callable rather than the exact substring of those lines declaring that
callable. Although typically identical for non-lambda functions, those two
strings typically differ for lambda functions. Lambda functions are
expressions embedded in larger statements rather than full statements.
**This getter is excruciatingly slow.** See the
:func:`get_func_code_or_none` getter for further commentary.
Parameters
----------
func : Callable
Callable to be inspected.
warning_cls : TypeWarning, optional
Type of warning to be emitted in the event of a non-fatal error.
Defaults to :class:`_BeartypeUtilCallableWarning`.
Returns
----------
Optional[str]
Either:
* If the passed callable was physically declared by a file, a string
concatenating the subset of lines of that file declaring that
callable.
* If the passed callable was dynamically declared in-memory, ``None``.
Warns
----------
:class:`warning_cls`
If the passed callable is defined by a pure-Python source code file
but is *not* parsable from that file. While we could allow any parser
exception to percolate up the call stack and halt the active Python
process when left unhandled, doing so would render :mod:`beartype`
fragile -- gaining us little and costing us much.
'''
# Avoid circular import dependencies.
from beartype._util.func.utilfuncfile import is_func_file
from beartype._util.text.utiltextlabel import prefix_callable
# If the passed callable exists on-disk and is thus pure-Python...
if is_func_file(func):
# Attempt to defer to the standard inspect.getsource() function.
try:
return getsource(func)
# If that function raised *ANY* exception, reduce that exception to a
# non-fatal warning.
except Exception:
# Reduce this fatal error to a non-fatal warning embedding a full
# exception traceback as a formatted string.
warn(
f'{prefix_callable(func)}not parsable:\n{format_exc()}',
warning_cls,
)
# Else, the passed callable only exists in-memory.
# Return "None" as a fallback.
return None
#FIXME: Unit test us up.
def get_func_file_code_lines_or_none(
# Mandatory parameters.
func: Callable,
# Optional parameters.
warning_cls: TypeWarning = _BeartypeUtilCallableWarning,
) -> Optional[str]:
'''
**Line-oriented callable source file code** (i.e., string concatenating
*all* lines of the on-disk Python script or module declaring the passed
pure-Python callable) if that callable was declared on-disk *or* ``None``
otherwise (i.e., if that callable was dynamically declared in-memory).
Caveats
----------
**This getter is excruciatingly slow.** See the
:func:`get_func_code_or_none` getter for further commentary.
Parameters
----------
func : Callable
Callable to be inspected.
warning_cls : TypeWarning, optional
Type of warning to be emitted in the event of a non-fatal error.
Defaults to :class:`_BeartypeUtilCallableWarning`.
Returns
----------
Optional[str]
Either:
* If the passed callable was physically declared by an file, a string
concatenating *all* lines of that file.
* If the passed callable was dynamically declared in-memory, ``None``.
Warns
----------
:class:`warning_cls`
If the passed callable is defined by a pure-Python source code file
but is *not* parsable from that file. While we could allow any parser
exception to percolate up the call stack and halt the active Python
process when left unhandled, doing so would render :mod:`beartype`
fragile -- gaining us little and costing us much.
'''
# Avoid circular import dependencies.
from beartype._util.func.utilfuncfile import is_func_file
from beartype._util.text.utiltextlabel import prefix_callable
# If the passed callable exists on-disk and is thus pure-Python...
if is_func_file(func):
# Attempt to defer to the standard inspect.findsource() function, which
# returns a 2-tuple "(file_code_lines, file_code_lineno_start)", where:
# * "file_code_lines" is a list of all lines of the script or module
# declaring the passed callable.
# * "file_code_lineno_start" is the line number of the first such line
# declaring the passed callable. Since this line number is already
# provided by the "co_firstlineno" instance variable of this
# callable's code object, however, there is *NO* reason whatsoever to
# return this line number. Indeed, it's unclear why that function
# returns this uselessly redundant metadata in the first place.
try:
# List of all lines of the file declaring the passed callable.
func_file_code_lines, _ = findsource(func)
# Return this list concatenated into a string.
return ''.join(func_file_code_lines)
# If that function raised *ANY* exception, reduce that exception to a
# non-fatal warning. While we could permit this exception to percolate
# up the call stack and inevitably halt the active Python process when
# left unhandled, doing so would render @beartype fragile -- gaining us
# little and costing us much.
#
# Notably, the lower-level inspect.getblock() function internally
# called by the higher-level findsource() function prematurely halted
# due to an unexpected bug in the pure-Python tokenizer leveraged by
# inspect.getblock(). Notably, this occurs when passing lambda
# functions preceded by triple-quoted strings: e.g.,
# >>> import inspect
# >>> built_to_fail = (
# ... ('''Uh-oh.
# ... ''', lambda obj: 'Oh, Gods above and/or below!'
# ... )
# ... )
# >>> inspect.findsource(built_to_fail[1])}
# tokenize.TokenError: ('EOF in multi-line string', (323, 8))
except Exception:
# Reduce this fatal error to a non-fatal warning embedding a full
# exception traceback as a formatted string.
warn(
f'{prefix_callable(func)}not parsable:\n{format_exc()}',
warning_cls,
)
# Else, the passed callable only exists in-memory.
# Return "None" as a fallback.
return None
# ....................{ GETTERS ~ code : lambda }....................
# If the active Python interpreter targets Python >= 3.9 and thus defines the
# ast.unparse() function required to decompile AST nodes into source code,
# define the get_func_code_or_none() getter to get only the exact source code
# substring defining a passed lambda function rather than the inexact
# concatenation of all source code lines embedding that definition.
if IS_PYTHON_AT_LEAST_3_9:
# Defer version-specific imports.
from ast import unparse as ast_unparse # type: ignore[attr-defined]
_LAMBDA_CODE_FILESIZE_MAX = 1000000
'''
Maximum size (in bytes) of files to be safely parsed for lambda function
declarations by the :func:`get_func_code_or_none` getter.
'''
def get_func_code_or_none(
# Mandatory parameters.
func: Callable,
# Optional parameters.
warning_cls: TypeWarning = _BeartypeUtilCallableWarning,
) -> Optional[str]:
# Avoid circular import dependencies.
from beartype._util.func.utilfunctest import is_func_lambda
from beartype._util.text.utiltextlabel import prefix_callable
# If the passed callable is a pure-Python lambda function...
if is_func_lambda(func):
# Attempt to parse the substring of the source code defining this
# lambda from the file providing that code.
#
# For safety, this function reduces *ALL* exceptions raised by this
# introspection to non-fatal warnings and returns "None". Why?
# Because the standard "ast" module in general and our
# "_LambdaNodeUnparser" class in specific are sufficiently fragile
# as to warrant extreme caution. AST parsing and unparsing is
# notoriously unreliable across different versions of different
# Python interpreters and compilers.
#
# Moreover, we *NEVER* call this function in a critical code path;
# we *ONLY* call this function to construct human-readable
# exception messages. Clearly, raising low-level non-human-readable
# exceptions when attempting to raise high-level human-readable
# exceptions rather defeats the entire purpose of the latter.
#
# Lastly, note that "pytest" will still fail any tests emitting
# unexpected warnings. In short, raising exceptions here would gain
# @beartype little and cost @beartype much.
try:
# String concatenating all lines of the file defining that
# lambda if that lambda is defined by a file *OR* "None".
lambda_file_code = get_func_file_code_lines_or_none(
func=func, warning_cls=warning_cls)
# If that lambda is defined by a file...
if lambda_file_code:
# Code object underlying this lambda.
func_codeobj = get_func_codeobj(func)
# If this file exceeds a sane maximum file size, emit a
# non-fatal warning and safely ignore this file.
if len(lambda_file_code) >= _LAMBDA_CODE_FILESIZE_MAX:
warn(
(
f'{prefix_callable(func)}not parsable, '
f'as file size exceeds safe maximum '
f'{_LAMBDA_CODE_FILESIZE_MAX}MB.'
),
warning_cls,
)
# Else, this file *SHOULD* be safely parsable by the
# standard "ast" module without inducing a fatal
# segmentation fault.
else:
# Abstract syntax tree (AST) parsed from this file.
ast_tree = ast_parse(lambda_file_code)
# Lambda node unparser decompiling all AST lambda nodes
# encapsulating lambda functions starting at the same
# line number as the passed lambda in this file.
lambda_node_unparser = _LambdaNodeUnparser(
lambda_lineno=func_codeobj.co_firstlineno)
# Perform this decompilation.
lambda_node_unparser.visit(ast_tree)
# List of each code substring exactly covering each
# lambda function starting at that line number.
lambdas_code = lambda_node_unparser.lambdas_code
# If one or more lambda functions start at that line
# number...
if lambdas_code:
# If two or more lambda functions start at that
# line number, emit a non-fatal warning. Since
# lambda functions only provide a starting line
# number rather than both starting line number
# *AND* column, we have *NO* means of
# disambiguating between these lambda functions and
# thus *CANNOT* raise an exception.
if len(lambdas_code) >= 2:
# Human-readable concatenation of the
# definitions of all lambda functions defined
# on that line.
lambdas_code_str = '\n '.join(lambdas_code)
# Emit this warning.
warn(
(
f'{prefix_callable(func)}ambiguous, '
f'as that line defines '
f'{len(lambdas_code)} lambdas; '
f'arbitrarily selecting first '
f'lambda:\n{lambdas_code_str}'
),
warning_cls,
)
# Else, that line number defines one lambda.
# Return the substring covering that lambda.
return lambdas_code[0]
# Else, *NO* lambda functions start at that line
# number. In this case, emit a non-fatal warning.
#
# Ideally, we would instead raise a fatal exception.
# Why? Because this edge case violates expectations.
# Since the passed lambda function claims it originates
# from some line number of some file *AND* since that
# file both exists and is parsable as valid Python, we
# expect that line number to define one or more lambda
# functions. If it does not, raising an exception seems
# superficially reasonable. Yet, we don't. See above.
else:
warn(
f'{prefix_callable(func)}not found.',
warning_cls,
)
# Else, that lambda is dynamically defined in-memory.
# If *ANY* of the dodgy stdlib callables (e.g., ast.parse(),
# inspect.findsource()) called above raise *ANY* other unexpected
# exception, reduce this fatal error to a non-fatal warning with an
# exception traceback as a formatted string.
#
# Note that the likeliest (but certainly *NOT* only) type of
# exception to be raised is a "RecursionError", as described by the
# official documentation for the ast.unparse() function:
# Warning: Trying to unparse a highly complex expression would
# result with RecursionError.
except Exception:
warn(
f'{prefix_callable(func)}not parsable:\n{format_exc()}',
warning_cls,
)
# Else, the passed callable is *NOT* a pure-Python lambda function.
# In any case, the above logic failed to introspect code for the passed
# callable. Defer to the get_func_code_lines_or_none() function.
return get_func_code_lines_or_none(func=func, warning_cls=warning_cls)
# Helper class instantiated above to decompile AST lambda nodes.
class _LambdaNodeUnparser(NodeVisitor):
'''
**Lambda node unparser** (i.e., object decompiling the abstract syntax
tree (AST) nodes of *all* pure-Python lambda functions defined in a
caller-specified block of source code into the exact substrings of that
block defining those lambda functions by applying the visitor design
pattern to an AST parsed from that block).
Attributes
----------
lambdas_code : List[str]
List of one or more **source code substrings** (i.e., of one or
more lines of code) defining each of the one or more lambda
functions starting at line :attr:`_lambda_lineno` of the code from
which the AST visited by this visitor was parsed.
_lambda_lineno : int
Caller-requested line number (of the code from which the AST
visited by this object was parsed) starting the definition of the
lambda functions to be unparsed by this visitor.
'''
# ................{ INITIALIZERS }................
def __init__(self, lambda_lineno: int) -> None:
'''
Initialize this visitor.
Parameters
----------
lambda_lineno : int
Caller-specific line number (of the code from which the AST
visited by this object was parsed) starting the definition of
the lambda functions to be unparsed by this visitor.
'''
assert isinstance(lambda_lineno, int), (
f'{repr(lambda_lineno)} not integer.')
assert lambda_lineno >= 0, f'{lambda_lineno} < 0.'
# Initialize our superclass.
super().__init__()
# Classify all passed parameters.
self._lambda_lineno = lambda_lineno
# Initialize all remaining instance variables.
self.lambdas_code: List[str] = []
def visit_Lambda(self, node):
'''
Visit (i.e., handle, process) the passed AST node encapsulating the
definition of a lambda function (parsed from the code from which
the AST visited by this visitor was parsed) *and*, if that lambda
starts on the caller-requested line number, decompile this node
back into the substring of this line defining that lambda.
Parameters
----------
node : LambdaNode
AST node encapsulating the definition of a lambda function.
'''
# If the desired lambda starts on the current line number...
if node.lineno == self._lambda_lineno:
# Decompile this node into the substring of this line defining
# this lambda.
self.lambdas_code.append(ast_unparse(node))
# Recursively visit all child nodes of this lambda node. While
# doing so is largely useless, a sufficient number of dragons
# are skulking to warrant an abundance of caution and magic.
self.generic_visit(node)
# Else if the desired lambda starts on a later line number than
# the current line number, recursively visit all child nodes of
# the current lambda node.
elif node.lineno < self._lambda_lineno:
self.generic_visit(node)
#FIXME: Consider raising an exception here instead like
#"StopException" to force a premature halt to this recursion. Of
#course, handling exceptions also incurs a performance cost, so...
# Else, the desired lambda starts on an earlier line number than
# the current line number, the current lambda *CANNOT* be the
# desired lambda and is thus ignorable. In this case, avoid
# recursively visiting *ANY* child nodes of the current lambda node
# to induce a premature halt to this recursive visitation.
# Else, the active Python interpreter targets only Python < 3.9 and thus does
# *NOT* define the ast.unparse() function required to decompile AST nodes into
# source code. In this case...
else:
def get_func_code_or_none(
# Mandatory parameters.
func: Callable,
# Optional parameters.
warning_cls: TypeWarning = _BeartypeUtilCallableWarning,
) -> Optional[str]:
# Defer to the get_func_code_lines_or_none() function as is.
return get_func_code_lines_or_none(func=func, warning_cls=warning_cls)
get_func_code_or_none.__doc__ = '''
**Callable source code** (i.e., substring of all lines of the on-disk Python
script or module declaring the passed pure-Python callable) if that callable
was declared on-disk *or* ``None`` otherwise (i.e., if that callable was
dynamically declared in-memory).
Specifically, this getter returns:
* If the passed callable is a lambda function *and* active Python interpreter
targets Python >= 3.9 (and thus defines the ast.unparse() function required
to decompile AST lambda nodes into original source code), the exact substring
of that code declaring that lambda function.
* Else, the concatenation of all lines of that code declaring that callable.
Caveats
----------
**This getter is excruciatingly slow.** This getter should *only* be called
when unavoidable and ideally *only* in performance-agnostic code paths.
Notably, this getter finds relevant lines by parsing the script or module
declaring the passed callable starting at the first line of that declaration
and continuing until a rudimentary tokenizer implemented in pure-Python (with
*no* concern for optimization and thus slow beyond all understanding of slow)
detects the last line of that declaration. In theory, we could significantly
optimize that routine; in practice, anyone who cares will preferably compile or
JIT :mod:`beartype` instead.
Parameters
----------
func : Callable
Callable to be inspected.
warning_cls : TypeWarning, optional
Type of warning to be emitted in the event of a non-fatal error. Defaults
to :class:`_BeartypeUtilCallableWarning`.
Returns
----------
Optional[str]
Either:
* If the passed callable was physically declared by a file, the exact
substring of all lines of that file declaring that callable.
* If the passed callable was dynamically declared in-memory, ``None``.
Warns
----------
:class:`warning_cls`
If the passed callable is a pure-Python lambda function that was physically
declared by either:
* A large file exceeding a sane maximum file size (e.g., 1MB). Note that:
* If this is *not* explicitly guarded against, passing absurdly long
strings to the :func:`ast.parse` function can actually induce a
segmentation fault in the active Python process. This is a longstanding
and unresolved issue in the :mod:`ast` module. See also:
https://bugs.python.org/issue32758
* Generously assuming each line of that file contains between
40 to 80 characters, this maximum supports files of between 12,500 to
25,000 lines, which at even the lower end of that range covers most
real-world files of interest.
* A complex (but *not* necessarily large) file causing the recursive
:func:`ast.parse` or :func:`ast.unparse` function or any other :mod:`ast`
callable to exceed Python's recursion limit by exhausting the stack.
* A line of source code declaring two or more lambda functions (e.g.,
``lambdas = lambda: 'and black,', lambda: 'and pale,'``). In this case,
the substring of code declaring the first such function is ambiguously
returned; all subsequent such functions are unavoidably ignored.
See Also
----------
https://stackoverflow.com/questions/59498679/how-can-i-get-exactly-the-code-of-a-lambda-function-in-python/64421174#64421174
StackOverflow answer strongly inspiring this implementation.
'''
# ....................{ GETTERS ~ label }....................
#FIXME: This getter no longer has a sane reason to exist. Consider excising.
# from beartype.roar._roarexc import _BeartypeUtilCallableException
# from beartype._cave._cavefast import CallableTypes
# from sys import modules
#
# def get_func_code_label(func: Callable) -> str:
# '''
# Human-readable label describing the **origin** (i.e., uncompiled source) of
# the passed callable.
#
# Specifically, this getter returns either:
#
# * If that callable is pure-Python *and* physically declared on-disk, the
# absolute filename of the uncompiled on-disk Python script or module
# physically declaring that callable.
# * If that callable is pure-Python *and* dynamically declared in-memory,
# the placeholder string ``"<string>"``.
# * If that callable is C-based, the placeholder string ``"<C-based>"``.
#
# Caveats
# ----------
# **This getter is intentionally implemented for speed rather than robustness
# against unlikely edge cases.** The string returned by this getter is *only*
# intended to be embedded in human-readable labels, warnings, and exceptions.
# Avoid using this string for *any* mission-critical purpose.
#
# Parameters
# ----------
# func : Callable
# Callable to be inspected.
#
# Returns
# ----------
# str
# Either:
#
# * If that callable is physically declared by an uncompiled Python
# script or module, the absolute filename of this script or module.
# * Else, the placeholder string ``"<string>"`` implying that callable to
# have been dynamically declared in-memory.
#
# Raises
# ------
# _BeartypeUtilCallableException
# If that callable is *not* callable.
#
# See Also
# ----------
# :func:`inspect.getsourcefile`
# Inefficient stdlib function strongly inspiring this implementation,
# which has been highly optimized for use by the performance-sensitive
# :func:`beartype.beartype` decorator.
# '''
#
# # If this callable is uncallable, raise an exception.
# if not callable(func):
# raise _BeartypeUtilCallableException(f'{repr(func)} not callable.')
# # Else, this callable is callable.
#
# # Human-readable label describing the origin of the passed callable.
# func_origin_label = '<string>'
#
# # If this callable is a standard callable rather than arbitrary class or
# # object overriding the __call__() dunder method...
# if isinstance(func, CallableTypes):
# # Avoid circular import dependencies.
# from beartype._util.func.utilfuncfile import get_func_filename_or_none
# from beartype._util.func.utilfuncwrap import unwrap_func
#
# # Code object underlying the passed pure-Python callable unwrapped if
# # this callable is pure-Python *OR* "None" otherwise.
# func_filename = get_func_filename_or_none(unwrap_func(func))
#
# # If this callable has a code object, set this label to either the
# # absolute filename of the physical Python module or script declaring
# # this callable if this code object provides that metadata *OR* a
# # placeholder string specific to C-based callables otherwise.
# func_origin_label = func_filename if func_filename else '<C-based>'
# # Else, this callable is *NOT* a standard callable. In this case...
# else:
# # If this callable is *NOT* a class (i.e., is an object defining the
# # __call__() method), reduce this callable to the class of this object.
# if not isinstance(func, type):
# func = type(func)
# # In either case, this callable is now a class.
#
# # Fully-qualified name of the module declaring this class if this class
# # was physically declared by an on-disk module *OR* "None" otherwise.
# func_module_name = func.__module__
#
# # If this class was physically declared by an on-disk module, defer to
# # the absolute filename of that module.
# #
# # Note that arbitrary modules need *NOT* declare the "__file__" dunder
# # attribute. Unlike most other core Python objects, modules are simply
# # arbitrary objects that reside in the "sys.modules" dictionary.
# if func_module_name:
# func_origin_label = getattr(
# modules[func_module_name], '__file__', func_origin_label)
#
# # Return this label.
# return func_origin_label
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable testers** (i.e., utility functions dynamically
validating and inspecting various properties of passed callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCallableException
from beartype.typing import Any
from beartype._util.func.utilfunccodeobj import (
get_func_codeobj_or_none)
from beartype._data.datatyping import (
Codeobjable,
TypeException,
)
from inspect import (
CO_ASYNC_GENERATOR,
CO_COROUTINE,
CO_GENERATOR,
)
# ....................{ CONSTANTS }....................
FUNC_NAME_LAMBDA = '<lambda>'
'''
Default name of all **pure-Python lambda functions** (i.e., function declared
as a ``lambda`` expression embedded in a larger statement rather than as a
full-blown ``def`` statement).
Python initializes the names of *all* lambda functions to this lambda-specific
placeholder string on lambda definition.
Caveats
----------
**Usage of this placeholder to differentiate lambda from non-lambda callables
invites false positives in unlikely edge cases.** Technically, malicious third
parties may externally change the name of any lambda function *after* defining
that function. Pragmatically, no one sane should ever do such a horrible thing.
While predictably absurd, this is also the only efficient (and thus sane) means
of differentiating lambda from non-lambda callables. Alternatives require
AST-based parsing, which comes with its own substantial caveats, concerns,
edge cases, and false positives. If you must pick your poison, pick this one.
'''
# ....................{ VALIDATORS }....................
def die_unless_func_python(
# Mandatory parameters.
func: Codeobjable,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilCallableException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception if the passed callable is **C-based** (i.e., implemented
in C as either a builtin bundled with the active Python interpreter *or*
third-party C extension function).
Equivalently, this validator raises an exception unless the passed function
is **pure-Python** (i.e., implemented in Python as either a function or
method).
Parameters
----------
func : Codeobjable
Callable to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:class:`_BeartypeUtilCallableException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If the passed callable is C-based.
See Also
----------
:func:`is_func_python`
Further details.
'''
# If this callable is *NOT* pure-Python, raise an exception.
if not is_func_python(func):
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not class.')
assert issubclass(exception_cls, Exception), (
f'{repr(exception_cls)} not exception subclass.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# If this callable is uncallable, raise an appropriate exception.
if not callable(func):
raise exception_cls(f'{exception_prefix}{repr(func)} not callable.')
# Else, this callable is callable.
# Raise a human-readable exception.
raise exception_cls(
f'{exception_prefix}{repr(func)} not '
f'pure-Python callable backed by code object '
f'(i.e., either C-based callable or pure-Python callable backed by '
f'__call__() dunder method).'
)
# Else, this callable is pure-Python.
# ....................{ VALIDATORS ~ descriptors }....................
def die_unless_func_classmethod(
# Mandatory parameters.
func: Any,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilCallableException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is a **C-based unbound class
method descriptor** (i.e., method decorated by the builtin
:class:`classmethod` decorator, yielding a non-callable instance of that
:class:`classmethod` decorator class implemented in low-level C and
accessible via the low-level :attr:`object.__dict__` dictionary rather than
as class or instance attributes).
Parameters
----------
func : Any
Object to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:class:`_BeartypeUtilCallableException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If the passed object is *not* a class method descriptor.
See Also
----------
:func:`is_func_classmethod`
Further details.
'''
# If this object is *NOT* a class method descriptor, raise an exception.
if not is_func_classmethod(func):
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not class.')
assert issubclass(exception_cls, Exception), (
f'{repr(exception_cls)} not exception subclass.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Raise a human-readable exception.
raise exception_cls(
f'{exception_prefix}{repr(func)} not '
f'C-based unbound class method descriptor.'
)
# Else, this object is a class method descriptor.
def die_unless_func_property(
# Mandatory parameters.
func: Any,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilCallableException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is a **C-based unbound property
method descriptor** (i.e., method decorated by the builtin :class:`property`
decorator, yielding a non-callable instance of that :class:`property`
decorator class implemented in low-level C and accessible as a class rather
than instance attribute).
Parameters
----------
func : Any
Object to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:property:`_BeartypeUtilCallableException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If the passed object is *not* a property method descriptor.
See Also
----------
:func:`is_func_property`
Further details.
'''
# If this object is *NOT* a property method descriptor, raise an exception.
if not is_func_property(func):
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not class.')
assert issubclass(exception_cls, Exception), (
f'{repr(exception_cls)} not exception subclass.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Raise a human-readable exception.
raise exception_cls(
f'{exception_prefix}{repr(func)} not '
f'C-based unbound property method descriptor.'
)
# Else, this object is a property method descriptor.
def die_unless_func_staticmethod(
# Mandatory parameters.
func: Any,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilCallableException,
exception_prefix: str = '',
) -> None:
'''
Raise an exception unless the passed object is a **C-based unbound static
method descriptor** (i.e., method decorated by the builtin
:class:`staticmethod` decorator, yielding a non-callable instance of that
:class:`staticmethod` decorator class implemented in low-level C and
accessible via the low-level :attr:`object.__dict__` dictionary rather than
as class or instance attributes).
Parameters
----------
func : Any
Object to be inspected.
exception_cls : TypeException, optional
Type of exception to be raised. Defaults to
:static:`_BeartypeUtilCallableException`.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Raises
----------
:exc:`exception_cls`
If the passed object is *not* a static method descriptor.
See Also
----------
:func:`is_func_staticmethod`
Further details.
'''
# If this object is *NOT* a static method descriptor, raise an exception.
if not is_func_staticmethod(func):
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not class.')
assert issubclass(exception_cls, Exception), (
f'{repr(exception_cls)} not exception subclass.')
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Raise a human-readable exception.
raise exception_cls(
f'{exception_prefix}{repr(func)} not '
f'C-based unbound static method descriptor.'
)
# Else, this object is a static method descriptor.
# ....................{ TESTERS }....................
def is_func_lambda(func: Any) -> bool:
'''
``True`` only if the passed object is a **pure-Python lambda function**
(i.e., function declared as a ``lambda`` expression embedded in a larger
statement rather than as a full-blown ``def`` statement).
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a pure-Python lambda function.
'''
# Return true only if this both...
return (
# This callable is pure-Python *AND*...
is_func_python(func) and
# This callable's name is the lambda-specific placeholder name
# initially given by Python to *ALL* lambda functions. Technically,
# this name may be externally changed by malicious third parties after
# the declaration of this lambda. Pragmatically, no one sane would ever
# do such a horrible thing. Would they!?!?
#
# While predictably absurd, this is also the only efficient (and thus
# sane) means of differentiating lambda from non-lambda callables.
# Alternatives require AST-based parsing, which comes with its own
# substantial caveats, concerns, and edge cases.
func.__name__ == FUNC_NAME_LAMBDA
)
def is_func_python(func: object) -> bool:
'''
``True`` only if the passed object is a **pure-Python callable** (i.e.,
implemented in Python as either a function or method rather than in C as
either a builtin bundled with the active Python interpreter *or*
third-party C extension function).
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a pure-Python callable
'''
# Return true only if a pure-Python code object underlies this object.
# C-based callables are associated with *NO* code objects.
return get_func_codeobj_or_none(func) is not None
# ....................{ TESTERS ~ descriptor }....................
def is_func_classmethod(func: Any) -> bool:
'''
``True`` only if the passed object is a **C-based unbound class method
descriptor** (i.e., method decorated by the builtin :class:`classmethod`
decorator, yielding a non-callable instance of that :class:`classmethod`
decorator class implemented in low-level C and accessible via the
low-level :attr:`object.__dict__` dictionary rather than as class or
instance attributes).
Caveats
----------
Class method objects are *only* directly accessible via the low-level
:attr:`object.__dict__` dictionary. When accessed as class or instance
attributes, class methods reduce to instances of the standard
:class:`MethodBoundInstanceOrClassType` type.
Class method objects are *not* callable, as their implementations fail to
define the ``__call__`` dunder method.
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a C-based unbound class method
descriptor.
'''
# Now you too have seen the pure light of the one-liner.
return isinstance(func, classmethod)
def is_func_property(func: Any) -> bool:
'''
``True`` only if the passed object is a **C-based unbound property method
descriptor** (i.e., method decorated by the builtin :class:`property`
decorator, yielding a non-callable instance of that :class:`property`
decorator class implemented in low-level C and accessible as a class rather
than instance attribute).
Caveats
----------
Property objects are directly accessible both as class attributes *and* via
the low-level :attr:`object.__dict__` dictionary. Property objects are *not*
accessible as instance attributes, for hopefully obvious reasons.
Property objects are *not* callable, as their implementations fail to define
the ``__call__`` dunder method.
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a pure-Python property.
'''
# We rejoice in the shared delight of one-liners.
return isinstance(func, property)
def is_func_staticmethod(func: Any) -> bool:
'''
``True`` only if the passed object is a **C-based unbound static method
descriptor** (i.e., method decorated by the builtin :class:`staticmethod`
decorator, yielding a non-callable instance of that :class:`staticmethod`
decorator class implemented in low-level C and accessible via the low-level
:attr:`object.__dict__` dictionary rather than as class or instance
attributes).
Caveats
----------
Static method objects are *only* directly accessible via the low-level
:attr:`object.__dict__` dictionary. When accessed as class or instance
attributes, static methods reduce to instances of the standard
:class:`FunctionType` type.
Static method objects are *not* callable, as their implementations fail to
define the ``__call__`` dunder method.
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a pure-Python static method.
'''
# Does the one-liner have Buddhahood? Mu.
return isinstance(func, staticmethod)
# ....................{ TESTERS ~ async }....................
def is_func_async(func: object) -> bool:
'''
``True`` only if the passed object is an **asynchronous callable** (i.e.,
awaitable factory callable implicitly creating and returning an awaitable
object (i.e., satisfying the :class:`collections.abc.Awaitable` protocol) by
being declared via the ``async def`` syntax and thus callable *only* when
preceded by comparable ``await`` syntax).
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is an asynchronous callable.
See Also
----------
:func:`inspect.iscoroutinefunction`
:func:`inspect.isasyncgenfunction`
Stdlib functions strongly inspiring this implementation.
'''
# Code object underlying this pure-Python callable if any *OR* "None".
#
# Note this tester intentionally:
# * Inlines the tests performed by the is_func_coro() and
# is_func_async_generator() testers for efficiency.
# * Calls the get_func_codeobj_or_none() with "is_unwrapping" disabled
# rather than enabled. Why? Because the asynchronicity of this possibly
# higher-level wrapper has *NO* relation to that of the possibly
# lower-level wrappee wrapped by this wrapper. Notably, it is both
# feasible and commonplace for third-party decorators to enable:
# * Synchronous callables to be called asynchronously by wrapping
# synchronous callables with asynchronous closures.
# * Asynchronous callables to be called synchronously by wrapping
# asynchronous callables with synchronous closures. Indeed, our
# top-level "conftest.py" pytest plugin does exactly this -- enabling
# asynchronous tests to be safely called by pytest's currently
# synchronous framework.
func_codeobj = get_func_codeobj_or_none(func)
# If this object is *NOT* a pure-Python callable, immediately return false.
if func_codeobj is None:
return False
# Else, this object is a pure-Python callable.
# Bit field of OR-ed binary flags describing this callable.
func_codeobj_flags = func_codeobj.co_flags
# Return true only if these flags imply this callable to be either...
return (
# An asynchronous coroutine *OR*...
func_codeobj_flags & CO_COROUTINE != 0 or
# An asynchronous generator.
func_codeobj_flags & CO_ASYNC_GENERATOR != 0
)
def is_func_coro(func: object) -> bool:
'''
``True`` only if the passed object is an **asynchronous coroutine factory**
(i.e., awaitable callable containing *no* ``yield`` expression implicitly
creating and returning an awaitable object (i.e., satisfying the
:class:`collections.abc.Awaitable` protocol) by being declared via the
``async def`` syntax and thus callable *only* when preceded by comparable
``await`` syntax).
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is an asynchronous coroutine factory.
See Also
----------
:func:`inspect.iscoroutinefunction`
Stdlib function strongly inspiring this implementation.
'''
# Code object underlying this pure-Python callable if any *OR* "None".
func_codeobj = get_func_codeobj_or_none(func)
# Return true only if...
return (
# This object is a pure-Python callable *AND*...
func_codeobj is not None and
# This callable's code object implies this callable to be an
# asynchronous coroutine.
func_codeobj.co_flags & CO_COROUTINE != 0
)
def is_func_async_generator(func: object) -> bool:
'''
``True`` only if the passed object is an **asynchronous generator factory**
(i.e., awaitable callable containing one or more ``yield`` expressions
implicitly creating and returning an awaitable object (i.e., satisfying the
:class:`collections.abc.Awaitable` protocol) by being declared via the
``async def`` syntax and thus callable *only* when preceded by comparable
``await`` syntax).
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is an asynchronous generator.
See Also
----------
:func:`inspect.isasyncgenfunction`
Stdlib function strongly inspiring this implementation.
'''
# Code object underlying this pure-Python callable if any *OR* "None".
func_codeobj = get_func_codeobj_or_none(func)
# Return true only if...
return (
# This object is a pure-Python callable *AND*...
func_codeobj is not None and
# This callable's code object implies this callable to be an
# asynchronous generator.
func_codeobj.co_flags & CO_ASYNC_GENERATOR != 0
)
# ....................{ TESTERS ~ sync }....................
def is_func_sync_generator(func: object) -> bool:
'''
``True`` only if the passed object is an **synchronous generator factory**
(i.e., awaitable callable containing one or more ``yield`` expressions
implicitly creating and returning a generator object (i.e., satisfying the
:class:`collections.abc.Generator` protocol) by being declared via the
``def`` rather than ``async def`` syntax).
Parameters
----------
func : object
Object to be inspected.
Returns
----------
bool
``True`` only if this object is a synchronous generator.
See Also
----------
:func:`inspect.isgeneratorfunction`
Stdlib function strongly inspiring this implementation.
'''
# If this object is uncallable, immediately return False.
#
# Note this test is explicitly required to differentiate synchronous
# generator callables from synchronous generator objects (i.e., the objects
# they implicitly create and return). Whereas both asynchronous coroutine
# objects *AND* asynchronous generator objects do *NOT* contain code
# objects whose "CO_COROUTINE" and "CO_ASYNC_GENERATOR" flags are non-zero,
# synchronous generator objects do contain code objects whose
# "CO_GENERATOR" flag is non-zero. This implies synchronous generator
# callables to create and return synchronous generator objects that are
# themselves technically valid synchronous generator callables, which is
# absurd. We prohibit this ambiguity by differentiating the two here.
if not callable(func):
return False
# Else, this object is callable.
# Code object underlying this pure-Python callable if any *OR* "None".
func_codeobj = get_func_codeobj_or_none(func)
# Return true only if...
return (
# This object is a pure-Python callable *AND*...
func_codeobj is not None and
# This callable's code object implies this callable to be a
# synchronous generator.
func_codeobj.co_flags & CO_GENERATOR != 0
)
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **call stack frame utilities** (i.e., callables introspecting the
current stack of frame objects, encapsulating the linear chain of calls to
external callables underlying the call to the current callable).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
import sys
from beartype.typing import (
Callable,
Iterable,
Optional,
)
from types import FrameType
# ....................{ GETTERS }....................
get_frame: Optional[Callable[[int,], Optional[FrameType]]] = (
getattr(sys, '_getframe', None))
'''
Private low-level :func:`sys._getframe` getter if the active Python interpreter
declares this getter *or* ``None`` otherwise (i.e., if this interpreter does
*not* declare this getter).
All standard Python interpreters supported by this package including both
CPython *and* PyPy declare this getter. Ergo, this attribute should *always* be
a valid callable rather than ``None``.
If this getter is *not* ``None``, this getter's signature and docstring under
CPython resembles:
::
_getframe([depth]) -> frameobject
Return a frame object from the call stack. If optional integer depth is
given, return the frame object that many calls below the top of the
stack. If that is deeper than the call stack, ValueError is raised. The
default for depth is zero, returning the frame at the top of the call
stack.
Frame objects provide these attributes:
f_back next outer frame object (this frame's caller)
f_builtins built-in namespace seen by this frame
f_code code object being executed in this frame
f_globals global namespace seen by this frame
f_lasti index of last attempted instruction in bytecode
f_lineno current line number in Python source code
f_locals local namespace seen by this frame
f_trace tracing function for this frame, or None
'''
# ....................{ ITERATORS }....................
def iter_frames(
# Optional parameters.
func_stack_frames_ignore: int = 0,
) -> Iterable[FrameType]:
'''
Generator yielding one **frame** (i.e., :class:`types.FrameType` instance)
for each call on the current **call stack** (i.e., stack of frame objects,
encapsulating the linear chain of calls to external callables underlying
the current call to this callable).
Notably, for each:
* **C-based callable call** (i.e., call of a C-based rather than
pure-Python callable), this generator yields one frame encapsulating *no*
code object. Only pure-Python frame objects have code objects.
* **Class-scoped callable call** (i.e., call of an arbitrary callable
occurring at class scope rather than from within the body of a callable
or class, typically due to a method being decorated), this generator
yields one frame ``func_frame`` for that class ``cls`` such that
``func_frame.f_code.co_name == cls.__name__`` (i.e., the name of the code
object encapsulated by that frame is the unqualified name of the class
encapsulating the lexical scope of this call). Actually, we just made all
of that up. That is *probably* (but *not* necessarily) the case. Research
is warranted.
* **Module-scoped callable call** (i.e., call of an arbitrary callable
occurring at module scope rather than from within the body of a callable
or class, typically due to a function or class being decorated), this
generator yields one frame ``func_frame`` such that
``func_frame.f_code.co_name == '<module>'`` (i.e., the name of the code
object encapsulated by that frame is the placeholder string assigned by
the active Python interpreter to all scopes encapsulating the top-most
lexical scope of a module in the current call stack).
The above constraints imply that frames yielded by this generator *cannot*
be assumed to encapsulate code objects. See the "Examples" subsection for
standard logic handling this edge case.
Caveats
----------
**This high-level iterator requires the private low-level**
:func:`sys._getframe` **getter.** If that getter is undefined, this iterator
reduces to the empty generator yielding nothing rather than raising an
exception. Since all standard Python implementations (e.g., CPython, PyPy)
define that getter, this should typically *not* be a real-world concern.
Parameters
----------
func_stack_frames_ignore : int, optional
Number of frames on the call stack to be ignored (i.e., silently
incremented past). Defaults to 0.
Returns
----------
Iterable[FrameType]
Generator yielding one frame for each call on the current call stack.
See Also
----------
:func:`get_frame`
Further details on stack frame objects.
Examples
----------
>>> from beartype._util.func.utilfunccodeobj import (
... get_func_codeobj_or_none)
>>> from beartype._util.func.utilfuncframe import iter_frames
# For each stack frame on the call stack...
>>> for func_frame in iter_frames():
... # Code object underlying this frame's scope if this scope is
... # pure-Python *OR* "None" otherwise.
... func_frame_codeobj = get_func_codeobj_or_none(func_frame)
...
... # If this code object does *NOT* exist, this scope is C-based.
... # In this case, silently ignore this scope and proceed to the
... # next frame in the call stack.
... if func_frame_codeobj is None:
... continue
... # Else, this code object exists, implying this scope to be
... # pure-Python.
...
... # Fully-qualified name of this scope's module.
... func_frame_module_name = func_frame.f_globals['__name__']
...
... # Unqualified name of this scope.
... func_frame_name = func_frame_codeobj.co_name
...
... # Print the fully-qualified name of this scope.
... print(f'On {func_frame_module_name}.{func_frame_name}()!')
'''
assert isinstance(func_stack_frames_ignore, int), (
f'{func_stack_frames_ignore} not integer.')
assert func_stack_frames_ignore >= 0, (
f'{func_stack_frames_ignore} negative.')
# If the active Python interpreter fails to declare the private
# sys._getframe() getter, reduce to the empty generator (i.e., noop).
if get_frame is None: # pragma: no cover
yield from ()
return
# Else, the active Python interpreter declares the sys._getframe() getter.
# Attempt to obtain the...
try:
# Next non-ignored frame following the last ignored frame, ignoring an
# additional frame embodying the current call to this iterator.
func_frame = get_frame(func_stack_frames_ignore + 1) # type: ignore[misc]
# If doing so raises a "ValueError" exception...
except ValueError as value_error:
# Whose message matches this standard boilerplate, the caller requested
# that this generator ignore more stack frames than currently exist on
# the call stack. Permitting this exception to unwind the call stack
# would only needlessly increase the fragility of this already fragile
# mission-critical generator. Instead, swallow this exception and
# silently reduce to the empty generator (i.e., noop).
if str(value_error) == 'call stack is not deep enough':
yield from ()
return
# Whose message does *NOT* match this standard boilerplate, an
# unexpected exception occurred. In this case, re-raise this exception.
raise
# Else, doing so raised *NO* "ValueError" exception.
# print(f'start frame: {repr(func_frame)}')
# While at least one frame remains on the call stack...
while func_frame:
# print(f'current frame: {repr(func_frame)}')
# Yield this frame to the caller.
yield func_frame
# Iterate to the next frame on the call stack.
func_frame = func_frame.f_back
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable origin** (i.e., uncompiled source from which a compiled
callable originated) utilities.
This private submodule implements supplementary callable-specific utility
functions required by various :mod:`beartype` facilities, including callables
generated by the :func:`beartype.beartype` decorator.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: *FILE UPSTREAM CPYTHON ISSUES.* Unfortunately, this submodule exposed a
#number of significant issues in the CPython stdlib -- all concerning parsing
#of lambda functions. These include:
#
#1. The inspect.getsourcelines() function raises unexpected
# "tokenize.TokenError" exceptions when passed lambda functions preceded by
# one or more triple-quoted strings: e.g.,
# >>> import inspect
# >>> built_to_fail = (
# ... ('''Uh-oh.
# ... ''', lambda obj: 'Oh, Gods above and/or below!'
# ... )
# ... )
# >>> inspect.getsourcelines(built_to_fail[1])}
# tokenize.TokenError: ('EOF in multi-line string', (323, 8))
#FIXME: Contribute get_func_code_or_none() back to this StackOverflow question
#as a new answer, as this is highly non-trivial, frankly:
# https://stackoverflow.com/questions/59498679/how-can-i-get-exactly-the-code-of-a-lambda-function-in-python/64421174#64421174
# ....................{ IMPORTS }....................
from beartype.typing import Optional
from beartype._util.func.utilfunccodeobj import get_func_codeobj_or_none
from collections.abc import Callable
from linecache import cache as linecache_cache
# ....................{ TESTERS }....................
def is_func_file(func: Callable) -> bool:
'''
``True`` only if the passed callable is defined **on-disk** (e.g., by a
script or module whose pure-Python source code is accessible to the active
Python interpreter as a file on the local filesystem).
Equivalently, this tester returns ``False`` if that callable is dynamically
defined in-memory (e.g., by a prior call to the :func:`exec` or
:func:`eval` builtins).
Parameters
----------
func : Callable
Callable to be inspected.
Returns
----------
bool
``True`` only if the passed callable is defined on-disk.
'''
# One-liners for abstruse abstraction.
return get_func_filename_or_none(func) is not None
# ....................{ GETTERS ~ code : lines }....................
def get_func_filename_or_none(
# Mandatory parameters.
func: Callable,
# Optional parameters.
# exception_cls: Type[Exception] = _BeartypeUtilCallableException,
) -> Optional[str]:
'''
Absolute filename of the file on the local filesystem containing the
pure-Python source code for the script or module defining the passed
callable if that callable is defined on-disk *or* ``None`` otherwise (i.e.,
if that callable is dynamically defined in-memory by a prior call to the
:func:`exec` or :func:`eval` builtins).
Parameters
----------
func : Callable
Callable to be inspected.
Returns
----------
Optional[str]
Either:
* If the passed callable was physically declared by a file, the
absolute filename of that file.
* If the passed callable was dynamically declared in-memory, ``None``.
'''
# Code object underlying the passed callable if that callable is
# pure-Python *OR* "None" otherwise (i.e., if that callable is C-based).
#
# Note that we intentionally do *NOT* test whether this callable is
# explicitly pure-Python or C-based: e.g.,
# # If this callable is implemented in C, this callable has no code
# # object with which to inspect the filename declaring this callable.
# # In this case, defer to a C-specific placeholder string.
# if isinstance(func, CallableCTypes):
# func_origin_label = '<C-based>'
# # Else, this callable is implemented in Python. In this case...
# else:
# # If this callable is a bound method wrapping an unbound function,
# # unwrap this method into the function it wraps. Why? Because only
# # the latter provides the code object for this callable.
# if isinstance(func, MethodBoundInstanceOrClassType):
# func = func.__func__
#
# # Defer to the absolute filename of the Python file declaring this
# # callable, dynamically retrieved from this callable's code object.
# func_origin_label = func.__code__.co_filename
#
# Why? Because PyPy. The logic above succeeds for CPython but fails for
# PyPy, because *ALL CALLABLES ARE C-BASED IN PYPY.* Adopting the above
# approach would unconditionally return the C-specific placeholder string
# for all callables -- including those originally declared as pure-Python
# in a Python module. So it goes.
func_codeobj = get_func_codeobj_or_none(func)
# If the passed callable has *NO* code object and is thus *NOT*
# pure-Python, that callable was *NOT* defined by a pure-Python source code
# file. In this case, return "None".
if not func_codeobj:
return None
# Else, that callable is pure-Python.
# Absolute filename of the pure-Python source code file defining that
# callable if this code object offers that metadata *OR* "None" otherwise.
#
# Note that we intentionally do *NOT* assume all code objects to offer this
# metadata (e.g., by unconditionally returning "func_codeobj.co_filename").
# Why? Because PyPy yet again. For inexplicable reasons, PyPy provides
# *ALL* C-based builtins (e.g., len()) with code objects failing to provide
# this metadata. Yes, this is awful. Yes, this is the Python ecosystem.
func_filename = getattr(func_codeobj, 'co_filename', None)
# If this code object does *NOT* offer that metadata, return "None".
if not func_filename:
return None
# Else, this code object offers that metadata.
# print(f'func_filename: {func_filename}')
# If this filename is a "<"- and ">"-bracketed placeholder string, this
# filename is a placeholder signifying this callable to be dynamically
# declared in-memory rather than by an on-disk module. In this case...
#
# Examples of such strings include:
# * "<string>", signifying a callable dynamically declared in-memory.
# * "<@beartype(...) at 0x...}>', signifying a callable dynamically
# declared in-memory by the beartype._util.func.utilfuncmake.make_func()
# function, possibly cached with the standard "linecache" module.
if (
func_filename[ 0] == '<' and
func_filename[-1] == '>'
):
# Return either...
return (
# If this in-memory callable's source code was cached with the
# standard "linecache" module, this filename as is;
func_filename
if func_filename in linecache_cache else
# Else, this in-memory callable's source code was *NOT* cached with
# the "linecache" module and has thus effectively been destroyed. In
# this case, "None".
None
)
# Else, this filename if is actually that of an on-disk module.
# Return this filename as is, regardless of whether this file exists.
# Callers are responsible for performing further validation if desired.
return func_filename
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable code object utilities** (i.e., callables introspecting
**code objects** (i.e., instances of the :class:`CodeType` type) underlying all
pure-Python callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCallableException
from beartype.typing import (
Any,
Optional,
)
from beartype._util.func.utilfuncwrap import unwrap_func
from beartype._data.datatyping import (
Codeobjable,
TypeException,
)
from types import (
CodeType,
FrameType,
FunctionType,
GeneratorType,
MethodType,
)
# ....................{ CONSTANTS }....................
#FIXME: Unit test us up, please.
FUNC_CODEOBJ_NAME_MODULE = '<module>'
'''
String constant unconditionally assigned to the ``co_name`` instance variables
of the code objects of all pure-Python modules.
'''
# ....................{ GETTERS }....................
def get_func_codeobj(
# Mandatory parameters.
func: Codeobjable,
# Optional parameters.
is_unwrapping: bool = False,
exception_cls: TypeException = _BeartypeUtilCallableException,
) -> CodeType:
'''
**Code object** (i.e., instance of the :class:`CodeType` type) underlying
the passed **codeobjable** (i.e., pure-Python object directly associated
with a code object) if this object is codeobjable *or* raise an exception
otherwise (e.g., if this object is *not* codeobjable).
For convenience, this getter also accepts a code object, in which case that
code object is simply returned as is.
Code objects have a docstring under CPython resembling:
.. code-block:: python
Code objects provide these attributes:
co_argcount number of arguments (not including *, ** args
or keyword only arguments)
co_code string of raw compiled bytecode
co_cellvars tuple of names of cell variables
co_consts tuple of constants used in the bytecode
co_filename name of file in which this code object was
created
co_firstlineno number of first line in Python source code
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg |
8=**arg | 16=nested | 32=generator | 64=nofree |
128=coroutine | 256=iterable_coroutine |
512=async_generator
co_freevars tuple of names of free variables
co_posonlyargcount number of positional only arguments
co_kwonlyargcount number of keyword only arguments (not including
** arg)
co_lnotab encoded mapping of line numbers to bytecode
indices
co_name name with which this code object was defined
co_names tuple of names of local variables
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables
Parameters
----------
func : Codeobjable
Codeobjable to be inspected.
is_unwrapping: bool, optional
``True`` only if this getter implicitly calls the :func:`unwrap_func`
function to unwrap this possibly higher-level wrapper into a possibly
lower-level wrappee *before* returning the code object of that wrappee.
Note that doing so incurs worst-case time complexity ``O(n)`` for ``n``
the number of lower-level wrappees wrapped by this wrapper. Defaults to
``False`` for efficiency.
exception_cls : type, optional
Type of exception in the event of a fatal error. Defaults to
:class:`_BeartypeUtilCallableException`.
Returns
----------
CodeType
Code object underlying this callable.
Raises
----------
exception_cls
If this callable has *no* code object and is thus *not* pure-Python.
'''
# Code object underlying this callable if this callable is pure-Python *OR*
# "None" otherwise.
func_codeobj = get_func_codeobj_or_none(
func=func, is_unwrapping=is_unwrapping)
# If this callable is *NOT* pure-Python...
if func_codeobj is None:
# Avoid circular import dependencies.
from beartype._util.func.utilfunctest import die_unless_func_python
# Raise an exception.
die_unless_func_python(func=func, exception_cls=exception_cls)
# Else, this callable is pure-Python and this code object exists.
# Return this code object.
return func_codeobj # type: ignore[return-value]
def get_func_codeobj_or_none(
# Mandatory parameters.
func: Any,
# Optional parameters.
is_unwrapping: bool = False,
) -> Optional[CodeType]:
'''
**Code object** (i.e., instance of the :class:`CodeType` type) underlying
the passed **codeobjable** (i.e., pure-Python object directly associated
with a code object) if this object is codeobjable *or* ``None`` otherwise
(e.g., if this object is *not* codeobjable).
Specifically, if the passed object is a:
* Pure-Python function, this getter returns the code object of that
function (i.e., ``func.__code__``).
* Pure-Python bound method wrapping a pure-Python unbound function, this
getter returns the code object of the latter (i.e.,
``func.__func__.__code__``).
* Pure-Python call stack frame, this getter returns the code object of the
pure-Python callable encapsulated by that frame (i.e., ``func.f_code``).
* Pure-Python generator, this getter returns the code object of that
generator (i.e., ``func.gi_code``).
* Code object, this getter returns that code object as is.
* Any other object, this getter raises an exception.
Caveats
-------
If ``is_unwrapping``, **this callable has worst-case time complexity**
``O(n)`` **for** ``n`` **the number of lower-level wrappees wrapped by this
higher-level wrapper.** That parameter should thus be disabled in
time-critical code paths; instead, the lowest-level wrappee returned by the
:func:``beartype._util.func.utilfuncwrap.unwrap_func` function should be
temporarily stored and then repeatedly passed.
Parameters
----------
func : Codeobjable
Codeobjable to be inspected.
is_unwrapping: bool, optional
``True`` only if this getter implicitly calls the :func:`unwrap_func`
function to unwrap this possibly higher-level wrapper into a possibly
lower-level wrappee *before* returning the code object of that wrappee.
Note that doing so incurs worst-case time complexity ``O(n)`` for ``n``
the number of lower-level wrappees wrapped by this wrapper. Defaults to
``False`` for efficiency.
Returns
----------
Optional[CodeType]
Either:
* If the passed callable is pure-Python, that callable's code object.
* Else, ``None``.
See Also
----------
:func:`get_func_codeobj`
Further details.
'''
assert is_unwrapping.__class__ is bool, f'{is_unwrapping} not boolean.'
# Note that:
# * For efficiency, tests are intentionally ordered in decreasing
# likelihood of a successful match.
# * An equivalent algorithm could also technically be written as a chain of
# "getattr(func, '__code__', None)" calls, but that doing so would both
# be less efficient *AND* render this getter less robust. Why? Because
# the getattr() builtin internally calls the __getattr__() and
# __getattribute__() dunder methods (either of which could raise
# arbitrary exceptions) and is thus considerably less safe.
#
# If this object is already a code object, return this object as is.
if isinstance(func, CodeType):
return func
# Else, this object is *NOT* already a code object.
#
# If this object is a pure-Python function...
#
# Note that this test intentionally leverages the standard
# "types.FunctionType" class rather than our equivalent
# "beartype.cave.FunctionType" class to avoid circular import issues.
elif isinstance(func, FunctionType):
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize this with the same test below (for methods).
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Return the code object of either:
# * If unwrapping this function, the lowest-level wrappee wrapped by
# this function.
# * Else, this function as is.
return (unwrap_func(func) if is_unwrapping else func).__code__ # type: ignore[attr-defined]
# Else, this object is *NOT* a pure-Python function.
#
# If this callable is a bound method, return this method's code object.
#
# Note this test intentionally tests the standard "types.MethodType" class
# rather than our equivalent "beartype.cave.MethodBoundInstanceOrClassType"
# class to avoid circular import issues.
elif isinstance(func, MethodType):
# Unbound function underlying this bound method.
func = func.__func__
#FIXME: Can "MethodType" objects actually bind lower-level C-based
#rather than pure-Python functions? We kinda doubt it -- but maybe they
#can. If they can't, then this test is superfluous and should be
#removed with all haste.
# If this unbound function is pure-Python...
if isinstance(func, FunctionType):
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize this with the same test above.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Return the code object of either:
# * If unwrapping this function, the lowest-level wrappee wrapped
# by this function.
# * Else, this function as is.
return (unwrap_func(func) if is_unwrapping else func).__code__ # type: ignore[attr-defined]
# Else, this callable is *NOT* a pure-Python bound method.
#
# If this object is a pure-Python generator, return this generator's code
# object.
elif isinstance(func, GeneratorType):
return func.gi_code
# Else, this object is *NOT* a pure-Python generator.
#
# If this object is a call stack frame, return this frame's code object.
elif isinstance(func, FrameType):
#FIXME: *SUS AF.* This is likely to behave as expected *ONLY* for
#frames encapsulating pure-Python callables. For frames encapsulating
#C-based callables, this is likely to fail with an "AttributeError"
#exception. That said, we have *NO* idea how to test this short of
#defining our own C-based callable accepting a pure-Python callable as
#a callback parameter and calling that callback. Are there even C-based
#callables like that in the wild?
return func.f_code
# Else, this object is *NOT* a call stack frame. Since none of the above
# tests matched, this object *MUST* be a C-based callable.
# Fallback to returning "None".
return None
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable creation** utilities.
This private submodule implements utility functions dynamically creating new
callables on-the-fly.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCallableException
from beartype.typing import (
Optional,
Type,
)
from beartype._data.datatyping import LexicalScope
from beartype._util.text.utiltextlabel import label_exception
from beartype._util.text.utiltextmunge import number_lines
from beartype._util.utilobject import get_object_name
from collections.abc import Callable
from functools import update_wrapper
from linecache import cache as linecache_cache # type: ignore[attr-defined]
from weakref import finalize
# ....................{ MAKERS }....................
def make_func(
# Mandatory arguments.
func_name: str,
func_code: str,
# Optional arguments.
func_globals: Optional[LexicalScope] = None,
func_locals: Optional[LexicalScope] = None,
func_doc: Optional[str] = None,
func_label: Optional[str] = None,
func_wrapped: Optional[Callable] = None,
is_debug: bool = False,
exception_cls: Type[Exception] = _BeartypeUtilCallableException,
) -> Callable:
'''
Dynamically create and return a new function with the passed name declared
by the passed code snippet and internally accessing the passed dictionaries
of globally and locally scoped variables.
Parameters
----------
func_name : str
Name of the function to be created.
func_code : str
Code snippet defining this function, including both this function's
signature prefixed by zero or more decorations *and* body. **This
snippet must be unindented.** If this snippet is indented, this factory
raises a syntax error.
func_globals : Dict[str, Any], optional
Dictionary mapping from the name to value of each **globally scoped
attribute** (i.e., internally referenced in the body of the function
declared by this code snippet). Defaults to the empty dictionary.
func_locals : Dict[str, Any], optional
Dictionary mapping from the name to value of each **locally scoped
attribute** (i.e., internally referenced either in the signature of
the function declared by this code snippet *or* as decorators
decorating that function). **Note that this factory necessarily
modifies the contents of this dictionary.** Defaults to the empty
dictionary.
func_doc : str, optional
Human-readable docstring documenting this function. Defaults to
``None``, in which case this function remains undocumented.
func_label : str, optional
Human-readable label describing this function for error-handling
purposes. Defaults to ``{func_name}()``.
func_wrapped : Callable, optional
Callable wrapped by the function to be created. If non-``None``,
special dunder attributes will be propagated (i.e., copied) from this
wrapped callable into this created function; these include:
* ``__name__``, this function's unqualified name.
* ``__doc__``, this function's docstring.
* ``__module__``, the fully-qualified name of this function's module.
Defaults to ``None``.
is_debug : bool, optional
``True`` only if this function is being debugged. If ``True``, the
definition (including signature and body) of this function is:
* Printed to standard output.
* Cached with the standard :mod:`linecache` module under a fake
filename uniquely synthesized by this factory for this function.
External callers may then subsequently access the definition of this
function from that module as:
.. code-block:: python
from linecache import cache as linecache_cache
func_source = linecache_cache[func.__code__.co_filename]
Defaults to ``False``.
exception_cls : type, optional
Type of exception to raise in the event of a fatal error. Defaults to
:exc:`_BeartypeUtilCallableException`.
Returns
----------
Callable
Function with this name declared by this snippet.
Raises
----------
:exc:`exception_cls`
If either:
* ``func_locals`` contains a key whose value is that of ``func_name``,
implying the caller already declared a local attribute whose name
collides with that of this function.
* This code snippet is syntactically invalid.
* This code snippet is syntactically valid but fails to declare a
function with this name.
'''
# ..................{ VALIDATION ~ pre }..................
assert isinstance(func_name, str), f'{repr(func_name)} not string.'
assert isinstance(func_code, str), f'{repr(func_code)} not string.'
assert isinstance(is_debug, bool), f'{repr(is_debug)} not bool.'
assert func_name, 'Parameter "func_name" empty.'
assert func_code, 'Parameter "func_code" empty.'
# Default all unpassed parameters.
if func_globals is None:
func_globals = {}
if func_locals is None:
func_locals = {}
if func_label is None:
func_label = f'{func_name}()'
assert isinstance(func_globals, dict), (
f'{repr(func_globals)} not dictionary.')
assert isinstance(func_locals, dict), (
f'{repr(func_locals)} not dictionary.')
assert isinstance(func_label, str), f'{repr(func_label)} not string.'
# If that function's name is already in this local scope, the caller
# already declared a local attribute whose name collides with that
# function's. In this case, raise an exception for safety.
if func_name in func_locals:
raise exception_cls(
f'{func_label} already defined by caller locals:\n'
f'{repr(func_locals)}'
)
# Else, that function's name is *NOT* already in this local scope.
# ..................{ STARTUP ~ filename }..................
# Note that this logic is intentionally performed *BEFORE* munging the
# "func_code" string in-place below, as this logic depends upon the unique
# ID of that string. Reassignment obliterates that uniqueness.
# Arbitrary object uniquely associated with this function.
func_filename_object: object = None
# Possibly fully-qualified name of an arbitrary object uniquely associated
# with this function.
func_filename_name: str = None # type: ignore[assignment]
# If this function is a high-level wrapper wrapping a lower-level
# wrappee, uniquify the subsequent filename against this wrappee. This
# wrappee's fully-qualified name guarantees the uniqueness of this
# filename. Ergo, this is the ideal case.
if func_wrapped:
func_filename_name = get_object_name(func_wrapped)
func_filename_object = func_wrapped
# Else, this function is *NOT* such a wrapper. In this less ideal case,
# fallback to a poor man's uniquification against the unqualified name and
# code string underlying this function.
else:
func_filename_name = func_name
func_filename_object = func_code
# Fake in-memory filename hopefully unique to this function.
# Optimistically, a fully-qualified object name and ID *SHOULD* be unique
# for the lifetime of the active Python process.
#
# Specifically, this filename guarantees the uniqueness of the 3-tuple
# ``({func_filename}, {func_file_line_number}, {func_name})`` commonly
# leveraged by profilers (e.g., "cProfile") to identify arbitrary callables,
# where:
# * `{func_filename}` is this filename (e.g.,
# `"</home/leycec/py/betse/betse/lib/libs.py:beartype({func_name})>"`).
# * `{func_file_line_number}`, is *ALWAYS* 0 and thus *NEVER* unique.
# * `{func_name}`, is identical to that of the decorated callable and also
# thus *NEVER* unique.
#
# Ergo, uniquifying this filename is the *ONLY* means of uniquifying
# metadata identifying this wrapper function via runtime inspection. Failure
# to do so reduces tracebacks induced by exceptions raised by this wrapper
# to non-human-readability, which is less than ideal: e.g.,
#
# Traceback (most recent call last):
# File "/home/leycec/py/betsee/betsee/gui/simconf/stack/widget/mixin/guisimconfwdgeditscalar.py", line 313, in _set_alias_to_widget_value_if_sim_conf_open
# widget=self, value_old=self._widget_value_last)
# File "<string>", line 25, in func_beartyped
# File "/home/leycec/py/betsee/betsee/gui/simconf/stack/widget/mixin/guisimconfwdgeditscalar.py", line 409, in __init__
# *args, widget=widget, synopsis=widget.undo_synopsis, **kwargs)
# File "<string>", line 13, in func_beartyped
#
# See the final traceback line, which is effectively useless.
func_filename = (
f'<@beartype({func_filename_name}) at {id(func_filename_object):#x}>')
# ..................{ STARTUP ~ code }..................
# Code snippet defining this function, stripped of all leading and trailing
# whitespace to improve both readability and disambiguity. Since this
# whitespace is safely ignorable, the original snippet is safely
# replaceable by this stripped snippet.
func_code = func_code.strip()
# If debugging this function, print the definition of this function.
if is_debug:
print(f'{number_lines(func_code)}')
# else:
# print('!!!!!!!!!PRINTING NOTHING!!!!!!!!!!!')
# Else, leave that definition obscured by the voracious bitbuckets of time.
# ..................{ CREATION }..................
# Attempt to...
try:
# Call the more verbose and obfuscatory compile() builtin instead of
# simply calling "exec(func_code, func_globals, func_locals)". Why?
# Because the exec() builtin does *NOT* provide a means to set this
# function's "__code__.co_filename" read-only attribute.
#
# Note that we could pass "single" instead of "exec" here if we were
# willing to constrain the passed "func_code" to a single statement. In
# casual testing, there is very little performance difference between
# the two (with an imperceptibly slight edge going to "single").
func_code_compiled = compile(func_code, func_filename, 'exec')
assert func_name not in func_locals
# Define that function. For obscure and likely uninteresting reasons,
# Python fails to capture that function (i.e., expose that function to
# this factory) when the locals() dictionary is passed; instead, a
# unique local dictionary *MUST* be passed.
exec(func_code_compiled, func_globals, func_locals)
# If doing so fails for any reason...
except Exception as exception:
# Raise an exception suffixed by that function's declaration such that
# each line of that declaration is prefixed by that line's number. This
# renders "SyntaxError" exceptions referencing arbitrary line numbers
# human-readable: e.g.,
# File "<string>", line 56
# if not (
# ^
# SyntaxError: invalid syntax
raise exception_cls(
f'{func_label} unparseable, as @beartype generated '
f'invalid code raising "{label_exception(exception)}":\n\n'
f'{number_lines(func_code)}'
) from exception
# ..................{ VALIDATION ~ post }..................
# If that function's name is *NOT* in this local scope, this code snippet
# failed to declare that function. In this case, raise an exception.
if func_name not in func_locals:
raise exception_cls(
f'{func_label} undefined by code snippet:\n\n'
f'{number_lines(func_code)}'
)
# Else, that function's name is in this local scope.
# Function declared by this code snippet.
func: Callable = func_locals[func_name] # type: ignore[assignment]
# If that function is uncallable, raise an exception.
if not callable(func):
raise exception_cls(
f'{func_label} defined by code snippet uncallable:\n\n'
f'{number_lines(func_code)}'
)
# Else, that function is callable.
# If that function is a wrapper wrapping a wrappee callable, propagate
# dunder attributes from that wrappee onto this wrapper.
if func_wrapped is not None:
assert callable(func_wrapped), f'{repr(func_wrapped)} uncallable.'
update_wrapper(wrapper=func, wrapped=func_wrapped)
# Else, that function is *NOT* such a wrapper.
# ..................{ CLEANUP }..................
# If that function is documented...
#
# Note that function is intentionally documented *AFTER* propagating dunder
# attributes to enable callers to explicitly overwrite documentation
# propagated from that wrappee onto this wrapper.
if func_doc is not None:
assert isinstance(func_doc, str), f'{repr(func_doc)} not string.'
assert func_doc, '"func_doc" empty.'
# Document that function.
func.__doc__ = func_doc
# Else, that function is undocumented.
# If debugging this function...
if is_debug:
# Render this function debuggable (e.g., via the standard "pdb" module)
# by exposing this function's definition to the standard "linecache"
# module under the fake filename synthesized above.
#
# Technically, we *COULD* slightly improve the uniquification of this
# filename for the uncommon edge case when this function does *NOT*
# wrap a lower-level wrappee (e.g., by embedding the ID of this
# function that now exists rather than an arbitrary string object).
# Pragmatically, doing so would prevent external callers from trivially
# retrieving this function's definition from "linecache". Why? Because
# reusing the "func_filename" string embedded in this function as
# "func.__code__.co_filename" trivializes this lookup for callers.
# Ultimately, sane lookup >>> slightly uniquer filename.
linecache_cache[func_filename] = ( # type: ignore[assignment]
len(func_code), # type: ignore[assignment] # Y u gotta b diff'rnt Python 3.7? WHY?!
None, # mtime, but should be None to avoid being discarded
func_code.splitlines(keepends=True),
func_filename,
)
# Define and register a cleanup callback removing that function's
# linecache entry called if and when that function is
# garbage-collected.
def _remove_func_linecache_entry():
linecache_cache.pop(func_filename, None)
finalize(func, _remove_func_linecache_entry)
# Return that function.
return func
# ....................{ COPIERS }....................
#FIXME: Consider excising. Although awesome, this is no longer needed.
# from beartype._util.func.utilfunctest import die_unless_func_python
# from types import FunctionType
# def copy_func_shallow(
# # Mandatory arguments.
# func: Callable,
#
# # Optional arguments.
# exception_cls: Type[Exception] = _BeartypeUtilCallableException,
# ) -> Callable:
# '''
# Create and return a new shallow copy of the passed callable.
#
# Specifically, this function creates and returns a new function sharing with
# the passed callable the same:
#
# * Underlying code object (i.e., ``func.__code__``).
# * Unqualified and fully-qualified names (i.e., ``func.__name__`` and
# ``func.__qualname__``).
# * Docstring (i.e., ``func.__doc__``).
# * Type hints (i.e., ``func.__annotations__``).
# * Global scope (i.e., ``func.__globals__``).
# * Fully-qualified module name (i.e., ``func.__module__``).
# * Default values of optional parameters (i.e., ``f.__defaults__`` and
# ``f.__kwdefaults__``).
# * Closure-specific cell variables (i.e., ``f.__closure__``).
# * Custom public and private attributes.
#
# Parameters
# ----------
# func : Callable
# Callable to be copied.
# exception_cls : type, optional
# Type of exception to raise in the event of a fatal error. Defaults to
# :exc:`_BeartypeUtilCallableException`.
#
# Returns
# ----------
# Callable
# Function shallowly copied from the passed callable.
#
# Raises
# ----------
# exception_cls
# If the passed callable is *not* pure-Python.
#
# See Also
# ----------
# https://stackoverflow.com/a/30714299/2809027
# StackOverflow answer strongly inspiring this implementation.
# '''
#
# # If the passed callable is *NOT* pure-Python, raise an exception.
# die_unless_func_python(func=func, exception_cls=exception_cls)
#
# # Function shallowly copied from the passed callable.
# #
# # Note that *ALL* pure-Python callables are guaranteed to define the
# # following dunder attributes.
# func_copy = FunctionType(
# func.__code__,
# func.__globals__, # type: ignore[attr-defined]
# func.__name__,
# func.__defaults__, # type: ignore[attr-defined]
# func.__closure__, # type: ignore[attr-defined]
# )
#
# # Shallowly copy all remaining dunder attributes from the original callable
# # onto this copy *NOT* already copied by the FunctionType.__init__() method
# # called above.
# #
# # Note that *ALL* pure-Python callables are guaranteed to define the
# # following dunder attributes.
# func_copy.__annotations__ = func.__annotations__
# func_copy.__doc__ = func.__doc__
# func_copy.__kwdefaults__ = func.__kwdefaults__ # type: ignore[attr-defined]
# func_copy.__module__ = func.__module__
# func_copy.__qualname__ = func.__qualname__
#
# # Shallowly copy all custom attributes (i.e., non-dunder attributes
# # explicitly set by the caller) from the original callable onto this copy.
# func_copy.__dict__.update(func.__dict__)
# # print(f'func.__dict__: {func.__dict__}')
# # print(f'func_copy.__dict__: {func_copy.__dict__}')
#
# # Return this copy.
# return func_copy
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable scope** utilities (i.e., functions handling the
possibly nested lexical scopes enclosing arbitrary callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCallableException
from beartype.typing import (
Any,
Optional,
)
from beartype._util.utilobject import get_object_basename_scoped
from beartype._data.datakind import DICT_EMPTY
from beartype._data.datatyping import (
LexicalScope,
TypeException,
)
from collections.abc import Callable
from types import CodeType
# ....................{ TESTERS }....................
def is_func_nested(func: Callable) -> bool:
'''
``True`` only if the passed callable is **nested** (i.e., a pure-Python
callable declared in the body of another pure-Python callable).
Parameters
----------
func : Callable
Callable to be inspected.
Returns
----------
bool
``True`` only if this callable is nested.
'''
assert callable(func), f'{repr(func)} not callable.'
# Return true only if the fully-qualified name of this callable contains
# one or more "." delimiters, each signifying a nested lexical scope. Since
# *ALL* callables (i.e., both pure-Python and C-based) define a non-empty
# "__qualname__" dunder variable containing at least their unqualified
# names, this simplistic test is guaranteed to be safe.
#
# Note this function intentionally tests for the general-purpose existence
# of a "." delimiter rather than the special-cased existence of a
# ".<locals>." placeholder substring. Why? Because there are two types of
# nested callables:
# * Non-methods, which are lexically nested in a parent callable whose
# scope encapsulates all previously declared local variables. For unknown
# reasons, the unqualified names of nested non-method callables are
# *ALWAYS* prefixed by ".<locals>." in their "__qualname__" variables:
# >>> from collections.abc import Callable
# >>> def muh_parent_callable() -> Callable:
# ... def muh_nested_callable() -> None: pass
# ... return muh_nested_callable
# >>> muh_nested_callable = muh_parent_callable()
# >>> muh_parent_callable.__qualname__
# 'muh_parent_callable'
# >>> muh_nested_callable.__qualname__
# 'muh_parent_callable.<locals>.muh_nested_callable'
# * Methods, which are lexically nested in the scope encapsulating all
# previously declared class variables (i.e., variables declared in class
# scope and thus accessible as method annotations). For unknown reasons,
# the unqualified names of methods are *NEVER* prefixed by ".<locals>."
# in their "__qualname__" variables: e.g.,
# >>> from typing import ClassVar
# >>> class MuhClass(object):
# ... # Class variable declared in class scope.
# ... muh_class_var: ClassVar[type] = int
# ... # Instance method annotated by this class variable.
# ... def muh_method(self) -> muh_class_var: return 42
# >>> MuhClass.muh_method.__qualname__
# 'MuhClass.muh_method'
return '.' in func.__qualname__
#FIXME: Unit test us up.
#FIXME: Technically, we currently don't call this anywhere. But we probably
#will someday, so let's preserve this intact until then. *shrug*
# def is_func_closure(func: Callable) -> bool:
# '''
# ``True`` only if the passed callable is a **closure** (i.e.,
# nested callable accessing one or more variables declared by the parent
# callable also declaring that callable).
#
# Note that all closures are necessarily nested callables but that the
# converse is *not* necessarily the case. In particular, a nested callable
# accessing no variables declared by the parent callable also declaring that
# callable is *not* a closure.
#
# Parameters
# ----------
# func : Callable
# Callable to be inspected.
#
# Returns
# ----------
# bool
# ``True`` only if this callable is a closure.
# '''
# assert callable(func), f'{repr(func)} not callable.'
#
# # Return true only if this callable defines a closure-specific dunder
# # attribute whose value is either:
# # * If this callable is a closure, a tuple of zero or more cell variables.
# # * If this callable is a pure-Python non-closure, "None".
# # * If this callable is C-based, undefined.
# return getattr(func, '__closure__', None) is not None
# ....................{ GETTERS }....................
#FIXME: Unit test us up, please.
def get_func_globals(
# Mandatory parameters.
func: Callable,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilCallableException,
) -> LexicalScope:
'''
**Global scope** (i.e., a dictionary mapping from the name to value of each
globally scoped attribute declared by the module transitively declaring
the passed pure-Python callable) for this callable.
This getter transparently supports **wrapper callables** (i.e.,
higher-level callables whose identifying metadata was propagated from other
lowel-level callables at either decoration time via the
:func:`functools.wraps` decorator *or* after declaration via the
:func:`functools.update_wrapper` function).
Parameters
----------
func : Callable
Callable to be inspected.
func_stack_frames_ignore : int, optional
Number of frames on the call stack to be ignored (i.e., silently
incremented past), such that the next non-ignored frame following the
last ignored frame is the parent callable or module directly declaring
the passed callable. Defaults to 0.
exception_cls : Type[Exception], optional
Type of exception to be raised in the event of a fatal error. Defaults
to :class:`_BeartypeUtilCallableException`.
Returns
----------
Dict[str, Any]
Global scope for this callable.
Raises
----------
exception_cls
If this callable is a wrapper wrapping a C-based rather than
pure-Python wrappee callable.
'''
assert callable(func), f'{repr(func)} not callable.'
# Avoid circular import dependencies.
from beartype._util.func.utilfunctest import die_unless_func_python
from beartype._util.func.utilfuncwrap import unwrap_func
# If this callable is *NOT* pure-Python, raise an exception. C-based
# callables do *NOT* define the "__globals__" dunder attribute.
die_unless_func_python(func=func, exception_cls=exception_cls)
# Else, this callable is pure-Python.
# Lowest-level wrappee callable wrapped by this wrapper callable.
func_wrappee = unwrap_func(func)
# Dictionary mapping from the name to value of each locally scoped
# attribute accessible to this wrappee callable to be returned.
#
# Note that we intentionally do *NOT* return the global scope for this
# wrapper callable, as wrappers are typically defined in different modules
# (and thus different global scopes) by different module authors.
return func_wrappee.__globals__ # type: ignore[attr-defined]
def get_func_locals(
# Mandatory parameters.
func: Callable,
# Optional parameters.
func_scope_names_ignore: int = 0,
func_stack_frames_ignore: int = 0,
exception_cls: TypeException = _BeartypeUtilCallableException,
) -> LexicalScope:
'''
**Local scope** for the passed callable.
This getter returns either:
* If that callable is **nested** (i.e., is a method *or* is a non-method
callable declared in the body of another callable), a dictionary mapping
from the name to value of each **locally scoped attribute** (i.e., local
attribute declared by a parent callable transitively declaring that
callable) accessible to that callable.
* Else, the empty dictionary otherwise (i.e., if that callable is a
function directly declared by a module).
This getter transparently supports methods, which in Python are lexically
nested in the scope encapsulating all previously declared **class
variables** (i.e., variables declared from class scope and thus accessible
as type hints when annotating the methods of that class). When declaring a
class, Python creates a stack frame for the declaration of that class whose
local scope is the set of all class-scoped attributes declared in the body
of that class (including class variables, class methods, static methods,
and instance methods). When passed any method, this getter finds and
returns that local scope. When passed the ``MuhClass.muh_method` method
declared by the following example, for example, this getter returns the
local scope containing the key ``'muh_class_var'`` with value ``int``:
.. code-block:: python
>>> from typing import ClassVar
>>> class MuhClass(object):
... # Class variable declared in class scope.
... muh_class_var: ClassVar[type] = int
... # Instance method annotated by this class variable.
... def muh_method(self) -> muh_class_var: return 42
However, note that this getter's transparent support for methods does *not*
extend to methods of the currently decorated class. Why? Because that class
has yet to be declared and thus added to the call stack.
Caveats
----------
**This high-level getter requires the private low-level**
:func:`sys._getframe` **getter.** If that getter is undefined, this getter
unconditionally treats the passed callable as module-scoped by returning the
empty dictionary rather than raising an exception. Since all standard
Python implementations (e.g., CPython, PyPy) define that getter, this
should typically *not* be a real-world concern.
**This high-level getter is inefficient and should thus only be called if
absolutely necessary.** Specifically, deciding the local scope for any
callable is an ``O(k)`` operation for ``k`` the distance in call stack
frames from the call of the current function to the call of the top-most
parent scope transitively declaring the passed callable in its submodule.
Ergo, this decision problem should be deferred as long as feasible to
minimize space and time consumption.
Parameters
----------
func : Callable
Callable to be inspected.
func_scope_names_ignore : int, optional
Number of parent lexical scopes in the fully-qualified name of that
callable to be ignored (i.e., silently incremented past), such that the
next non-ignored lexical scope preceding the first ignored lexical scope
is that of the parent callable or module directly declaring the passed
callable. This parameter is typically used to ignore the parent lexical
scopes of parent classes lexically nesting that callable that have yet
to be fully declared and thus encapsulated by stack frames on the call
stack (e.g., due to being currently decorated by
:func:`beartype.beartype`). See the :mod:`beartype._decor._pep.pep563`
submodule for the standard use case. Defaults to 0.
func_stack_frames_ignore : int, optional
Number of frames on the call stack to be ignored (i.e., silently
incremented past), such that the next non-ignored frame following the
last ignored frame is the parent callable or module directly declaring
the passed callable. Defaults to 0.
exception_cls : Type[Exception], optional
Type of exception to be raised in the event of a fatal error. Defaults
to :class:`_BeartypeUtilCallableException`.
Returns
----------
LexicalScope
Local scope for this callable.
Raises
----------
:exc:`exception_cls`
If the next non-ignored frame following the last ignored frame is *not*
the parent callable or module directly declaring the passed callable.
'''
assert callable(func), f'{repr(func)} not callable.'
assert isinstance(func_scope_names_ignore, int), (
f'{func_scope_names_ignore} not integer.')
assert func_scope_names_ignore >= 0, (
f'{func_scope_names_ignore} negative.')
assert isinstance(func_stack_frames_ignore, int), (
f'{func_stack_frames_ignore} not integer.')
assert func_stack_frames_ignore >= 0, (
f'{func_stack_frames_ignore} negative.')
# print(f'\n--------- Capturing nested {func.__qualname__}() local scope...')
# ..................{ IMPORTS }..................
# Avoid circular import dependencies.
from beartype._util.func.utilfunccodeobj import (
FUNC_CODEOBJ_NAME_MODULE,
get_func_codeobj_or_none,
)
from beartype._util.func.utilfuncframe import iter_frames
# ..................{ NOOP }..................
# Fully-qualified name of the module declaring the passed callable if that
# callable was physically declared by an on-disk module *OR* "None"
# otherwise (i.e., if that callable was dynamically declared in-memory).
func_module_name = func.__module__
# Note that we intentionally return the local scope for this wrapper rather
# than wrappee callable, as local scope can *ONLY* be obtained by
# dynamically inspecting local attributes bound to call frames on the
# current call stack. However, this wrapper was called at a higher call
# frame than this wrappee. All local attributes declared within the body of
# this wrapper callable are irrelevant to this wrappee callable, as Python
# syntactically parsed the latter at a later time than the former. If we
# returned the local scope for this wrappee rather than wrapper callable,
# we would erroneously return local attributes that this wrappee callable
# originally had no lexical access to. That's bad. So, we don't do that.
#
# If either...
if (
# The passed callable is dynamically declared in-memory...
func_module_name is None or
# The passed callable is module-scoped rather than nested *OR*...
not is_func_nested(func)
# Then silently reduce to a noop by treating this nested callable as
# module-scoped by preserving "func_locals" as the empty dictionary.
):
return DICT_EMPTY
# Else, all of the following constraints hold:
# * The passed callable is physically declared on-disk.
# * The passed callable is nested.
# ..................{ LOCALS ~ scope }..................
# Local scope of the passed callable to be returned.
func_scope: LexicalScope = {}
# ..................{ LOCALS ~ scope : name }..................
# Unqualified name of this nested callable.
func_name_unqualified = func.__name__
# Fully-qualified name of this nested callable. If this nested callable is
# a non-method, this name contains one or more meaningless placeholders
# "<locals>" -- each identifying one parent callable lexically containing
# this nested callable: e.g.,
# >>> def muh_func():
# ... def muh_closure(): pass
# ... return muh_closure()
# >>> muh_func().__qualname__
# 'muh_func.<locals>.muh_closure'
func_name_qualified = get_object_basename_scoped(func)
# Non-empty list of the unqualified names of all parent callables lexically
# containing that nested callable (including that nested callable itself).
#
# Note that:
# * The set of all callables embodied by the current runtime call stack is
# a (usually proper) superset of the set of all callables embodied by the
# lexical scopes encapsulating this nested callable. Ergo:
# * Some stack frames have no corresponding lexical scopes (e.g., stack
# frames embodying callables defined by different modules).
# * *ALL* lexical scopes have a corresponding stack frame.
# * Stack frames are only efficiently accessible relative to the initial
# stack frame embodying this nested callable, which resides at the end of
# the call stack. This implies we *MUST* iteratively search up the call
# stack for frames with relevant lexical scopes and ignore intervening
# frames with irrelevant lexical scopes, starting at the stack top (end).
func_scope_names = func_name_qualified.rsplit(sep='.')
# Number of lexical scopes encapsulating that callable.
func_scope_names_len = len(func_scope_names)
# If that nested callable is *NOT* encapsulated by at least two lexical
# scopes identifying at least that nested callable and the parent callable
# or class declaring that nested callable, raise an exception.
#
# You are probably now contemplating to yourself in the special darkness of
# your own personal computer cave: "But @leycec, isn't this condition
# *ALWAYS* the case? The above `not is_func_nested()` check already ignored
# non-nested callables."
#
# Allow me to now explicate. By the check above, that callable is nested...
# By the check below, however, only one lexical scope encapsulates that
# callable. This is not a contradiction. This is just a malicious caller.
# The get_object_basename_scoped() getter called above silently removed all
# "<locals>." placeholders from this list of lexical scopes, because those
# "<locals>." placeholders convey no meaningful semantics. But the
# is_func_nested() tester detects nested callables by searching for those
# "<locals>." placeholders. It follows that the caller triggered this
# condition by maliciously renaming the "__qualname__" dunder attribute of
# the passed callable to be erroneously prefixed by "<locals>". Curiously,
# Python permits such manhandling: e.g.,
# # Python thinks this is fine.
# >>> def muh_func(): pass
# >>> muh_func.__qualname__ = '<locals>.muh_func' # <-- curse you!
if func_scope_names_len < 2:
raise exception_cls(
f'{func_name_unqualified}() fully-qualified name '
f'{func.__qualname__}() invalid (e.g., placeholder substring '
f'"<locals>" not preceded by parent callable name).'
)
# Else, that nested callable is encapsulated by at least two lexical
# scopes identifying at least that nested callable and the parent callable
# or class declaring that nested callable.
#
# If the unqualified basename of the last parent callable lexically
# containing the passed callable is *NOT* that callable itself, the caller
# maliciously renamed one but *NOT* both of "__qualname__" and "__name__".
# In this case, raise an exception. Again, Python permits this. *sigh*
elif func_scope_names[-1] != func_name_unqualified:
raise exception_cls(
f'{func_name_unqualified}() fully-qualified name '
f'{func.__qualname__}() invalid (i.e., last lexical scope '
f'"{func_scope_names[-1]}" != unqualified name '
f'"{func_name_unqualified}").'
)
# Else, the unqualified basename of the last parent callable lexically
# containing the passed callable is that callable itself.
# 1-based negative index of the unqualified basename of the parent callable
# or module directly lexically containing the passed callable in the list of
# all unqualified basenames encapsulating that callable. By the above
# validation, this index is guaranteed to begin at the second-to-last
# basename in this list.
func_scope_names_index = -2 - func_scope_names_ignore
# Number of unignorable lexical scopes encapsulating that callable,
# magically adding 1 to account for the fact that "func_scope_names_index"
# is a 1-based negative index rather than 0-based positive index.
func_scope_names_search_len = (
func_scope_names_len + func_scope_names_index + 1)
# If exactly *ZERO* unignorable lexical scopes encapsulate that callable,
# all lexical scopes encapsulating that callable are exactly ignorable,
# implying that there is *NO* parent lexical scope to search for. In this
# case, silently reduce to a noop by returning the empty dictionary.
if func_scope_names_search_len == 0:
return DICT_EMPTY
# If a *NEGATIVE* number of unignorable lexical scopes encapsulate that
# callable, the caller erroneously insists that there exist more ignorable
# lexical scopes encapsulating that callable than there actually exist
# lexical scopes encapsulating that callable. The caller is profoundly
# mistaken. Whereas the prior branch is a non-erroneous condition that
# commonly occurs, this current branch is an erroneous condition that should
# *NEVER* occur. In this case...
elif func_scope_names_search_len < 0:
# Number of parent lexical scopes containing that callable.
func_scope_parents_len = func_scope_names_len - 1
# Raise an exception.
raise exception_cls(
f'Callable name "{func_name_qualified}" contains only '
f'{func_scope_parents_len} parent lexical scope(s) but '
f'"func_scope_names_ignore" parameter ignores '
f'{func_scope_names_ignore} parent lexical scope(s), leaving '
f'{func_scope_names_search_len} parent lexical scope(s) to be '
f'searched for {func_name_qualified}() locals.'
)
# Else, there are one or more unignorable lexical scopes to be searched.
# Unqualified basename of the parent callable or module directly lexically
# containing the passed callable.
#
# Note that that the parent callable's local runtime scope transitively
# contains *ALL* local variables accessible to this nested callable
# (including the local variables directly contained in the body of that
# parent callable as well as the local variables directly contained in the
# bodies of all parent callables of that callable in the same lexical
# scope). Since that parent callable's local runtime scope is exactly the
# dictionary to be returned, iteration below searches up the runtime call
# stack for a stack frame embodying that parent callable and no further.
func_scope_name = func_scope_names[func_scope_names_index]
# print(f'Searching for parent {func_scope_name}() local scope...')
# ..................{ LOCALS ~ frame }..................
# Code object underlying the parent callable associated with the current
# stack frame if that callable is pure-Python *OR* "None".
func_frame_codeobj: Optional[CodeType] = None
# Fully-qualified name of that callable's module.
func_frame_module_name = ''
# Unqualified name of that callable.
func_frame_name = ''
# ..................{ SEARCH }..................
# While at least one frame remains on the call stack, iteratively search up
# the call stack for a stack frame embodying the parent callable directly
# declaring this nested callable, whereupon that parent callable's local
# runtime scope is returned as is.
#
# Note this also implicitly skips past all other decorators applied *AFTER*
# @beartype (and thus residing lexically above @beartype) in caller code to
# this nested callable: e.g.,
# @the_way_of_kings <--- skipped past
# @words_of_radiance <--- skipped past
# @oathbringer <--- skipped past
# @rhythm_of_war <--- skipped past
# @beartype
# def the_stormlight_archive(bruh: str) -> str:
# return bruh
for func_frame in iter_frames(
# 0-based index of the first non-ignored frame following the last
# ignored frame, ignoring an additional frame embodying the current
# call to this getter.
func_stack_frames_ignore=func_stack_frames_ignore + 1,
):
# Code object underlying this frame's scope if that scope is
# pure-Python *OR* "None" otherwise.
func_frame_codeobj = get_func_codeobj_or_none(func_frame)
# If this code object does *NOT* exist, this scope is C-based. In this
# case, silently ignore this scope and proceed to the next frame.
if func_frame_codeobj is None:
continue
# Else, this code object exists, implying this scope to be pure-Python.
# Fully-qualified name of that scope's module.
func_frame_module_name = func_frame.f_globals['__name__']
# Unqualified name of that scope.
func_frame_name = func_frame_codeobj.co_name
# print(f'{func_frame_name}() locals: {repr(func_frame.f_locals)}')
# If that scope is the placeholder string assigned by the active Python
# interpreter to all scopes encapsulating the top-most lexical scope of
# a module in the current call stack, this search has just crossed a
# module boundary and is thus no longer searching within the module
# declaring this nested callable and has thus failed to find the
# lexical scope of the parent declaring this nested callable. Why?
# Because that scope *MUST* necessarily be in the same module as that
# of this nested callable. In this case, raise an exception.
if func_frame_name == FUNC_CODEOBJ_NAME_MODULE:
raise exception_cls(
f'{func_name_qualified}() parent lexical scope '
f'{func_scope_name}() not found on call stack.'
)
# Else, that scope is *NOT* a module.
#
# If...
elif (
# That callable's name is that of the current lexical scope to be
# found *AND*...
func_frame_name == func_scope_name and
# That callable's module is that of this nested callable's and thus
# resides in the same lexical scope...
func_frame_module_name == func_module_name
):
# Then that callable embodies the lexical scope to be found. In this
# case, that callable is the parent callable directly declaring this
# nested callable.
#
# Note that this scope *CANNOT* be validated to declare this nested
# callable. Why? Because this getter function is called by the
# @beartype decorator when decorating this nested callable, which has
# yet to be declared until @beartype creates and returns a new wrapper
# function and is thus unavailable from this scope: e.g.,
# # This conditional *ALWAYS* raises an exception, because this
# # nested callable has yet to be declared.
# if func_name not in func_locals:
# raise exception_cls(
# f'{func_label} not declared by lexically scoped parent '
# f'callable(s) that declared local variables:\n{repr(func_locals)}'
# )
#
# Ergo, we have *NO* alternative but to blindly assume the above
# algorithm correctly collected this scope, which we only do because we
# have exhaustively tested this with *ALL* edge cases.
# print(f'{func_frame_name}() locals: {repr(func_frame.f_locals)}')
# Local scope of the passed callable. Since this nested callable is
# directly declared in the body of this parent callable, the local
# scope of this nested callable is *EXACTLY* the local scope of the
# body of this parent callable. Well, isn't that special?
func_scope = func_frame.f_locals
# Halt iteration.
break
# Else, that callable does *NOT* embody the current lexical scope to be
# found. In this case, silently ignore that callable and proceed to the
# next frame in the call stack.
# Return the local scope of the passed callable.
return func_scope
# ....................{ ADDERS }....................
def add_func_scope_attr(
# Mandatory parameters.
attr: Any,
func_scope: LexicalScope,
# Optional parameters.
exception_prefix: str = 'Globally or locally scoped attribute ',
) -> str:
'''
Add a new **scoped attribute** (i.e., new key-value pair of the passed
dictionary mapping from the name to value of each globally or locally scoped
attribute externally accessed elsewhere, whose key is a machine-readable
name internally generated by this function to uniquely refer to the passed
object and whose value is that object) to the passed scope *and* return that
name.
Parameters
----------
attr : Any
Arbitrary object to be added to this scope.
func_scope : LexicalScope
Local or global scope to add this object to.
exception_prefix : str, optional
Human-readable label prefixing the representation of this object in the
exception message. Defaults to the empty string.
Returns
----------
str
Name of the passed object in this scope generated by this function.
Raises
----------
:exc:`_BeartypeUtilCallableException`
If an attribute with the same name as that internally generated by
this adder but having a different value already exists in this scope.
This adder uniquifies names by object identifier and should thus
*never* generate name collisions. This exception is thus intentionally
raised as a private rather than public exception.
'''
assert isinstance(func_scope, dict), f'{repr(func_scope)} not dictionary.'
assert isinstance(exception_prefix, str), (
f'{repr(exception_prefix)} not string.')
# Name of the new attribute referring to this object in this scope, mildly
# obfuscated so as to avoid name collisions.
attr_name = f'__beartype_object_{id(attr)}'
# If an attribute with the same name but differing value already exists in
# this scope, raise an exception.
if func_scope.get(attr_name, attr) is not attr:
raise _BeartypeUtilCallableException(
f'{exception_prefix}"{attr_name}" already exists with differing value:\n'
f'~~~~[ NEW VALUE ]~~~~\n{repr(attr)}\n'
f'~~~~[ OLD VALUE ]~~~~\n{repr(func_scope[attr_name])}'
)
# Else, either no attribute with this name exists in this scope *OR* an
# attribute with this name and value already exists in this scope.
# Refer to the passed object in this scope with this name.
func_scope[attr_name] = attr
# Return this name.
return attr_name
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable wrapper** (i.e., higher-level callable, typically
implemented as a decorator, wrapping a lower-level callable) utilities.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.typing import Any
from collections.abc import Callable
# ....................{ UNWRAPPERS }....................
def unwrap_func(func: Any) -> Callable:
'''
Lowest-level **wrappee** (i.e., callable wrapped by the passed wrapper
callable) of the passed higher-level **wrapper** (i.e., callable wrapping
the wrappee callable to be returned) if the passed callable is a wrapper
*or* that callable as is otherwise (i.e., if that callable is *not* a
wrapper).
Specifically, this getter iteratively undoes the work performed by:
* One or more consecutive uses of the :func:`functools.wrap` decorator on
the wrappee callable to be returned.
* One or more consecutive calls to the :func:`functools.update_wrapper`
function on the wrappee callable to be returned.
Parameters
----------
func : Callable
Wrapper callable to be inspected.
Returns
----------
Callable
Either:
* If the passed callable is a wrapper, the lowest-level wrappee
callable wrapped by that wrapper.
* Else, the passed callable as is.
'''
# While this callable still wraps another callable, unwrap one layer of
# wrapping by reducing this wrapper to its next wrappee.
while hasattr(func, '__wrapped__'):
func = func.__wrapped__ # type: ignore[attr-defined]
# Return this wrappee, which is now guaranteed to *NOT* be a wrapper.
return func
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide :pep:`484`-compliant **callable utilities** (i.e., callables
specifically applicable to :pep:`484`-compliant decorators used to decorate
user-defined callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from collections.abc import Callable
# ....................{ TESTERS }....................
def is_func_pep484_notypechecked(func: Callable) -> bool:
'''
``True`` only if the passed callable was decorated by the
:pep:`484`-compliant :func:`typing.no_type_check` decorator instructing
both static and runtime type checkers to ignore that callable with respect
to type-checking (and thus preserve that callable as is).
Parameters
----------
func : Callable
Callable to be inspected.
Returns
----------
bool
``True`` only if that callable was decorated by the
:pep:`484`-compliant :func:`typing.no_type_check` decorator.
'''
# Return true only if that callable declares a dunder attribute hopefully
# *ONLY* declared on that callable by the @typing.no_type_check decorator.
return getattr(func, '__no_type_check__', False) is True
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable parameter iterator utilities** (i.e., callables
introspectively iterating over parameters accepted by arbitrary callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.typing import (
Dict,
Iterable,
Optional,
Tuple,
)
from beartype._util.func.utilfunccodeobj import get_func_codeobj
from beartype._util.func.utilfuncwrap import unwrap_func
from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_8
from collections.abc import Callable
from enum import (
Enum,
auto as next_enum_member_value,
unique as die_unless_enum_member_values_unique,
)
from inspect import CO_VARARGS, CO_VARKEYWORDS
from itertools import count
from types import CodeType
# ....................{ ENUMERATIONS }....................
@die_unless_enum_member_values_unique
class ArgKind(Enum):
'''
Enumeration of all kinds of **callable parameters** (i.e., arguments passed
to pure-Python callables).
This enumeration intentionally declares members of the same name as those
declared by the standard :class:`inspect.Parameter` class. Whereas the
former are unconditionally declared below and thus portable across Python
versions, the latter are only conditionally declared depending on Python
version and thus non-portable across Python versions. Notably, the
:attr:`inspect.Parameter.POSITIONAL_ONLY` attribute is only defined under
Python >= 3.8.
Attributes
----------
POSITIONAL_ONLY : EnumMemberType
Kind of all **positional-only parameters** (i.e., parameters required
to be passed positionally, syntactically followed in the signatures of
their callables by the :pep:`570`-compliant ``/,`` pseudo-parameter).
POSITIONAL_OR_KEYWORD : EnumMemberType
Kind of all **flexible parameters** (i.e., parameters permitted to be
passed either positionally or by keyword).
VAR_POSITIONAL : EnumMemberType
Kind of all **variadic positional parameters** (i.e., tuple of zero or
more positional parameters *not* explicitly named by preceding
positional-only or flexible parameters, syntactically preceded by the
``*`` prefix and typically named ``*args``).
KEYWORD_ONLY : EnumMemberType
Kind of all **keyword-only parameters** (i.e., parameters required to
be passed by keyword, syntactically preceded in the signatures of
their callables by the :pep:`3102`-compliant ``*,`` pseudo-parameter).
VAR_KEYWORD : EnumMemberType
Kind of all **variadic keyword parameters** (i.e., tuple of zero or
more keyword parameters *not* explicitly named by preceding
keyword-only or flexible parameters, syntactically preceded by the
``**`` prefix and typically named ``**kwargs``).
'''
POSITIONAL_ONLY = next_enum_member_value()
POSITIONAL_OR_KEYWORD = next_enum_member_value()
VAR_POSITIONAL = next_enum_member_value()
KEYWORD_ONLY = next_enum_member_value()
VAR_KEYWORD = next_enum_member_value()
# ....................{ SINGLETONS }....................
ArgMandatory = object()
'''
Arbitrary sentinel singleton assigned by the
:func:`iter_func_args` generator to the :data:`ARG_META_INDEX_DEFAULT` fields
of all :data:`ArgMeta` instances describing **mandatory parameters** (i.e.,
parameters that *must* be explicitly passed to their callables).
'''
# ....................{ HINTS }....................
ArgMeta = Tuple[ArgKind, str, object]
'''
PEP-compliant type hint matching each 3-tuple ``(arg_kind, arg_name,
default_value_or_mandatory)`` iteratively yielded by the :func:`iter_func_args`
generator for each parameter accepted by the passed pure-Python callable, where:
* ``arg_kind`` is this parameter's **kind** (i.e., :class:`ArgKind` enumeration
member conveying this parameter's syntactic class, constraining how the
callable declaring this parameter requires this parameter to be passed).
* ``name`` is this parameter's **name** (i.e., syntactically valid Python
identifier uniquely identifying this parameter in its parameter list).
* ``default_value_or_mandatory`` is either:
* If this parameter is mandatory, the magic constant :data:`ArgMandatory`.
* Else, this parameter is optional and thus defaults to a default value
when unpassed. In this case, this is that default value.
'''
# ....................{ CONSTANTS ~ index }....................
# Iterator yielding the next integer incrementation starting at 0, to be safely
# deleted *AFTER* defining the following 0-based indices via this iterator.
__arg_meta_index_counter = count(start=0, step=1)
ARG_META_INDEX_KIND = next(__arg_meta_index_counter)
'''
0-based index into each 4-tuple iteratively yielded by the generator returned
by the :func:`iter_func_args` generator function of the currently iterated
parameter's **kind** (i.e., :class:`ArgKind` enumeration member conveying
this parameter's syntactic class, constraining how the callable declaring this
parameter requires this parameter to be passed).
'''
ARG_META_INDEX_NAME = next(__arg_meta_index_counter)
'''
0-based index into each 4-tuple iteratively yielded by the generator returned
by the :func:`iter_func_args` generator function of the currently iterated
parameter's **name** (i.e., syntactically valid Python identifier uniquely
identifying this parameter in its parameter list).
'''
ARG_META_INDEX_DEFAULT = next(__arg_meta_index_counter)
'''
0-based index into each 4-tuple iteratively yielded by the generator returned
by the :func:`iter_func_args` generator function of the currently iterated
parameter's **default value** specified as either:
* If this parameter is mandatory, the magic constant :data:`ArgMandatory`.
* Else, this parameter is optional and thus defaults to a default value when
unpassed. In this case, this is that default value.
'''
# Delete the above counter for safety and sanity in equal measure.
del __arg_meta_index_counter
# ....................{ GENERATORS }....................
def iter_func_args(
# Mandatory parameters.
func: Callable,
# Optional parameters.
func_codeobj: Optional[CodeType] = None,
is_unwrapping: bool = True,
# Note this generator is intentionally annotated as returning a high-level
# "Iterable[...]" rather than a low-level "Generator[..., ..., ...]", as the
# syntax governing the latter is overly verbose and largely unhelpful.
) -> Iterable[ArgMeta]:
'''
Generator yielding one **parameter metadata tuple** (i.e., tuple whose
items describe a single parameter) for each parameter accepted by the
passed pure-Python callable.
For consistency with the official grammar for callable signatures
standardized by :pep:`570`, this generator is guaranteed to yield parameter
metadata in the same order as required by Python syntax and semantics. In
order, this is:
* **Mandatory positional-only parameters** (i.e., parameter metadata
whose kind is :attr:`ArgKind.POSITIONAL_ONLY` and whose default value is
:data:`ArgMandatory`).
* **Optional positional-only parameters** (i.e., parameter metadata
whose kind is :attr:`ArgKind.POSITIONAL_ONLY` and whose default value is
*not* :data:`ArgMandatory`).
* **Mandatory flexible parameters** (i.e., parameter metadata whose kind is
:attr:`ArgKind.POSITIONAL_OR_KEYWORD` and whose default value is
:data:`ArgMandatory`).
* **Optional flexible parameters** (i.e., parameter metadata whose kind is
:attr:`ArgKind.POSITIONAL_OR_KEYWORD` and whose default value is *not*
:data:`ArgMandatory`).
* **Variadic positional parameters** (i.e., parameter metadata whose kind
is :attr:`ArgKind.VAR_POSITIONAL` and whose default value is
:data:`ArgMandatory`).
* **Mandatory and optional keyword-only parameters** (i.e., parameter
metadata whose kind is :attr:`ArgKind.KEYWORD_ONLY`). Unlike all other
parameter kinds, keyword-only parameters are (by definition) unordered;
ergo, Python explicitly permits mandatory and optional keyword-only
parameters to be heterogeneously intermingled rather than clustered.
* **Variadic keyword parameters** (i.e., parameter metadata whose kind
is :attr:`ArgKind.VAR_KEYWORD` and whose default value is
:data:`ArgMandatory`).
Caveats
----------
**This highly optimized generator function should always be called in lieu
of the highly unoptimized** :func:`inspect.signature` **function,** which
implements a similar introspection as this generator with significantly
worse space and time consumption. Seriously. *Never* call that anywhere.
Parameters
----------
func : Callable
Pure-Python callable to be inspected.
func_codeobj: CodeType, optional
Code object underlying that callable unwrapped. Defaults to ``None``,
in which case this iterator internally defers to the comparatively
slower :func:`get_func_codeobj` function.
is_unwrapping: bool, optional
``True`` only if this generator implicitly calls the
:func:`unwrap_func` function to unwrap this possibly higher-level
wrapper into its possibly lowest-level wrappee *before* returning the
code object of that wrappee. Note that doing so incurs worst-case time
complexity ``O(n)`` for ``n`` the number of lower-level wrappees
wrapped by this wrapper. Defaults to ``True`` for robustness. Why?
Because this generator *must* always introspect lowest-level wrappees
rather than higher-level wrappers. The latter typically do *not* wrap
the default values of the former, since this is the default behaviour
of the :func:`functools.update_wrapper` function underlying the
:func:`functools.wrap` decorator underlying all sane decorators. If
this boolean is set to ``False`` while that callable is actually a
wrapper, this generator will erroneously misidentify optional as
mandatory parameters and fail to yield their default values. Only set
this boolean to ``False`` if you pretend to know what you're doing.
Yields
----------
ArgMeta
Parameter metadata tuple describing the currently yielded parameter.
Raises
----------
:exc:`_BeartypeUtilCallableException`
If that callable is *not* pure-Python.
'''
# ..................{ LOCALS ~ noop }..................
# If unwrapping that callable, do so *BEFORE* querying that callable for
# its code object to avoid desynchronization between the two.
if is_unwrapping:
func = unwrap_func(func)
# Else, that callable is assumed to have already been unwrapped by the
# caller. We should probably assert that, but doing so requires an
# expensive call to hasattr(). What you gonna do?
# If passed *NO* code object, query that callable for its code object.
if func_codeobj is None:
func_codeobj = get_func_codeobj(func)
# In any case, that code object is now defined.
# Bit field of OR-ed binary flags describing this callable.
func_codeobj_flags = func_codeobj.co_flags
# Number of both optional and mandatory non-keyword-only parameters (i.e.,
# positional-only *AND* flexible (i.e., positional or keyword) parameters)
# accepted by that callable.
args_len_posonly_or_flex = func_codeobj.co_argcount
# Number of both optional and mandatory keyword-only parameters accepted by
# that callable.
args_len_kwonly = func_codeobj.co_kwonlyargcount
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with the is_func_arg_variadic_positional() and
# is_func_arg_variadic_keyword() testers.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# True only if that callable accepts variadic positional or keyword
# parameters. For efficiency, these tests are inlined from the
# is_func_arg_variadic_positional() and is_func_arg_variadic_keyword()
# testers. Yes, this optimization has been profiled to yield joy.
is_arg_var_pos = bool(func_codeobj_flags & CO_VARARGS)
is_arg_var_kw = bool(func_codeobj_flags & CO_VARKEYWORDS)
# print(f'func.__name__ = {func.__name__}\nis_arg_var_pos = {is_arg_var_pos}\nis_arg_var_kw = {is_arg_var_kw}')
# If that callable accepts *NO* parameters, silently reduce to the empty
# generator (i.e., noop) for both space and time efficiency. Just. Do. It.
#
# Note that this is a critical optimization when @beartype is
# unconditionally applied with import hook automation to *ALL* physical
# callables declared by a package, many of which will be argument-less.
if (
args_len_posonly_or_flex +
args_len_kwonly +
is_arg_var_pos +
is_arg_var_kw
) == 0:
yield from ()
return
# Else, that callable accepts one or more parameters.
# ..................{ LOCALS ~ names }..................
# Tuple of the names of all variables localized to that callable.
#
# Note that this tuple contains the names of both:
# * All parameters accepted by that callable.
# * All local variables internally declared in that callable's body.
#
# Ergo, this tuple *CANNOT* be searched in full. Only the subset of this
# tuple containing argument names is relevant and may be safely searched.
#
# Lastly, note the "func_codeobj.co_names" attribute is incorrectly
# documented in the "inspect" module as the "tuple of names of local
# variables." That's a lie. That attribute is instead a mostly useless
# tuple of the names of both globals and object attributes accessed in the
# body of that callable. *shrug*
args_name = func_codeobj.co_varnames
# ..................{ LOCALS ~ defaults }..................
# Tuple of the default values assigned to all optional non-keyword-only
# parameters (i.e., all optional positional-only *AND* optional flexible
# (i.e., positional or keyword) parameters) accepted by that callable if
# any *OR* the empty tuple otherwise.
args_defaults_posonly_or_flex = func.__defaults__ or () # type: ignore[attr-defined]
# print(f'args_defaults_posonly_or_flex: {args_defaults_posonly_or_flex}')
# Dictionary mapping the name of each optional keyword-only parameter
# accepted by that callable to the default value assigned to that parameter
# if any *OR* the empty dictionary otherwise.
#
# For both space and time efficiency, the empty dictionary is intentionally
# *NOT* accessed here as "{}". Whereas each instantiation of the empty
# tuple efficiently reduces to the same empty tuple, each instantiation of
# the empty dictionary inefficiently creates a new empty dictionary: e.g.,
# >>> () is ()
# True
# >>> {} is {}
# False
args_defaults_kwonly = func.__kwdefaults__ or _ARGS_DEFAULTS_KWONLY_EMPTY # type: ignore[attr-defined]
# ..................{ LOCALS ~ len }..................
# Number of both optional and mandatory positional-only parameters accepted
# by that callable, specified as either...
args_len_posonly = (
# If the active Python interpreter targets Python >= 3.8 and thus
# supports PEP 570 standardizing positional-only parameters, the number
# of these parameters;
func_codeobj.co_posonlyargcount # type: ignore[attr-defined]
if IS_PYTHON_AT_LEAST_3_8 else
# Else, this interpreter targets Python < 3.8 and thus fails to support
# PEP 570. In this case, there are *NO* such parameters.
0
)
assert args_len_posonly_or_flex >= args_len_posonly, (
f'Positional-only and flexible argument count {args_len_posonly_or_flex} < '
f'positional-only argument count {args_len_posonly}.')
# Number of both optional and mandatory flexible parameters accepted by
# that callable.
args_len_flex = args_len_posonly_or_flex - args_len_posonly
# Number of optional non-keyword-only parameters accepted by that callable.
args_len_posonly_or_flex_optional = len(args_defaults_posonly_or_flex)
# Number of optional flexible parameters accepted by that callable, defined
# as the number of optional non-keyword-only parameters capped to the total
# number of flexible parameters. Why? Because optional flexible parameters
# preferentially consume non-keyword-only default values first; optional
# positional-only parameters consume all remaining non-keyword-only default
# values. Why? Because:
# * Default values are *ALWAYS* assigned to positional parameters from
# right-to-left.
# * Flexible parameters reside to the right of positional-only parameters.
#
# Specifically, this number is defined as...
args_len_flex_optional = min(
# If the number of optional non-keyword-only parameters exceeds the
# total number of flexible parameters, the total number of flexible
# parameters. For obvious reasons, the number of optional flexible
# parameters *CANNOT* exceed the total number of flexible parameters;
args_len_flex,
# Else, the total number of flexible parameters is strictly greater
# than the number of optional non-keyword-only parameters, implying
# optional flexible parameters consume all non-keyword-only default
# values. In this case, the number of optional flexible parameters is
# the number of optional non-keyword-only parameters.
args_len_posonly_or_flex_optional,
)
# Number of optional positional-only parameters accepted by that callable,
# defined as all remaining optional non-keyword-only parameters *NOT*
# already consumed by positional parameters. Note that this number is
# guaranteed to be non-negative. Why? Because, it is the case that either:
# * "args_len_posonly_or_flex_optional >= args_len_flex", in which case
# "args_len_flex_optional == args_len_flex", in which case
# "args_len_posonly_or_flex_optional >= args_len_flex_optional".
# * "args_len_posonly_or_flex_optional < args_len_flex", in which case
# "args_len_flex_optional == args_len_posonly_or_flex_optional", in which
# case "args_len_posonly_or_flex_optional == args_len_flex_optional".
#
# Just roll with it, folks. It's best not to question the unfathomable.
args_len_posonly_optional = (
args_len_posonly_or_flex_optional - args_len_flex_optional)
# Number of mandatory positional-only parameters accepted by that callable.
args_len_posonly_mandatory = args_len_posonly - args_len_posonly_optional
# Number of mandatory flexible parameters accepted by that callable.
args_len_flex_mandatory = args_len_flex - args_len_flex_optional
# ..................{ INTROSPECTION }..................
# 0-based index of the first parameter of the currently iterated kind
# accepted by that callable in the "args_name" tuple.
args_index_kind_first = 0
# If that callable accepts at least one mandatory positional-only
# parameter...
if args_len_posonly_mandatory:
# For each mandatory positional-only parameter accepted by that
# callable, yield a tuple describing this parameter.
for arg_name in args_name[
args_index_kind_first:args_len_posonly_mandatory]:
yield (ArgKind.POSITIONAL_ONLY, arg_name, ArgMandatory,)
# 0-based index of the first parameter of the next iterated kind.
args_index_kind_first = args_len_posonly_mandatory
# If that callable accepts at least one optional positional-only
# parameter...
if args_len_posonly_optional:
# 0-based index of the parameter following the last optional
# positional-only parameter in the "args_name" tuple.
args_index_kind_last_after = (
args_index_kind_first + args_len_posonly_optional)
# For the 0-based index of each optional positional-only parameter
# accepted by that callable and that parameter, yield a tuple
# describing this parameter.
for arg_index, arg_name in enumerate(args_name[
args_index_kind_first:args_index_kind_last_after]):
# assert arg_posonly_optional_index < args_len_posonly_optional, (
# f'Optional positional-only parameter index {arg_posonly_optional_index} >= '
# f'optional positional-only parameter count {args_len_posonly_optional}.')
yield (
ArgKind.POSITIONAL_ONLY,
arg_name,
args_defaults_posonly_or_flex[arg_index],
)
# 0-based index of the first parameter of the next iterated kind.
args_index_kind_first = args_index_kind_last_after
# If that callable accepts at least one mandatory flexible parameter...
if args_len_flex_mandatory:
# 0-based index of the parameter following the last mandatory
# flexible parameter in the "args_name" tuple.
args_index_kind_last_after = (
args_index_kind_first + args_len_flex_mandatory)
# For each mandatory flexible parameter accepted by that callable,
# yield a tuple describing this parameter.
for arg_name in args_name[
args_index_kind_first:args_index_kind_last_after]:
yield (ArgKind.POSITIONAL_OR_KEYWORD, arg_name, ArgMandatory,)
# 0-based index of the first parameter of the next iterated kind.
args_index_kind_first = args_index_kind_last_after
# If that callable accepts at least one optional flexible parameter...
if args_len_flex_optional:
# 0-based index of the parameter following the last optional
# flexible parameter in the "args_name" tuple.
args_index_kind_last_after = (
args_index_kind_first + args_len_flex_optional)
# For the 0-based index of each optional flexible parameter accepted by
# this callable and that parameter, yield a 3-tuple describing this
# parameter.
for arg_index, arg_name in enumerate(args_name[
args_index_kind_first:args_index_kind_last_after]):
# assert arg_flex_optional_index < args_len_flex_optional, (
# f'Optional flexible parameter index {arg_flex_optional_index} >= '
# f'optional flexible parameter count {args_len_flex_optional}.')
yield (
ArgKind.POSITIONAL_OR_KEYWORD,
arg_name,
args_defaults_posonly_or_flex[
args_len_posonly_optional + arg_index],
)
# 0-based index of the first parameter of the next iterated kind.
args_index_kind_first = args_index_kind_last_after
# 0-based index of the parameter following the last keyword-only
# parameter in the "args_name" tuple. This index is required by multiple
# branches below (rather than merely one branch) and thus unconditionally
# computed for all these branches.
args_index_kind_last_after = args_index_kind_first + args_len_kwonly
# If that callable accepts a variadic positional parameter, yield a tuple
# describing this parameter.
#
# Note that:
# * This parameter is intentionally yielded *BEFORE* keyword-only
# parameters to conform with syntactic standards. A variadic positional
# parameter necessarily appears before any keyword-only parameters in the
# signature of that callable.
# * The 0-based index of this parameter in the "args_name" tuple is exactly
# one *AFTER* the last keyword-only parameter in that tuple if any and
# one *BEFORE* the variadic keyword parameter in that tuple if any. This
# idiosyncrasy is entirely the fault of CPython, which grouped the
# two variadic positional and keyword parameters at the end of this list
# despite syntactic constraints on their lexical position.
if is_arg_var_pos:
yield (
ArgKind.VAR_POSITIONAL,
args_name[args_index_kind_last_after],
ArgMandatory,
)
# If that callable accepts at least one keyword-only parameter...
if args_len_kwonly:
# dict.get() method repeatedly called below and thus localized for
# negligible efficiency. Look. Just do this. We needs godspeed.
args_defaults_kwonly_get = args_defaults_kwonly.get
# For each keyword-only parameter accepted by that callable, yield a
# tuple describing this parameter.
for arg_name in args_name[
args_index_kind_first:args_index_kind_last_after]:
yield (
ArgKind.KEYWORD_ONLY,
arg_name,
# Either:
# * If this is an optional keyword-only parameter, the default
# value of this parameter.
# * If this is a mandatory keyword-only parameter, the
# placeholder "ArgMandatory" singleton.
args_defaults_kwonly_get(arg_name, ArgMandatory),
)
# If that callable accepts a variadic keyword parameter...
if is_arg_var_kw:
# 0-based index of the variadic keyword parameter accepted by that
# callable in the "args_name" tuple, optimized by noting that Python
# booleans are literally integers that can be computed with. Notably:
# * If that callable accepts *NO* variadic positional parameter, then:
# is_arg_var_pos == 0
# args_index_var_kw == args_index_var_pos
# * If that callable accepts a variadic positional parameter, then:
# is_arg_var_kw == 1
# args_index_var_pos == args_index_var_pos + 1
args_index_kind_last_after += is_arg_var_pos
# Yield a tuple describing this parameter.
yield (
ArgKind.VAR_KEYWORD,
args_name[args_index_kind_last_after],
ArgMandatory,
)
# ....................{ PRIVATE ~ constants }....................
_ARGS_DEFAULTS_KWONLY_EMPTY: Dict[str, object] = {}
'''
Empty dictionary suitable for use as the default dictionary mapping the name of
each optional keyword-only parameter accepted by a callable to the default
value assigned to that parameter.
'''
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable parameter tester utilities** (i.e., callables
introspectively validating and testing parameters accepted by arbitrary
callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCallableException
from beartype.typing import Dict
from beartype._util.func.utilfunccodeobj import get_func_codeobj
from beartype._data.datatyping import Codeobjable, TypeException
from collections.abc import Callable
from inspect import CO_VARARGS, CO_VARKEYWORDS
# ....................{ VALIDATORS }....................
def die_unless_func_args_len_flexible_equal(
# Mandatory parameters.
func: Codeobjable,
func_args_len_flexible: int,
# Optional parameters.
is_unwrapping: bool = True,
exception_cls: TypeException = _BeartypeUtilCallableException,
) -> None:
'''
Raise an exception unless the passed pure-Python callable accepts the
passed number of **flexible parameters** (i.e., parameters passable as
either positional or keyword arguments).
Parameters
----------
func : Codeobjable
Pure-Python callable, frame, or code object to be inspected.
func_args_len_flexible : int
Number of flexible parameters to validate this callable as accepting.
is_unwrapping: bool, optional
``True`` only if this validator implicitly calls the
:func:`unwrap_func` function to unwrap this possibly higher-level
wrapper into its possibly lowest-level wrappee *before* returning the
code object of that wrappee. Note that doing so incurs worst-case time
complexity ``O(n)`` for ``n`` the number of lower-level wrappees
wrapped by this wrapper. Defaults to ``True`` for robustness. Why?
Because this validator *must* always introspect lowest-level wrappees
rather than higher-level wrappers. The latter typically do *not*
accurately replicate the signatures of the former. In particular,
decorator wrappers typically wrap decorated callables with variadic
positional and keyword parameters (e.g., ``def _decorator_wrapper(*args,
**kwargs)``). Since neither constitutes a flexible parameter, this
validator raises an exception when passed such a wrapper with this
boolean set to ``False``. For this reason, only set this boolean to
``False`` if you pretend to know what you're doing.
exception_cls : type, optional
Type of exception to be raised if this callable is neither a
pure-Python function nor method. Defaults to
:class:`_BeartypeUtilCallableException`.
Raises
----------
:exc:`exception_cls`
If this callable either:
* Is *not* callable.
* Is callable but is *not* pure-Python.
* Is a pure-Python callable accepting either more or less than this
Number of flexible parameters.
'''
assert isinstance(func_args_len_flexible, int)
# Avoid circular import dependencies.
from beartype._util.func.arg.utilfuncargget import (
get_func_args_len_flexible)
# Number of flexible parameters accepted by this callable.
func_args_len_flexible_actual = get_func_args_len_flexible(
func=func,
is_unwrapping=is_unwrapping,
exception_cls=exception_cls,
)
# If this callable accepts more or less than this number of flexible
# parameters, raise an exception.
if func_args_len_flexible_actual != func_args_len_flexible:
assert isinstance(exception_cls, type), (
f'{repr(exception_cls)} not class.')
raise exception_cls(
f'Callable {repr(func)} flexible argument count '
f'{func_args_len_flexible_actual} != {func_args_len_flexible}.'
)
# Else, this callable accepts exactly this number of flexible parameters.
#FIXME: Uncomment as needed.
# def die_unless_func_argless(
# # Mandatory parameters.
# func: Codeobjable,
#
# # Optional parameters.
# func_label: str = 'Callable',
# exception_cls: Type[Exception] = _BeartypeUtilCallableException,
# ) -> None:
# '''
# Raise an exception unless the passed pure-Python callable is
# **argument-less** (i.e., accepts *no* arguments).
#
# Parameters
# ----------
# func : Codeobjable
# Pure-Python callable, frame, or code object to be inspected.
# func_label : str, optional
# Human-readable label describing this callable in exception messages
# raised by this validator. Defaults to ``'Callable'``.
# exception_cls : type, optional
# Type of exception to be raised if this callable is neither a
# pure-Python function nor method. Defaults to
# :class:`_BeartypeUtilCallableException`.
#
# Raises
# ----------
# exception_cls
# If this callable either:
#
# * Is *not* callable.
# * Is callable but is *not* pure-Python.
# * Is a pure-Python callable accepting one or more parameters.
# '''
#
# # If this callable accepts one or more arguments, raise an exception.
# if is_func_argless(
# func=func, func_label=func_label, exception_cls=exception_cls):
# assert isinstance(func_label, str), f'{repr(func_label)} not string.'
# assert isinstance(exception_cls, type), (
# f'{repr(exception_cls)} not class.')
#
# raise exception_cls(
# f'{func_label} {repr(func)} not argument-less '
# f'(i.e., accepts one or more arguments).'
# )
# ....................{ TESTERS ~ kind }....................
def is_func_argless(
# Mandatory parameters.
func: Codeobjable,
# Optional parameters.
exception_cls: TypeException = _BeartypeUtilCallableException,
) -> bool:
'''
``True`` only if the passed pure-Python callable is **argument-less**
(i.e., accepts *no* arguments).
Parameters
----------
func : Codeobjable
Pure-Python callable, frame, or code object to be inspected.
exception_cls : type, optional
Type of exception to be raised in the event of fatal error. Defaults to
:class:`_BeartypeUtilCallableException`.
Returns
----------
bool
``True`` only if the passed callable accepts *no* arguments.
Raises
----------
:exc:`exception_cls`
If the passed callable is *not* pure-Python.
'''
# Code object underlying the passed pure-Python callable unwrapped.
func_codeobj = get_func_codeobj(
func=func, is_unwrapping=True, exception_cls=exception_cls)
# Return true only if this callable accepts neither...
return not (
# One or more non-variadic arguments that are either standard or
# keyword-only *NOR*...
#
# Note that both of the argument counts tested here ignore the
# existence of variadic arguments, which is mildly frustrating... but
# that's the backward-compatible hodgepodge that is the modern code
# object for you.
(func_codeobj.co_argcount + func_codeobj.co_kwonlyargcount > 0) or
# One or more variadic arguments.
is_func_arg_variadic(func_codeobj)
)
# ....................{ TESTERS ~ kind : variadic }....................
def is_func_arg_variadic(func: Codeobjable) -> bool:
'''
``True`` only if the passed pure-Python callable accepts any **variadic
parameters** and thus either variadic positional arguments (e.g.,
"*args") or variadic keyword arguments (e.g., "**kwargs").
Parameters
----------
func : Union[Callable, CodeType, FrameType]
Pure-Python callable, frame, or code object to be inspected.
Returns
----------
bool
``True`` only if the passed callable accepts either:
* Variadic positional arguments (e.g., "*args").
* Variadic keyword arguments (e.g., "**kwargs").
Raises
----------
_BeartypeUtilCallableException
If the passed callable is *not* pure-Python.
'''
# Return true only if this callable declares either...
#
# We can't believe it's this simple, either. But it is.
return (
# Variadic positional arguments *OR*...
is_func_arg_variadic_positional(func) or
# Variadic keyword arguments.
is_func_arg_variadic_keyword(func)
)
def is_func_arg_variadic_positional(func: Codeobjable) -> bool:
'''
``True`` only if the passed pure-Python callable accepts variadic
positional arguments (e.g., "*args").
Parameters
----------
func : Union[Callable, CodeType, FrameType]
Pure-Python callable, frame, or code object to be inspected.
Returns
----------
bool
``True`` only if the passed callable accepts variadic positional
arguments.
Raises
----------
_BeartypeUtilCallableException
If the passed callable is *not* pure-Python.
'''
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with the iter_func_args() iterator.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Code object underlying the passed pure-Python callable unwrapped.
func_codeobj = get_func_codeobj(func=func, is_unwrapping=True)
# Return true only if this callable declares variadic positional arguments.
return func_codeobj.co_flags & CO_VARARGS != 0
def is_func_arg_variadic_keyword(func: Codeobjable) -> bool:
'''
``True`` only if the passed pure-Python callable accepts variadic
keyword arguments (e.g., "**kwargs").
Parameters
----------
func : Union[Callable, CodeType, FrameType]
Pure-Python callable, frame, or code object to be inspected.
Returns
----------
bool
``True`` only if the passed callable accepts variadic keyword
arguments.
Raises
----------
_BeartypeUtilCallableException
If the passed callable is *not* pure-Python.
'''
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# CAUTION: Synchronize with the iter_func_args() iterator.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Code object underlying the passed pure-Python callable unwrapped.
func_codeobj = get_func_codeobj(func=func, is_unwrapping=True)
# Return true only if this callable declares variadic keyword arguments.
return func_codeobj.co_flags & CO_VARKEYWORDS != 0
# ....................{ TESTERS ~ name }....................
#FIXME: *THIS TESTER IS HORRIFYINGLY SLOW*, thanks to a naive implementation
#deferring to the slow iter_func_args() iterator. A substantially faster
#get_func_arg_names() getter should be implemented instead and this tester
#refactored to call that getter. How? Simple:
# def get_func_arg_names(func: Callable) -> Tuple[str]:
# # A trivial algorithm for deciding the number of arguments can be
# # found at the head of the iter_func_args() iterator.
# args_len = ...
#
# # One-liners for great glory.
# return func.__code__.co_varnames[:args_len] # <-- BOOM
def is_func_arg_name(func: Callable, arg_name: str) -> bool:
'''
``True`` only if the passed pure-Python callable accepts an argument with
the passed name.
Caveats
----------
**This tester exhibits worst-case time complexity** ``O(n)`` **for** ``n``
**the total number of arguments accepted by this callable,** due to
unavoidably performing a linear search for an argument with this name is
this callable's argument list. This tester should thus be called sparingly
and certainly *not* repeatedly for the same callable.
Parameters
----------
func : Callable
Pure-Python callable to be inspected.
arg_name : str
Name of the argument to be searched for.
Returns
----------
bool
``True`` only if that callable accepts an argument with this name.
Raises
----------
_BeartypeUtilCallableException
If the passed callable is *not* pure-Python.
'''
assert isinstance(arg_name, str), f'{arg_name} not string.'
# Avoid circular import dependencies.
from beartype._util.func.arg.utilfuncargiter import (
ARG_META_INDEX_NAME,
iter_func_args,
)
# Return true only if...
return any(
# This is the passed name...
arg_meta[ARG_META_INDEX_NAME] == arg_name
# For the name of any parameter accepted by this callable.
for arg_meta in iter_func_args(func)
)
# ....................{ PRIVATE }....................
_ARGS_DEFAULTS_KWONLY_EMPTY: Dict[str, object] = {}
'''
Empty dictionary suitable for use as the default dictionary mapping the name of
each optional keyword-only parameter accepted by a callable to the default
value assigned to that parameter.
'''
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable parameter getter utilities** (i.e., callables
introspectively querying metadata on parameters accepted by arbitrary
callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype.roar._roarexc import _BeartypeUtilCallableException
from beartype._util.func.utilfunccodeobj import get_func_codeobj
from beartype._util.func.utilfuncwrap import unwrap_func
from beartype._data.datatyping import Codeobjable, TypeException
# ....................{ GETTERS }....................
def get_func_args_len_flexible(
# Mandatory parameters.
func: Codeobjable,
# Optional parameters.
is_unwrapping: bool = True,
exception_cls: TypeException = _BeartypeUtilCallableException,
) -> int:
'''
Number of **flexible parameters** (i.e., parameters passable as either
positional or keyword arguments) accepted by the passed pure-Python
callable.
Parameters
----------
func : Codeobjable
Pure-Python callable, frame, or code object to be inspected.
is_unwrapping: bool, optional
``True`` only if this getter implicitly calls the :func:`unwrap_func`
function to unwrap this possibly higher-level wrapper into its possibly
lowest-level wrappee *before* returning the code object of that
wrappee. Note that doing so incurs worst-case time complexity ``O(n)``
for ``n`` the number of lower-level wrappees wrapped by this wrapper.
Defaults to ``True`` for robustness. Why? Because this getter *must*
always introspect lowest-level wrappees rather than higher-level
wrappers. The latter typically do *not* accurately replicate the
signatures of the former. In particular, decorator wrappers typically
wrap decorated callables with variadic positional and keyword
parameters (e.g., ``def _decorator_wrapper(*args, **kwargs)``). Since
neither constitutes a flexible parameter, this getter raises an
exception when passed such a wrapper with this boolean set to
``False``. For this reason, only set this boolean to ``False`` if you
pretend to know what you're doing.
exception_cls : type, optional
Type of exception in the event of a fatal error. Defaults to
:class:`_BeartypeUtilCallableException`.
Returns
----------
int
Number of flexible parameters accepted by this callable.
Raises
----------
:exc:`exception_cls`
If the passed callable is *not* pure-Python.
'''
# If unwrapping that callable, do so *BEFORE* querying that callable for
# its code object to avoid desynchronization between the two.
if is_unwrapping:
func = unwrap_func(func)
# Else, that callable is assumed to have already been unwrapped by the
# caller. We should probably assert that, but doing so requires an
# expensive call to hasattr(). What you gonna do?
# Code object underlying the passed pure-Python callable unwrapped.
func_codeobj = get_func_codeobj(func=func, exception_cls=exception_cls)
# Return the number of flexible parameters accepted by this callable.
return func_codeobj.co_argcount
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **beartype-generated wrapper function utilities** (i.e., callables
specifically applicable to wrapper functions generated by the
:func:`beartype.beartype` decorator for beartype-decorated callables).
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ IMPORTS }....................
from beartype._util.func.pep.utilpep484func import (
is_func_pep484_notypechecked)
from beartype._util.mod.lib.utilsphinx import is_sphinx_autodocing
from collections.abc import Callable
# ....................{ TESTERS }....................
#FIXME: Unit test us up, please.
def is_func_unbeartypeable(func: Callable) -> bool:
'''
``True`` only if the passed callable is **unbeartypeable** (i.e., if the
:func:`beartype.beartype` decorator should preserve that callable as is by
reducing to the identity decorator rather than wrap that callable with
constant-time type-checking).
Parameters
----------
func : Callable
Callable to be inspected.
Returns
----------
bool
``True`` only if that callable is unbeartypeable.
'''
# Return true only if either...
return (
# This callable is unannotated *OR*...
#
# Note that the "__annotations__" dunder attribute is guaranteed to
# exist *ONLY* for standard pure-Python callables. Various other
# callables of interest (e.g., functions exported by the standard
# "operator" module) do *NOT* necessarily declare that attribute. Since
# this tester is commonly called in general-purpose contexts where this
# guarantee does *NOT* necessarily hold, we intentionally access that
# attribute safely albeit somewhat more slowly via getattr().
not getattr(func, '__annotations__', None) or
# This callable is decorated by the @typing.no_type_check decorator
# defining this dunder instance variable on this callable *OR*...
is_func_pep484_notypechecked(func) or
# This callable is a @beartype-specific wrapper previously generated by
# this decorator *OR*...
is_func_beartyped(func) or
# Sphinx is currently autogenerating documentation (i.e., if this
# decorator has been called from a Python call stack invoked by the
# "autodoc" extension bundled with the optional third-party build-time
# "sphinx" package)...
#
# Why? Because of mocking. When @beartype-decorated callables are
# annotated with one more classes mocked by "autodoc_mock_imports",
# @beartype frequently raises exceptions at decoration time. Why?
# Because mocking subverts our assumptions and expectations about
# classes used as annotations.
is_sphinx_autodocing()
)
def is_func_beartyped(func: Callable) -> bool:
'''
``True`` only if the passed callable is a **beartype-generated wrapper
function** (i.e., function dynamically generated by the
:func:`beartype.beartype` decorator for a user-defined callable decorated by
that decorator, wrapping that callable with constant-time type-checking).
Parameters
----------
func : Callable
Callable to be inspected.
Returns
----------
bool
``True`` only if that callable is a beartype-generated wrapper function.
'''
# Return true only if this callable is a @beartype-specific wrapper
# previously generated by this decorator.
return hasattr(func, '__beartype_wrapper')
# ....................{ SETTERS }....................
def set_func_beartyped(func: Callable) -> None:
'''
Declare the passed callable to be a **beartype-generated wrapper function**
(i.e., function dynamically generated by the :func:`beartype.beartype`
decorator for a user-defined callable decorated by that decorator, wrapping
that callable with constant-time type-checking).
Parameters
----------
func : Callable
Callable to be modified.
'''
# Declare this callable to be generated by @beartype, which tests for the
# existence of this attribute above to avoid re-decorating callables
# already decorated by @beartype by efficiently reducing to a noop.
func.__beartype_wrapper = True # type: ignore[attr-defined]
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype validator API.**
This submodule publishes a PEP-compliant hierarchy of subscriptable (indexable)
classes enabling callers to validate the internal structure of arbitrarily
complex scalars, data structures, and third-party objects. Like annotation
objects defined by the :mod:`typing` module (e.g., :attr:`typing.Union`), these
classes dynamically generate PEP-compliant type hints when subscripted
(indexed) and are thus intended to annotate callables and variables. Unlike
annotation objects defined by the :mod:`typing` module, these classes are *not*
explicitly covered by existing PEPs and thus *not* directly usable as
annotations.
Instead, callers are expected to (in order):
#. Annotate callable parameters and returns to be validated with
:pep:`593`-compliant :attr:`typing.Annotated` type hints.
#. Subscript those hints with (in order):
#. The type of those parameters and returns.
#. One or more subscriptions of classes declared by this submodule.
'''
# ....................{ TODO }....................
#FIXME: [FEATURE] Add a new "beartype.vale.IsInline" validator factory,
#elegantly resolving issue #82 and presumably other future issues, too. The
#core idea here is that "beartype.vale.IsInline" will enable callers to
#directly embed arbitrary test code substrings in the bodies of wrapper
#functions dynamically generated by @beartype. The signature resembles:
# beartype.vale.IsInline[code: str, arg_1: object, ..., arg_N: object]
#...where:
#* "arg_1" through "arg_N" are optional arbitrary objects to be made available
# through the corresponding format variables "{arg_1}" through "{arg_N}" in
# the "code" substring. These arguments are the *ONLY* safe means of exposing
# non-builtin objects to the "code" substring.
#* "code" is a mandatory arbitrary test code substring. This substring *MUST*
# contain at least this mandatory format variable:
# * "{obj}", expanding to the current object being validated. Should this
# perhaps be "{pith}" instead for disambiguity? *shrug*
# Additionally, for each optional "arg_{index}" object subscripting this
# "IsInline" factory, this "code" substring *MUST* contain at least one
# corresponding format variable "{arg_{index}}". For example:
# # This is valid.
# IsInline['len({obj}) == len({arg_1})', ['muh', 'list',]]
#
# # This is invalid, because the "['muh', 'list',]" list argument is
# # *NEVER* referenced via "{arg_1}" in this code snippet.
# IsInline['len({obj}) == 2', ['muh', 'list',]]
# Lastly, this substring may additionally contain these optional format
# variables:
# * "{indent}", expanding to the current indentation level. Specifically:
# * Any "code" substring beginning with a newline *MUST* contain one or more
# "{indent}" variables.
# * Any "code" substring *NOT* beginning with a newline must *NOT* contain
# any "{indent}" variables.
#FIXME: As intelligently requested by @Saphyel at #32, add support for
#additional classes support constraints resembling:
#
#* String constraints:
# * Email.
# * Uuid.
# * Choice.
# * Language.
# * Locale.
# * Country.
# * Currency.
#* Comparison constraints
# * IdenticalTo.
# * NotIdenticalTo.
# * LessThan.
# * GreaterThan.
# * Range.
# * DivisibleBy.
#FIXME: Add a new BeartypeValidator.find_cause() method with the same
#signature and docstring as the existing ViolationCause.find_cause()
#method. This new BeartypeValidator.find_cause() method should then be
#called by the "_peperrorannotated" submodule to generate human-readable
#exception messages. Note that this implies that:
#* The BeartypeValidator.__init__() method will need to additionally accept a new
# mandatory "find_cause: Callable[[], Optional[str]]" parameter, which
# that method should then localize to "self.find_cause".
#* Each __class_getitem__() dunder method of each "_BeartypeValidatorFactoryABC" subclass will need
# to additionally define and pass that callable when creating and returning
# its "BeartypeValidator" instance.
#FIXME: *BRILLIANT IDEA.* Holyshitballstime. The idea here is that we can
#leverage all of our existing "beartype.is" infrastructure to dynamically
#synthesize PEP-compliant type hints that would then be implicitly supported by
#any runtime type checker. At present, subscriptions of "Is" (e.g.,
#"Annotated[str, Is[lambda text: bool(text)]]") are only supported by beartype
#itself. Of course, does anyone care? I mean, if you're using a runtime type
#checker, you're probably *ONLY* using beartype. Right? That said, this would
#technically improve portability by allowing users to switch between different
#checkers... except not really, since they'd still have to import beartype
#infrastructure to do so. So, this is probably actually useless.
#
#Nonetheless, the idea itself is trivial. We declare a new
#"beartype.is.Portable" singleton accessed in the same way: e.g.,
# from beartype import beartype
# from beartype.is import Portable
# NonEmptyStringTest = Is[lambda text: bool(text)]
# NonEmptyString = Portable[str, NonEmptyStringTest]
# @beartype
# def munge_it(text: NonEmptyString) -> str: ...
#
#So what's the difference between "typing.Annotated" and "beartype.is.Portable"
#then? Simple. The latter dynamically generates one new PEP 3119-compliant
#metaclass and associated class whenever subscripted. Clearly, this gets
#expensive in both space and time consumption fast -- which is why this won't
#be the default approach. For safety, this new class does *NOT* subclass the
#first subscripted class. Instead:
#* This new metaclass of this new class simply defines an __isinstancecheck__()
# dunder method. For the above example, this would be:
# class NonEmptyStringMetaclass(object):
# def __isinstancecheck__(cls, obj) -> bool:
# return isinstance(obj, str) and NonEmptyStringTest(obj)
#* This new class would then be entirely empty. For the above example, this
# would be:
# class NonEmptyStringClass(object, metaclass=NonEmptyStringMetaclass):
# pass
#
#Well, so much for brilliant. It's slow and big, so it seems doubtful anyone
#would actually do that. Nonetheless, that's food for thought for you.
# ....................{ IMPORTS }....................
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# WARNING: To avoid polluting the public module namespace, external attributes
# should be locally imported at module scope *ONLY* under alternate private
# names (e.g., "from argparse import ArgumentParser as _ArgumentParser" rather
# than merely "from argparse import ArgumentParser").
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
from beartype.vale._is._valeis import _IsFactory
from beartype.vale._is._valeistype import (
_IsInstanceFactory,
_IsSubclassFactory,
)
from beartype.vale._is._valeisobj import _IsAttrFactory
from beartype.vale._is._valeisoper import _IsEqualFactory
# ....................{ SINGLETONS }....................
# Public factory singletons instantiating these private factory classes.
Is = _IsFactory(basename='Is')
IsAttr = _IsAttrFactory(basename='IsAttr')
IsEqual = _IsEqualFactory(basename='IsEqual')
IsInstance = _IsInstanceFactory(basename='IsInstance')
IsSubclass = _IsSubclassFactory(basename='IsSubclass')
# Delete all private factory classes imported above for safety.
del (
_IsFactory,
_IsAttrFactory,
_IsEqualFactory,
_IsInstanceFactory,
_IsSubclassFactory,
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.