[Python-ideas] divmod(): fallback to __floordiv__ and __mod__?

David Mertz mertz at gnosis.cx
Sat Sep 17 13:34:29 EDT 2016


It seems like this could be something similar to `functools.total_ordering`
and decorate a class.  In principle that transformation could go in either
direction, but only if the decorator is used.

On Sat, Sep 17, 2016 at 3:56 AM, Mark Dickinson <dickinsm at gmail.com> wrote:

> On Sat, Sep 17, 2016 at 10:01 AM, Spencer Brown <spencerb21 at live.com>
> wrote:
> > Currently, calling divmod() on a class with __floordiv__ and __mod__
> > defined, but not __divmod__ raises a TypeError. Is there any reason why
> it
> > doesn't fallback to (self // x, self % x)?
>
> It's an interesting idea. I wonder whether the falling back shouldn't
> be in the other direction, though: that is, if a class defines
> `__divmod__` but not `__floordiv__` or `__mod__`, perhaps the `//` and
> `%` operations should use `__divmod__`? That way, if you're writing a
> class that intends to support all three operations, you only have to
> write one method. And it might make sense from an efficiency
> perspective, too; it's common for a `divmod` computation to be cheaper
> than doing separate computations of the quotient and remainder.
>
> For the builtin int type, for example, in nontrivial cases Python
> computes both the quotient and remainder when asked to do a % or //
> operation, and then discards whichever part isn't needed. So in that
> case it would be wasteful to build up the divmod result from two
> separate % and // calls.
>
> --
> Mark
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160917/09542d92/attachment.html>


More information about the Python-ideas mailing list