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

David Mertz mertz at gnosis.cx
Sat Sep 17 13:57:49 EDT 2016


The fallback you described would be a change in the behavior of some
working programs.  Moreover, it would only affect custom classes where
adding a decorator is an option (even in external code, you can use
`MyThing = total_divmod(library.MyThing)` under this option.

Showing that a recipe for a decorator is of wide use feels like a necessary
step towards any future semantic change in the language to me.

For example, '%' is fairly widely (ab)used for meanings other than modulo.
E.g. string formatting.  Probably not that many classes that respond to '%'
to do something non-modulo simultaneously implement `.__divmod__()` ... but
maybe some use case is not obvious to me.  If those exist, your change
would break that (well, depending whether methods of ancestors are used or
not).

On Sat, Sep 17, 2016 at 10:42 AM, Ethan Furman <ethan at stoneleaf.us> wrote:

> On 09/17/2016 10:34 AM, David Mertz wrote:
>
>> On Sat, Sep 17, 2016 at 3:56 AM, Mark Dickinson wrote:
>>
>>> On Sat, Sep 17, 2016 at 10:01 AM, Spencer Brown 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
>>>
>>
>> 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.
>>
>
> Not at all.  Currently Python will fallback to `not ==` if a class does not
> define `!=`.  Having `//` and `%` fall back to `__divmod__` would not be
> out of place.
>
> --
> ~Ethan~
>
> _______________________________________________
> 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/4e3a7cc7/attachment-0001.html>


More information about the Python-ideas mailing list