On Mon, Mar 9, 2015 at 2:07 AM, Serhiy Storchaka <storch...@gmail.com> wrote:
> On 09.03.15 06:33, Ethan Furman wrote: > >> I guess it could boil down to: if IntEnum was not based on 'int', but >> instead had the __int__ and __index__ methods >> (plus all the other __xxx__ methods that int has), would it still be a >> drop-in replacement for actual ints? Even when >> being used to talk to non-Python libs? >> > > If you don't call isinstance(x, int) (PyLong_Check* in C). > > Most conversions from Python to C implicitly call __index__ or __int__, > but unfortunately not all. > > >>> float(Thin(42)) > 42.0 > >>> float(Wrap(42)) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: float() argument must be a string or a number, not 'Wrap' > > >>> '%*s' % (Thin(5), 'x') > ' x' > >>> '%*s' % (Wrap(5), 'x') > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: * wants int > > >>> OSError(Thin(2), 'No such file or directory') > FileNotFoundError(2, 'No such file or directory') > >>> OSError(Wrap(2), 'No such file or directory') > OSError(<__main__.Wrap object at 0xb6fe81ac>, 'No such file or directory') > > >>> re.match('(x)', 'x').group(Thin(1)) > 'x' > >>> re.match('(x)', 'x').group(Wrap(1)) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > IndexError: no such group > > And to be ideal drop-in replacement IntEnum should override such methods > as __eq__ and __hash__ (so it could be used as mapping key). If all methods > should be overridden to quack as int, why not take an int? > > You're absolutely right that if *all the methods should be overrriden to quack as int, then you should subclass int (the Liskov substitution principle). But all methods should not be overridden — mainly the methods you overrode in your patch should be exposed. Here is a list of methods on int that should not be on IntFlags in my opinion (give or take a couple): __abs__, __add__, __delattr__, __divmod__, __float__, __floor__, __floordiv__, __index__, __lshift__, __mod__, __mul__, __pos__, __pow__, __radd__, __rdivmod__, __rfloordiv__, __rlshift__, __rmod__, __rmul__, __round__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __sub__, __truediv__, __trunc__, conjugate, denominator, imag, numerator, real. I don't think __index__ should be exposed either since are you really going to slice a list using IntFlags? Really? > > > _______________________________________________ > Python-Dev mailing list > Python-Dev@python.org > https://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: https://mail.python.org/mailman/options/python-dev/ > mistersheik%40gmail.com >
_______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com