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...@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
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.In [1]: import numpy as npIn [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])
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])
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_).
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-e...@python.org]
De la part de Chris Barker
Envoyé : mardi 13 février 2018 21:12
À : David Mertz <me...@gnosis.cx>
Cc : python-ideas <python...@python.org>
Objet : Re: [Python-ideas] Boolean ABC similar to what's provided in the 'numbers' module
______________________________________________________________________
This email has been scanned by the Symantec Email Security.cloud service.
______________________________________________________________________
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-electr...@python.org] De la part de Chris Barker
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-e...@python.org]
De la part de David Mertz
Envoyé : mardi 13 février 2018 07:08
À : Nick Coghlan <ncog...@gmail.com>
Cc : python-ideas <python...@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_).
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-electr...@python.org] De la part de David Mertz
_______________________________________________
Python-ideas mailing list
Python...@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/
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 : gvanr...@gmail.com [mailto:gvanr...@gmail.com]
De la part de Guido van Rossum
Envoyé : mercredi 14 février 2018 19:47
À : Sylvain MARIE <sylvai...@schneider-electric.com>
Cc : python-ideas <python...@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 <sylvai...@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-e...@python.org] De la part de David Mertz
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 : gvanr...@gmail.com [mailto:gvanr...@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...@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-electr...@python.org] De la part de David Mertz
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
>
> 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.
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:gvanr...@gmail.com]
Envoyé : mercredi 14 février 2018 17:14
À : Sylvain MARIE <sylvai...@schneider-electric.com>
Cc : Python-Ideas <python...@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" <sylvai...@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-e...@python.org] De la part de Chris Barker
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:gvanr...@gmail.com]
Envoyé : mercredi 14 février 2018 17:14
À : Sylvain MARIE <sylvain.marie@schneider-electric.com>
Cc : Python-Ideas <python...@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-electr...@python.org] De la part de Chris Barker
This makes lots of sense to me.
Bool is a subclass of int — might as well embrace that fact.
-CHB
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.
> 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 ?
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".