Add __trunc__ to ObjectProxy so math.trunc() works transparently#344
Add __trunc__ to ObjectProxy so math.trunc() works transparently#344gaoflow wants to merge 2 commits into
Conversation
ObjectProxy already implements __round__ (so round() works), but was
missing __trunc__, causing math.trunc() to raise TypeError for any
wrapped numeric type:
>>> import wrapt, math
>>> math.trunc(wrapt.ObjectProxy(1.7))
TypeError: type ObjectProxy doesn't define __trunc__ method
In Python 3.11+ math.trunc() looks up __trunc__ via the type (not
instance), so ObjectProxy.__getattr__ forwarding does not help. Add an
explicit __trunc__ that delegates to math.trunc(self.__wrapped__),
mirroring the pattern already used by __round__ / round().
Also add three regression tests covering float, negative float, and
fractions.Fraction wrapped values.
|
The Note though that the change proposed doesn't include C API implementations which if the tests work without, suggests that |
|
Thanks, that makes sense. I updated the PR to cover the full math integral protocol surface:
Verification:
|
Summary
ObjectProxyalready implements__round__(soround()works onproxied numeric objects), but
__trunc__was absent. In Python 3.11+math.trunc()looks up__trunc__via the type, not the instance,so
ObjectProxy.__getattr__forwarding does not help:This is inconsistent:
round(proxy)works viaObjectProxy.__round__math.ceil(proxy)/math.floor(proxy)happen to work via CPython's__float__fallback in those builtinsmath.trunc(proxy)fails with aTypeErrorFix
Add
__trunc__to_ObjectProxyMethods, mirroring the__round__/round()pattern:Three regression tests are included covering
float, negativefloat,and
fractions.Fractionproxied values.Relation to issue #296
Issue #296 listed
__trunc__as a missing method and was closedwithout implementing it. This PR provides a minimal, focused fix with
test coverage.
This pull request was prepared with the assistance of AI, under my direction and review.