pythonpint

pint: Is wrapping built-in functions with ureg.wraps() impossible?


I'm trying to wrap time.sleep:

from time import sleep
from pint import UnitRegistry

ureg = UnitRegistry()
ureg.wraps(None, ureg.seconds)(sleep)

However, this code throws a ValueError:

Traceback (most recent call last):
  File "demo.py", line 5, in <module>
    ureg.wraps(None, ureg.seconds)(sleep)
  File "[path-to-venv]/lib/python3.8/site-packages/pint/registry_helpers.py", line 258, in decorator
    count_params = len(signature(func).parameters)
  File "/usr/lib/python3.8/inspect.py", line 3105, in signature
    return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  File "/usr/lib/python3.8/inspect.py", line 2854, in from_callable
    return _signature_from_callable(obj, sigcls=cls,
  File "/usr/lib/python3.8/inspect.py", line 2308, in _signature_from_callable
    return _signature_from_builtin(sigcls, obj,
  File "/usr/lib/python3.8/inspect.py", line 2119, in _signature_from_builtin
    raise ValueError("no signature found for builtin {!r}".format(func))
ValueError: no signature found for builtin <built-in function sleep>

Is it not possible to wrap a builtin? Is there a workaround?


Solution

  • There is a workaround: Define your own (non-builtin) function. This can be a simple lambda like this:

    ureg.wraps(None, ureg.seconds)(lambda t: sleep(t))