Boolean ABC similar to what's provided in the 'numbers' module
The numbers module provides very useful ABC for the 'numeric tower', able to abstract away the differences between python primitives and for example numpy primitives. I could not find any equivalent for Booleans. However numpy defines np.bool too, so being able to have an abstract Boolean class for both python bool and numpy bool would be great. Here is a version that I included in valid8 in the meantime ----------------------- class Boolean(metaclass=ABCMeta): """ An abstract base class for booleans, similar to what is available in numbers see https://docs.python.org/3.5/library/numbers.html """ __slots__ = () @abstractmethod def __bool__(self): """Return a builtin bool instance. Called for bool(self).""" @abstractmethod def __and__(self, other): """self & other""" @abstractmethod def __rand__(self, other): """other & self""" @abstractmethod def __xor__(self, other): """self ^ other""" @abstractmethod def __rxor__(self, other): """other ^ self""" @abstractmethod def __or__(self, other): """self | other""" @abstractmethod def __ror__(self, other): """other | self""" @abstractmethod def __invert__(self): """~self""" # register bool and numpy bool_ as virtual subclasses # so that issubclass(bool, Boolean) = issubclass(np.bool_, Boolean) = True Boolean.register(bool) try: import numpy as np Boolean.register(np.bool_) except ImportError: # silently escape pass --------------------------- If that topic was already discussed and settled in the past, please ignore this thread - apologies for not being able to find it. Best regards Sylvain
On Mon, Feb 12, 2018 at 09:41:04AM +0000, Sylvain MARIE wrote:
The numbers module provides very useful ABC for the 'numeric tower', able to abstract away the differences between python primitives and for example numpy primitives. I could not find any equivalent for Booleans. However numpy defines np.bool too, so being able to have an abstract Boolean class for both python bool and numpy bool would be great.
I don't know anything about numpy bools, but Python built-in bools are numbers, and as such already have an ABC: they are a subclass of int. -- Steve
NumPy np.bool_ is specifically not a subclass of any np.int_. If it we're, there would be an ambiguity between indexing with a Boolean array and an array of ints. Both are meaningful, but they mean different things (mask vs collection of indices). Do we have other examples a Python ABC that exists to accommodate something outside the standard library or builtins? Even if not, NumPy is special... the actual syntax for '@' exists primarily for that library! On Feb 12, 2018 5:51 AM, "Steven D'Aprano" <steve@pearwood.info> wrote: On Mon, Feb 12, 2018 at 09:41:04AM +0000, Sylvain MARIE wrote:
The numbers module provides very useful ABC for the 'numeric tower', able to abstract away the differences between python primitives and for example numpy primitives. I could not find any equivalent for Booleans. However numpy defines np.bool too, so being able to have an abstract Boolean class for both python bool and numpy bool would be great.
I don't know anything about numpy bools, but Python built-in bools are numbers, and as such already have an ABC: they are a subclass of int. -- Steve _______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
On 13 February 2018 at 02:14, David Mertz <mertz@gnosis.cx> wrote:
NumPy np.bool_ is specifically not a subclass of any np.int_. If it we're, there would be an ambiguity between indexing with a Boolean array and an array of ints. Both are meaningful, but they mean different things (mask vs collection of indices).
Do we have other examples a Python ABC that exists to accommodate something outside the standard library or builtins? Even if not, NumPy is special... the actual syntax for '@' exists primarily for that library!
collections.abc.Sequence and collections.abc.Mapping come to mind - the standard library doesn't tend to distinguish between different kinds of subscriptable objects, but it's a distinction some third party libraries and tools want to be able to make reliably. The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer"). Right now, we only define boolean coercion via "__bool__" - there's no mechanism to say "this *is* a boolean value that can be losslessly converted to and from the builtin boolean constants". That isn't a distinction the standard library makes, but it sounds like it's one that NumPy cares about (and NumPy was also the main driver for introducing __index__). Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_). But just for anyone who doesn't know NumPy, here's a quick illustration of what I alluded to: In [1]: import numpy as np In [2]: arr = np.array([7,8,12,33]) In [3]: ndx1 = np.array([0,1,1,0], dtype=int) In [4]: ndx2 = np.array([0,1,1,0], dtype=bool) In [5]: arr[ndx1] Out[5]: array([7, 8, 8, 7]) In [6]: arr[ndx2] Out[6]: array([ 8, 12]) ndx1 and ndx2 are both nice things (and are both often programmatically constructed by operations in NumPy). But indexing using ndx1 gives us an array of the things in the listed *positions* in arr. In this case, we happen to choose two each of the things an index 0 and index 1 in the result. Indexing by ndx2 gives us a filter of only those positions in arr corresponding to 'True's. These are both nice things to be able to do, but if NumPy's True was a special kind of 1, it wouldn't work out unambiguously. However, recent versions of NumPy *have* gotten a bit smarter about recognizing the special type of Python bools, so it's less of a trap than it used to be. Still, contrast these (using actual Python lists for the indexes: In [10]: arr[[False, True, True, False]] Out[10]: array([ 8, 12]) In [11]: arr[[False, True, 1, 0]] Out[11]: array([7, 8, 8, 7]) On Mon, Feb 12, 2018 at 7:50 PM, Nick Coghlan <ncoghlan@gmail.com> wrote:
On 13 February 2018 at 02:14, David Mertz <mertz@gnosis.cx> wrote:
NumPy np.bool_ is specifically not a subclass of any np.int_. If it we're, there would be an ambiguity between indexing with a Boolean array and an array of ints. Both are meaningful, but they mean different things (mask vs collection of indices).
Do we have other examples a Python ABC that exists to accommodate something outside the standard library or builtins? Even if not, NumPy is special... the actual syntax for '@' exists primarily for that library!
collections.abc.Sequence and collections.abc.Mapping come to mind - the standard library doesn't tend to distinguish between different kinds of subscriptable objects, but it's a distinction some third party libraries and tools want to be able to make reliably.
The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer").
Right now, we only define boolean coercion via "__bool__" - there's no mechanism to say "this *is* a boolean value that can be losslessly converted to and from the builtin boolean constants". That isn't a distinction the standard library makes, but it sounds like it's one that NumPy cares about (and NumPy was also the main driver for introducing __index__).
Cheers, Nick.
-- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
-- 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.
The main use case I had in mind was PEP484-based type hinting/checking actually: def my_function(foo: Boolean): pass explicitly states that my_function accepts any Boolean value, whether it is a python bool or a np.bool that would come from a numpy array or pandas dataframe. Note that type hinting is also the use case for which I make extensive use of the types from the ‘numbers’ package, for the same reasons. Sylvain De : Python-ideas [mailto:python-ideas-bounces+sylvain.marie=schneider-electric.com@python.org] De la part de David Mertz Envoyé : mardi 13 février 2018 07:08 À : Nick Coghlan <ncoghlan@gmail.com> Cc : python-ideas <python-ideas@python.org> Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_). But just for anyone who doesn't know NumPy, here's a quick illustration of what I alluded to: In [1]: import numpy as np In [2]: arr = np.array([7,8,12,33]) In [3]: ndx1 = np.array([0,1,1,0], dtype=int) In [4]: ndx2 = np.array([0,1,1,0], dtype=bool) In [5]: arr[ndx1] Out[5]: array([7, 8, 8, 7]) In [6]: arr[ndx2] Out[6]: array([ 8, 12]) ndx1 and ndx2 are both nice things (and are both often programmatically constructed by operations in NumPy). But indexing using ndx1 gives us an array of the things in the listed positions in arr. In this case, we happen to choose two each of the things an index 0 and index 1 in the result. Indexing by ndx2 gives us a filter of only those positions in arr corresponding to 'True's. These are both nice things to be able to do, but if NumPy's True was a special kind of 1, it wouldn't work out unambiguously. However, recent versions of NumPy have gotten a bit smarter about recognizing the special type of Python bools, so it's less of a trap than it used to be. Still, contrast these (using actual Python lists for the indexes: In [10]: arr[[False, True, True, False]] Out[10]: array([ 8, 12]) In [11]: arr[[False, True, 1, 0]] Out[11]: array([7, 8, 8, 7]) On Mon, Feb 12, 2018 at 7:50 PM, Nick Coghlan <ncoghlan@gmail.com<mailto:ncoghlan@gmail.com>> wrote: On 13 February 2018 at 02:14, David Mertz <mertz@gnosis.cx<mailto:mertz@gnosis.cx>> wrote:
NumPy np.bool_ is specifically not a subclass of any np.int_. If it we're, there would be an ambiguity between indexing with a Boolean array and an array of ints. Both are meaningful, but they mean different things (mask vs collection of indices).
Do we have other examples a Python ABC that exists to accommodate something outside the standard library or builtins? Even if not, NumPy is special... the actual syntax for '@' exists primarily for that library!
collections.abc.Sequence and collections.abc.Mapping come to mind - the standard library doesn't tend to distinguish between different kinds of subscriptable objects, but it's a distinction some third party libraries and tools want to be able to make reliably. The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer"). Right now, we only define boolean coercion via "__bool__" - there's no mechanism to say "this *is* a boolean value that can be losslessly converted to and from the builtin boolean constants". That isn't a distinction the standard library makes, but it sounds like it's one that NumPy cares about (and NumPy was also the main driver for introducing __index__). Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com<mailto:ncoghlan@gmail.com> | Brisbane, Australia -- 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. ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
I am mystified how you can be using the numbers package with mypy. Example: import numbers def f(a: numbers.Integral, b: numbers.Integral) -> numbers.Integral: return a + b f(12, 12) This gives an two errors on the last line when checked by mypy: _.py:10: error: Argument 1 to "f" has incompatible type "int"; expected "Integral" _.py:10: error: Argument 2 to "f" has incompatible type "int"; expected "Integral" On Tue, Feb 13, 2018 at 1:21 AM, Sylvain MARIE < sylvain.marie@schneider-electric.com> wrote:
The main use case I had in mind was PEP484-based type hinting/checking actually:
def my_function(foo: Boolean):
pass
explicitly states that my_function accepts any Boolean value, whether it is a python bool or a np.bool that would come from a numpy array or pandas dataframe.
Note that type hinting is also the use case for which I make extensive use of the types from the ‘numbers’ package, for the same reasons.
Sylvain
*De :* Python-ideas [mailto:python-ideas-bounces+sylvain.marie=schneider- electric.com@python.org] *De la part de* David Mertz *Envoyé :* mardi 13 février 2018 07:08 *À :* Nick Coghlan <ncoghlan@gmail.com> *Cc :* python-ideas <python-ideas@python.org> *Objet :* Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module
I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_).
But just for anyone who doesn't know NumPy, here's a quick illustration of what I alluded to:
In [1]: import numpy as np
In [2]: arr = np.array([7,8,12,33])
In [3]: ndx1 = np.array([0,1,1,0], dtype=int)
In [4]: ndx2 = np.array([0,1,1,0], dtype=bool)
In [5]: arr[ndx1]
Out[5]: array([7, 8, 8, 7])
In [6]: arr[ndx2]
Out[6]: array([ 8, 12])
ndx1 and ndx2 are both nice things (and are both often programmatically constructed by operations in NumPy). But indexing using ndx1 gives us an array of the things in the listed *positions* in arr. In this case, we happen to choose two each of the things an index 0 and index 1 in the result.
Indexing by ndx2 gives us a filter of only those positions in arr corresponding to 'True's. These are both nice things to be able to do, but if NumPy's True was a special kind of 1, it wouldn't work out unambiguously. However, recent versions of NumPy *have* gotten a bit smarter about recognizing the special type of Python bools, so it's less of a trap than it used to be. Still, contrast these (using actual Python lists for the indexes:
In [10]: arr[[False, True, True, False]]
Out[10]: array([ 8, 12])
In [11]: arr[[False, True, 1, 0]]
Out[11]: array([7, 8, 8, 7])
On Mon, Feb 12, 2018 at 7:50 PM, Nick Coghlan <ncoghlan@gmail.com> wrote:
On 13 February 2018 at 02:14, David Mertz <mertz@gnosis.cx> wrote:
NumPy np.bool_ is specifically not a subclass of any np.int_. If it we're, there would be an ambiguity between indexing with a Boolean array and an array of ints. Both are meaningful, but they mean different things (mask vs collection of indices).
Do we have other examples a Python ABC that exists to accommodate something outside the standard library or builtins? Even if not, NumPy is special... the actual syntax for '@' exists primarily for that library!
collections.abc.Sequence and collections.abc.Mapping come to mind - the standard library doesn't tend to distinguish between different kinds of subscriptable objects, but it's a distinction some third party libraries and tools want to be able to make reliably.
The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer").
Right now, we only define boolean coercion via "__bool__" - there's no mechanism to say "this *is* a boolean value that can be losslessly converted to and from the builtin boolean constants". That isn't a distinction the standard library makes, but it sounds like it's one that NumPy cares about (and NumPy was also the main driver for introducing __index__).
Cheers, Nick.
-- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
--
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.
______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
-- --Guido van Rossum (python.org/~guido)
I see :) This does not seem to happen with PyCharm IDE + Anaconda distribution. Is PyCharm relying on MyPy under the hood ? I actually have no knowledge at all about MyPy and how it relates to PyCharm static code analysis warnings. I’m pretty sure though that the runtime checkers (enforce, pytypes) are not dependent on MyPy. Sylvain De : gvanrossum@gmail.com [mailto:gvanrossum@gmail.com] De la part de Guido van Rossum Envoyé : mercredi 14 février 2018 19:47 À : Sylvain MARIE <sylvain.marie@schneider-electric.com> Cc : python-ideas <python-ideas@python.org> Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module I am mystified how you can be using the numbers package with mypy. Example: import numbers def f(a: numbers.Integral, b: numbers.Integral) -> numbers.Integral: return a + b f(12, 12) This gives an two errors on the last line when checked by mypy: _.py:10: error: Argument 1 to "f" has incompatible type "int"; expected "Integral" _.py:10: error: Argument 2 to "f" has incompatible type "int"; expected "Integral" On Tue, Feb 13, 2018 at 1:21 AM, Sylvain MARIE <sylvain.marie@schneider-electric.com<mailto:sylvain.marie@schneider-electric.com>> wrote: The main use case I had in mind was PEP484-based type hinting/checking actually: def my_function(foo: Boolean): pass explicitly states that my_function accepts any Boolean value, whether it is a python bool or a np.bool that would come from a numpy array or pandas dataframe. Note that type hinting is also the use case for which I make extensive use of the types from the ‘numbers’ package, for the same reasons. Sylvain De : Python-ideas [mailto:python-ideas-bounces+sylvain.marie<mailto:python-ideas-bounces%2Bsylvain.marie>=schneider-electric.com@python.org<mailto:schneider-electric.com@python.org>] De la part de David Mertz Envoyé : mardi 13 février 2018 07:08 À : Nick Coghlan <ncoghlan@gmail.com<mailto:ncoghlan@gmail.com>> Cc : python-ideas <python-ideas@python.org<mailto:python-ideas@python.org>> Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_). But just for anyone who doesn't know NumPy, here's a quick illustration of what I alluded to: In [1]: import numpy as np In [2]: arr = np.array([7,8,12,33]) In [3]: ndx1 = np.array([0,1,1,0], dtype=int) In [4]: ndx2 = np.array([0,1,1,0], dtype=bool) In [5]: arr[ndx1] Out[5]: array([7, 8, 8, 7]) In [6]: arr[ndx2] Out[6]: array([ 8, 12]) ndx1 and ndx2 are both nice things (and are both often programmatically constructed by operations in NumPy). But indexing using ndx1 gives us an array of the things in the listed positions in arr. In this case, we happen to choose two each of the things an index 0 and index 1 in the result. Indexing by ndx2 gives us a filter of only those positions in arr corresponding to 'True's. These are both nice things to be able to do, but if NumPy's True was a special kind of 1, it wouldn't work out unambiguously. However, recent versions of NumPy have gotten a bit smarter about recognizing the special type of Python bools, so it's less of a trap than it used to be. Still, contrast these (using actual Python lists for the indexes: In [10]: arr[[False, True, True, False]] Out[10]: array([ 8, 12]) In [11]: arr[[False, True, 1, 0]] Out[11]: array([7, 8, 8, 7]) On Mon, Feb 12, 2018 at 7:50 PM, Nick Coghlan <ncoghlan@gmail.com<mailto:ncoghlan@gmail.com>> wrote: On 13 February 2018 at 02:14, David Mertz <mertz@gnosis.cx<mailto:mertz@gnosis.cx>> wrote:
NumPy np.bool_ is specifically not a subclass of any np.int_. If it we're, there would be an ambiguity between indexing with a Boolean array and an array of ints. Both are meaningful, but they mean different things (mask vs collection of indices).
Do we have other examples a Python ABC that exists to accommodate something outside the standard library or builtins? Even if not, NumPy is special... the actual syntax for '@' exists primarily for that library!
collections.abc.Sequence and collections.abc.Mapping come to mind - the standard library doesn't tend to distinguish between different kinds of subscriptable objects, but it's a distinction some third party libraries and tools want to be able to make reliably. The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer"). Right now, we only define boolean coercion via "__bool__" - there's no mechanism to say "this *is* a boolean value that can be losslessly converted to and from the builtin boolean constants". That isn't a distinction the standard library makes, but it sounds like it's one that NumPy cares about (and NumPy was also the main driver for introducing __index__). Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com<mailto:ncoghlan@gmail.com> | Brisbane, Australia -- 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. ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________ _______________________________________________ Python-ideas mailing list Python-ideas@python.org<mailto:Python-ideas@python.org> https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/ -- --Guido van Rossum (python.org/~guido<http://python.org/~guido>) ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
No, PyCharm has its own annotation checker, which is much more lenient than mypy (and less compliant with PEP 484). And indeed the runtime checkers are also unrelated (though a runtime checker will have to work with the type objects created by typing.py). So as long as you are not expecting to ever need mypy you should be fine -- however if you're sharing code at some point someone is probably going to want to point mypy at it. On Wed, Feb 14, 2018 at 2:36 PM, Sylvain MARIE < sylvain.marie@schneider-electric.com> wrote:
I see :)
This does not seem to happen with PyCharm IDE + Anaconda distribution. Is PyCharm relying on MyPy under the hood ?
I actually have no knowledge at all about MyPy and how it relates to PyCharm static code analysis warnings. I’m pretty sure though that the runtime checkers (enforce, pytypes) are not dependent on MyPy.
Sylvain
*De :* gvanrossum@gmail.com [mailto:gvanrossum@gmail.com] *De la part de* Guido van Rossum *Envoyé :* mercredi 14 février 2018 19:47 *À :* Sylvain MARIE <sylvain.marie@schneider-electric.com>
*Cc :* python-ideas <python-ideas@python.org> *Objet :* Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module
I am mystified how you can be using the numbers package with mypy. Example:
import numbers def f(a: numbers.Integral, b: numbers.Integral) -> numbers.Integral: return a + b f(12, 12)
This gives an two errors on the last line when checked by mypy:
_.py:10: error: Argument 1 to "f" has incompatible type "int"; expected "Integral" _.py:10: error: Argument 2 to "f" has incompatible type "int"; expected "Integral"
On Tue, Feb 13, 2018 at 1:21 AM, Sylvain MARIE <sylvain.marie@schneider- electric.com> wrote:
The main use case I had in mind was PEP484-based type hinting/checking actually:
def my_function(foo: Boolean):
pass
explicitly states that my_function accepts any Boolean value, whether it is a python bool or a np.bool that would come from a numpy array or pandas dataframe.
Note that type hinting is also the use case for which I make extensive use of the types from the ‘numbers’ package, for the same reasons.
Sylvain
*De :* Python-ideas [mailto:python-ideas-bounces+sylvain.marie=schneider- electric.com@python.org] *De la part de* David Mertz *Envoyé :* mardi 13 février 2018 07:08 *À :* Nick Coghlan <ncoghlan@gmail.com> *Cc :* python-ideas <python-ideas@python.org> *Objet :* Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module
I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_).
But just for anyone who doesn't know NumPy, here's a quick illustration of what I alluded to:
In [1]: import numpy as np
In [2]: arr = np.array([7,8,12,33])
In [3]: ndx1 = np.array([0,1,1,0], dtype=int)
In [4]: ndx2 = np.array([0,1,1,0], dtype=bool)
In [5]: arr[ndx1]
Out[5]: array([7, 8, 8, 7])
In [6]: arr[ndx2]
Out[6]: array([ 8, 12])
ndx1 and ndx2 are both nice things (and are both often programmatically constructed by operations in NumPy). But indexing using ndx1 gives us an array of the things in the listed *positions* in arr. In this case, we happen to choose two each of the things an index 0 and index 1 in the result.
Indexing by ndx2 gives us a filter of only those positions in arr corresponding to 'True's. These are both nice things to be able to do, but if NumPy's True was a special kind of 1, it wouldn't work out unambiguously. However, recent versions of NumPy *have* gotten a bit smarter about recognizing the special type of Python bools, so it's less of a trap than it used to be. Still, contrast these (using actual Python lists for the indexes:
In [10]: arr[[False, True, True, False]]
Out[10]: array([ 8, 12])
In [11]: arr[[False, True, 1, 0]]
Out[11]: array([7, 8, 8, 7])
On Mon, Feb 12, 2018 at 7:50 PM, Nick Coghlan <ncoghlan@gmail.com> wrote:
On 13 February 2018 at 02:14, David Mertz <mertz@gnosis.cx> wrote:
NumPy np.bool_ is specifically not a subclass of any np.int_. If it we're, there would be an ambiguity between indexing with a Boolean array and an array of ints. Both are meaningful, but they mean different things (mask vs collection of indices).
Do we have other examples a Python ABC that exists to accommodate something outside the standard library or builtins? Even if not, NumPy is special... the actual syntax for '@' exists primarily for that library!
collections.abc.Sequence and collections.abc.Mapping come to mind - the standard library doesn't tend to distinguish between different kinds of subscriptable objects, but it's a distinction some third party libraries and tools want to be able to make reliably.
The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer").
Right now, we only define boolean coercion via "__bool__" - there's no mechanism to say "this *is* a boolean value that can be losslessly converted to and from the builtin boolean constants". That isn't a distinction the standard library makes, but it sounds like it's one that NumPy cares about (and NumPy was also the main driver for introducing __index__).
Cheers, Nick.
-- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
--
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.
______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
--
--Guido van Rossum (python.org/~guido)
______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
-- --Guido van Rossum (python.org/~guido)
So as long as you are not expecting to ever need mypy you should be fine -- however if you're sharing code at some point someone is probably going to want to point mypy at it.
mypy isn’t an “official” tool, but PEP484 is — and mypy is more or less a reference implimentation, yes? mypy support bool, as far as I can tell, will that not work for your case? Even though the python bools are integer subclasses, that doesn’t mean a type checker shouldn’t flag passing an integer in to a function that expects a bool. -CHB
On Wed, Feb 14, 2018 at 5:49 PM, Chris Barker - NOAA Federal < chris.barker@noaa.gov> wrote:
So as long as you are not expecting to ever need mypy you should be fine
-- however if you're sharing code at some point someone is probably going to want to point mypy at it.
mypy isn’t an “official” tool, but PEP484 is — and mypy is more or less a reference implimentation, yes?
Except PEP 484 is silent on many, many details. So far from all of mypy's behavior is normative. However, in this case PEP 484 has an opinion on the numbers module (don't use it, just use int).
mypy support bool, as far as I can tell, will that not work for your case?
Even though the python bools are integer subclasses, that doesn’t mean a type checker shouldn’t flag passing an integer in to a function that expects a bool.
That's not the issue. The issue is that, from mypy's POV, np.bool is not a subtype of builtins.bool, just like the various np.intXX types aren't subtypes of builtins.int. But IMO the solution is to lie about this in the stubs and make the np types subtypes of the builtin types, not to switch to numbers.Integral. And the reason is that few people (outside hardcore np fans) will want to write numbers.Integral instead of int. -- --Guido van Rossum (python.org/~guido)
On Mon, Feb 12, 2018 at 10:07 PM, David Mertz <mertz@gnosis.cx> wrote:
I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_).
But is an ABC the way to do it? Personally, I'm skeptical that ABCs are a solution to, well, anything (as apposed to duck typing and EAFTP). Take Nick's example: """ The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer"). """ I suppose we could have had an Index ABC -- but that seems painful to me. so maybe we could use a __true_bool__ special method? (and an operator.true_bool() function ???) (this all makes me wish that python bools were more pure -- but way to late for that!) I guess it comes down to whether you want to: - Ask the question: "is this object a boolean?" or - Make this object a boolean __index__ (and operator.index()) is essentially the later -- you want to make an index out of whatever object you have, if you can do so. -CHB -- Christopher Barker, Ph.D. Oceanographer Emergency Response Division NOAA/NOS/OR&R (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker@noaa.gov
My point is just that today, I use the ‘numbers’ package classes (Integral, Real, …) for PEP484 type-hinting, and I find it quite useful in term of input type validation (in combination with PEP484-compliant type checkers, whether static or dynamic). Adding a Boolean ABC with a similar behavior would certainly add consistency to that ‘numbers’ package – only for users who already find it useful, of course. Note that my use case is not about converting an object to a Boolean, I’m just speaking about type validation of a ‘true’ boolean object, for example to be received as a function argument for a flag option. This is for example for users who want to define strongly-typed APIs for interaction with the ‘outside world’, and keep using duck-typing for internals. Sylvain De : Python-ideas [mailto:python-ideas-bounces+sylvain.marie=schneider-electric.com@python.org] De la part de Chris Barker Envoyé : mardi 13 février 2018 21:12 À : David Mertz <mertz@gnosis.cx> Cc : python-ideas <python-ideas@python.org> Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module On Mon, Feb 12, 2018 at 10:07 PM, David Mertz <mertz@gnosis.cx<mailto:mertz@gnosis.cx>> wrote: I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_). But is an ABC the way to do it? Personally, I'm skeptical that ABCs are a solution to, well, anything (as apposed to duck typing and EAFTP). Take Nick's example: """ The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer"). """ I suppose we could have had an Index ABC -- but that seems painful to me. so maybe we could use a __true_bool__ special method? (and an operator.true_bool() function ???) (this all makes me wish that python bools were more pure -- but way to late for that!) I guess it comes down to whether you want to: - Ask the question: "is this object a boolean?" or - Make this object a boolean __index__ (and operator.index()) is essentially the later -- you want to make an index out of whatever object you have, if you can do so. -CHB -- Christopher Barker, Ph.D. Oceanographer Emergency Response Division NOAA/NOS/OR&R (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker@noaa.gov<mailto:Chris.Barker@noaa.gov> ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
Can you show some sample code that you have written that shows where this would be useful? Note that using the numbers package actually makes static type checking through e.g. mypy difficult. So I presume you are talking about dynamic checking? --Guido On Feb 14, 2018 12:42 AM, "Sylvain MARIE" < sylvain.marie@schneider-electric.com> wrote: My point is just that today, I use the ‘numbers’ package classes (Integral, Real, …) for PEP484 type-hinting, and I find it quite useful in term of input type validation (in combination with PEP484-compliant type checkers, whether static or dynamic). Adding a Boolean ABC with a similar behavior would certainly add consistency to that ‘numbers’ package – only for users who already find it useful, of course. Note that my use case is not about converting an object to a Boolean, I’m just speaking about type validation of a ‘true’ boolean object, for example to be received as a function argument for a flag option. This is for example for users who want to define strongly-typed APIs for interaction with the ‘outside world’, and keep using duck-typing for internals. Sylvain *De :* Python-ideas [mailto:python-ideas-bounces+sylvain.marie=schneider- electric.com@python.org] *De la part de* Chris Barker *Envoyé :* mardi 13 février 2018 21:12 *À :* David Mertz <mertz@gnosis.cx> *Cc :* python-ideas <python-ideas@python.org> *Objet :* Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module On Mon, Feb 12, 2018 at 10:07 PM, David Mertz <mertz@gnosis.cx> wrote: I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_). But is an ABC the way to do it? Personally, I'm skeptical that ABCs are a solution to, well, anything (as apposed to duck typing and EAFTP). Take Nick's example: """ The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer"). """ I suppose we could have had an Index ABC -- but that seems painful to me. so maybe we could use a __true_bool__ special method? (and an operator.true_bool() function ???) (this all makes me wish that python bools were more pure -- but way to late for that!) I guess it comes down to whether you want to: - Ask the question: "is this object a boolean?" or - Make this object a boolean __index__ (and operator.index()) is essentially the later -- you want to make an index out of whatever object you have, if you can do so. -CHB -- Christopher Barker, Ph.D. Oceanographer Emergency Response Division NOAA/NOS/OR&R (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker@noaa.gov ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________ _______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
Yes, this is used in combination dynamic type checking, currently using enforce (https://github.com/RussBaz/enforce ) but I know that others exist (pytypes in particular) As per examples…all utility functions that we write that are receiving a number or a boolean in their parameters are now written using the numbers and additional Boolean classes: ------------- example where Integral is used instead of int ----------------- from numbers import Integral import pandas as pd from enforce import runtime_validation, config config(dict(mode='covariant')) # type validation will accept subclasses too @runtime_validation def only_keep_events_lasting_at_least(boolean_series: pd.Series, min_nb_occurrences: Integral): """ Filters boolean flags to keep 'true' only when it appears at least min_nb_occurrences times in a row :param boolean_series: :param min_nb_occurrences: :return: """ (contents skipped for clarity) ------------------------------------- Similarly when a bool type hint is in the signature we try to replace it with a Boolean, so that people can call it with a numpy bool. But maybe that’s too much of type checking for the python philosophy ? I’m wondering if we’re going too far here… Anyway, again, my point is just about consistency: if this is available for numbers, why not for simple Booleans? Sylvain De : Guido van Rossum [mailto:gvanrossum@gmail.com] Envoyé : mercredi 14 février 2018 17:14 À : Sylvain MARIE <sylvain.marie@schneider-electric.com> Cc : Python-Ideas <python-ideas@python.org> Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module Can you show some sample code that you have written that shows where this would be useful? Note that using the numbers package actually makes static type checking through e.g. mypy difficult. So I presume you are talking about dynamic checking? --Guido On Feb 14, 2018 12:42 AM, "Sylvain MARIE" <sylvain.marie@schneider-electric.com<mailto:sylvain.marie@schneider-electric.com>> wrote: My point is just that today, I use the ‘numbers’ package classes (Integral, Real, …) for PEP484 type-hinting, and I find it quite useful in term of input type validation (in combination with PEP484-compliant type checkers, whether static or dynamic). Adding a Boolean ABC with a similar behavior would certainly add consistency to that ‘numbers’ package – only for users who already find it useful, of course. Note that my use case is not about converting an object to a Boolean, I’m just speaking about type validation of a ‘true’ boolean object, for example to be received as a function argument for a flag option. This is for example for users who want to define strongly-typed APIs for interaction with the ‘outside world’, and keep using duck-typing for internals. Sylvain De : Python-ideas [mailto:python-ideas-bounces+sylvain.marie<mailto:python-ideas-bounces%2Bsylvain.marie>=schneider-electric.com@python.org<mailto:schneider-electric.com@python.org>] De la part de Chris Barker Envoyé : mardi 13 février 2018 21:12 À : David Mertz <mertz@gnosis.cx<mailto:mertz@gnosis.cx>> Cc : python-ideas <python-ideas@python.org<mailto:python-ideas@python.org>> Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module On Mon, Feb 12, 2018 at 10:07 PM, David Mertz <mertz@gnosis.cx<mailto:mertz@gnosis.cx>> wrote: I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_). But is an ABC the way to do it? Personally, I'm skeptical that ABCs are a solution to, well, anything (as apposed to duck typing and EAFTP). Take Nick's example: """ The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer"). """ I suppose we could have had an Index ABC -- but that seems painful to me. so maybe we could use a __true_bool__ special method? (and an operator.true_bool() function ???) (this all makes me wish that python bools were more pure -- but way to late for that!) I guess it comes down to whether you want to: - Ask the question: "is this object a boolean?" or - Make this object a boolean __index__ (and operator.index()) is essentially the later -- you want to make an index out of whatever object you have, if you can do so. -CHB -- Christopher Barker, Ph.D. Oceanographer Emergency Response Division NOAA/NOS/OR&R (206) 526-6959<tel:(206)%20526-6959> voice 7600 Sand Point Way NE (206) 526-6329<tel:(206)%20526-6329> fax Seattle, WA 98115 (206) 526-6317<tel:(206)%20526-6317> main reception Chris.Barker@noaa.gov<mailto:Chris.Barker@noaa.gov> ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________ _______________________________________________ Python-ideas mailing list Python-ideas@python.org<mailto:Python-ideas@python.org> https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/ ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
A thought just occurred to me. Maybe we should just add a Boolean class to numbers? It's a subclass of Integral, presumably. And normally only builtins.bool is registered with it. But np.bool can be added at the same point you register the other np integral types. On Wed, Feb 14, 2018 at 10:23 AM, Sylvain MARIE < sylvain.marie@schneider-electric.com> wrote:
Yes, this is used in combination dynamic type checking, currently using enforce (https://github.com/RussBaz/enforce ) but I know that others exist (pytypes in particular)
As per examples…all utility functions that we write that are receiving a number or a boolean in their parameters are now written using the numbers and additional Boolean classes:
------------- example where Integral is used instead of int -----------------
*from *numbers *import *Integral
*import *pandas *as *pd
*from *enforce *import *runtime_validation, config config(dict(mode=*'covariant'*))
*# type validation will accept subclasses too *@runtime_validation *def *only_keep_events_lasting_at_least(boolean_series: pd.Series, min_nb_occurrences: Integral):
*""" Filters boolean flags to keep 'true' only when it appears at least min_nb_occurrences times in a row **:param* * boolean_series: **:param* * min_nb_occurrences: **:return* *: """*
(contents skipped for clarity)
-------------------------------------
Similarly when a bool type hint is in the signature we try to replace it with a Boolean, so that people can call it with a numpy bool. But maybe that’s too much of type checking for the python philosophy ? I’m wondering if we’re going too far here…
Anyway, again, my point is just about consistency: if this is available for numbers, why not for simple Booleans?
Sylvain
*De :* Guido van Rossum [mailto:gvanrossum@gmail.com] *Envoyé :* mercredi 14 février 2018 17:14 *À :* Sylvain MARIE <sylvain.marie@schneider-electric.com> *Cc :* Python-Ideas <python-ideas@python.org>
*Objet :* Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module
Can you show some sample code that you have written that shows where this would be useful?
Note that using the numbers package actually makes static type checking through e.g. mypy difficult. So I presume you are talking about dynamic checking?
--Guido
On Feb 14, 2018 12:42 AM, "Sylvain MARIE" <sylvain.marie@schneider- electric.com> wrote:
My point is just that today, I use the ‘numbers’ package classes (Integral, Real, …) for PEP484 type-hinting, and I find it quite useful in term of input type validation (in combination with PEP484-compliant type checkers, whether static or dynamic). Adding a Boolean ABC with a similar behavior would certainly add consistency to that ‘numbers’ package – only for users who already find it useful, of course.
Note that my use case is not about converting an object to a Boolean, I’m just speaking about type validation of a ‘true’ boolean object, for example to be received as a function argument for a flag option. This is for example for users who want to define strongly-typed APIs for interaction with the ‘outside world’, and keep using duck-typing for internals.
Sylvain
*De :* Python-ideas [mailto:python-ideas-bounces+sylvain.marie=schneider- electric.com@python.org] *De la part de* Chris Barker *Envoyé :* mardi 13 février 2018 21:12 *À :* David Mertz <mertz@gnosis.cx> *Cc :* python-ideas <python-ideas@python.org> *Objet :* Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module
On Mon, Feb 12, 2018 at 10:07 PM, David Mertz <mertz@gnosis.cx> wrote:
I'm not sure I'm convinced by Sylvain that Boolean needs to be an ABC in the standard library; Guido expresses skepticism. Of course it is possible to define it in some other library that actually needs to use `isinstance(x, Boolean)` as Sylvain demonstraits in his post. I'm not sure I'm unconvinced either, I can see a certain value to saying a given value is "fully round-trippable to bool" (as is np.bool_).
But is an ABC the way to do it? Personally, I'm skeptical that ABCs are a solution to, well, anything (as apposed to duck typing and EAFTP). Take Nick's example:
"""
The other comparison that comes to mind would be the distinction between "__int__" ("can be coerced to an integer, but may lose information in the process") and "__index__" ("can be losslessly converted to and from a builtin integer").
"""
I suppose we could have had an Index ABC -- but that seems painful to me.
so maybe we could use a __true_bool__ special method?
(and an operator.true_bool() function ???)
(this all makes me wish that python bools were more pure -- but way to late for that!)
I guess it comes down to whether you want to:
- Ask the question: "is this object a boolean?"
or
- Make this object a boolean
__index__ (and operator.index()) is essentially the later -- you want to make an index out of whatever object you have, if you can do so.
-CHB
--
Christopher Barker, Ph.D. Oceanographer
Emergency Response Division NOAA/NOS/OR&R (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker@noaa.gov
______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
-- --Guido van Rossum (python.org/~guido)
A thought just occurred to me. Maybe we should just add a Boolean class to numbers?
That would be great indeed
It's a subclass of Integral, presumably. And normally only builtins.bool is registered with it. But np.bool can be added at the same point you register the other np integral types.
I would rather suggest to keep that Boolean ABC class independent of Integral (see proposal in first post) to let it remain 'pure', i.e. represent logical booleans only. However nothing prevents us to register python bool as a virtual subclass of *both* Integral and Boolean - while np.bool would be registered as a virtual subclass of Boolean only. This would reflect quite well the reality - the fact that python bool is both a Boolean and an Integer, while numpy bool is only a Boolean. By the way, is there a reason for the name "Integral" (algebraic theory) instead of "Integer" (computer science) ? Would it be practically feasible to add "Integer" as an alias to "Integral" in the numbers package ? Sylvain -----Message d'origine----- De : Chris Barker - NOAA Federal [mailto:chris.barker@noaa.gov] Envoyé : vendredi 16 février 2018 22:42 À : guido@python.org Cc : Sylvain MARIE <sylvain.marie@schneider-electric.com>; Python-Ideas <python-ideas@python.org> Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module Sent from my iPhone
A thought just occurred to me. Maybe we should just add a Boolean class to numbers?
This makes lots of sense to me. Bool is a subclass of int — might as well embrace that fact. -CHB ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
On Mon, Feb 19, 2018 at 5:58 AM, Sylvain MARIE < sylvain.marie@schneider-electric.com> wrote:
A thought just occurred to me. Maybe we should just add a Boolean class to numbers?
That would be great indeed
It's a subclass of Integral, presumably. And normally only builtins.bool is registered with it. But np.bool can be added at the same point you register the other np integral types.
I would rather suggest to keep that Boolean ABC class independent of Integral (see proposal in first post) to let it remain 'pure', i.e. represent logical booleans only. However nothing prevents us to register python bool as a virtual subclass of *both* Integral and Boolean - while np.bool would be registered as a virtual subclass of Boolean only. This would reflect quite well the reality - the fact that python bool is both a Boolean and an Integer, while numpy bool is only a Boolean.
OK, that could work. At this point I think you should just file an issue on bugs.python.org (but since Python 3.7 is in feature freeze, expect this to be put on the 3.8 track).
By the way, is there a reason for the name "Integral" (algebraic theory) instead of "Integer" (computer science) ? Would it be practically feasible to add "Integer" as an alias to "Integral" in the numbers package ?
Hm, perhaps Integral is an adjective, just like Boolean? Though it's also possible that it was simply a mistake. In general I don't like adding aliases for different spellings -- it violates TOOWTDI. If we decide that this really was a mistake we should go ahead and make Integer the recommended way and define Integral as an alias for backwards compatibility. -- --Guido van Rossum (python.org/~guido)
On 20 February 2018 at 08:33, Guido van Rossum <guido@python.org> wrote:
Hm, perhaps Integral is an adjective, just like Boolean? Though it's also possible that it was simply a mistake. In general I don't like adding aliases for different spellings -- it violates TOOWTDI. If we decide that this really was a mistake we should go ahead and make Integer the recommended way and define Integral as an alias for backwards compatibility.
FWIW, I had to run `dir(numbers)` while tinkering at the REPL based on this discussion, because I was surprised that "numbers.Integer" was giving me an attribute error. Checking PEP 3141 doesn't shed any light on the question either - while that cites Scheme as the origin of the numeric tower structure, the given reference at https://groups.csail.mit.edu/mac/ftpdir/scheme-reports/r5rs-html/r5rs_8.html... uses "integer" rather than "integral". Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
https://bugs.python.org/issue32886 created. Don't hesitate to correct if anything is wrong in the text or associated tags Sylvain -----Message d'origine----- De : Stephen J. Turnbull [mailto:turnbull.stephen.fw@u.tsukuba.ac.jp] Envoyé : mardi 20 février 2018 06:53 À : guido@python.org Cc : Sylvain MARIE <sylvain.marie@schneider-electric.com>; Python-Ideas <python-ideas@python.org> Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module Guido van Rossum writes:
Hm, perhaps Integral is an adjective, just like Boolean?
I would guess so. This is the same idiom we use when we call [1, 2, 3] a "truth-y". ______________________________________________________________________ This email has been scanned by the Symantec Email Security.cloud service. ______________________________________________________________________
Looking at https://en.wikipedia.org/wiki/Number it seems that Integer is "special" -- every other number type is listed as "<adjective> numbers" (e.g. rational numbers, complex numbers) but integers are listed as "Integers". So let's just switch it to that, and keep Integral as an alias for backwards compatibility. I don't think it's a huge problem to fix this in 3.7b2, if someone wants to do the work. On Mon, Feb 19, 2018 at 9:53 PM, Stephen J. Turnbull < turnbull.stephen.fw@u.tsukuba.ac.jp> wrote:
Guido van Rossum writes:
Hm, perhaps Integral is an adjective, just like Boolean?
I would guess so. This is the same idiom we use when we call [1, 2, 3] a "truth-y".
-- --Guido van Rossum (python.org/~guido)
On 2/20/2018 12:06 PM, Guido van Rossum wrote:
Looking at https://en.wikipedia.org/wiki/Number it seems that Integer is "special" -- every other number type is listed as "<adjective> numbers" (e.g. rational numbers, complex numbers) but integers are listed as "Integers". So let's just switch it to that, and keep Integral as an alias for backwards compatibility. I don't think it's a huge problem to fix this in 3.7b2, if someone wants to do the work.
https://bugs.python.org/issue32891 -- Terry Jan Reedy
On Mon, Feb 19, 2018 at 5:58 AM, Sylvain MARIE <sylvain.marie@schneider-electric.com <mailto:sylvain.marie@schneider-electric.com>> wrote:
By the way, is there a reason for the name "Integral" (algebraic theory) instead of "Integer" (computer science) ? Would it be practically feasible to add "Integer" as an alias to "Integral" in the numbers package ?
Possibly inspired by Haskell, which has Integral (a type class, sort of like an abstract type) and also Integer and Int (which are concrete types). -- Greg
15.02.18 18:27, Guido van Rossum пише:
A thought just occurred to me. Maybe we should just add a Boolean class to numbers? It's a subclass of Integral, presumably.
Isn't bool a subclass of int only for historical reasons? I think that if bool was in Python from the beginning, it would not be an int subclass. Operations inherited from int like division or bits shift doesn't make sense as boolean operations. The only boolean operations are testing for truthfulness, `not`, `and` and `or`. But every object in Python supports them. The bool class is just a type of constants True and False.
TBH I've found the numeric tower a questionable addition to Python's stdlib. For PEP 484 we decided not to use it (using the concrete types, int, float etc. instead). So I'm not excited about adding more like this, especially since essentially *everything* can be used in a Boolean context. If your specific project has a specific style requirement for Booleans that would be helped by a Boolean ABC, maybe you should add it to your project and see how it works out, and after a few months report back here. Finally. How were you planning to use this new ABC? On Mon, Feb 12, 2018 at 1:41 AM, Sylvain MARIE < sylvain.marie@schneider-electric.com> wrote:
The numbers module provides very useful ABC for the ‘numeric tower’, able to abstract away the differences between python primitives and for example numpy primitives.
I could not find any equivalent for Booleans.
However numpy defines np.bool too, so being able to have an abstract Boolean class for both python bool and numpy bool would be great.
Here is a version that I included in valid8 in the meantime
-----------------------
class Boolean(metaclass=ABCMeta):
"""
An abstract base class for booleans, similar to what is available in numbers
see https://docs.python.org/3.5/library/numbers.html
"""
__slots__ = ()
@abstractmethod
def __bool__(self):
"""Return a builtin bool instance. Called for bool(self)."""
@abstractmethod
def __and__(self, other):
"""self & other"""
@abstractmethod
def __rand__(self, other):
"""other & self"""
@abstractmethod
def __xor__(self, other):
"""self ^ other"""
@abstractmethod
def __rxor__(self, other):
"""other ^ self"""
@abstractmethod
def __or__(self, other):
"""self | other"""
@abstractmethod
def __ror__(self, other):
"""other | self"""
@abstractmethod
def __invert__(self):
"""~self"""
# register bool and numpy bool_ as virtual subclasses
# so that issubclass(bool, Boolean) = issubclass(np.bool_, Boolean) = True
Boolean.register(bool)
try:
import numpy as np
Boolean.register(np.bool_)
except ImportError:
# silently escape
pass
---------------------------
If that topic was already discussed and settled in the past, please ignore this thread – apologies for not being able to find it.
Best regards
Sylvain
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
-- --Guido van Rossum (python.org/~guido)
participants (12)
-
Chris Barker
-
Chris Barker - NOAA Federal
-
David Mertz
-
Greg Ewing
-
Guido van Rossum
-
Guido van Rossum
-
Nick Coghlan
-
Serhiy Storchaka
-
Stephen J. Turnbull
-
Steven D'Aprano
-
Sylvain MARIE
-
Terry Reedy