[Feature Request] @beartype option preventing "int" type hints from accepting booleans
See original GitHub issueIt would appear that beartype allows booleans to be passed into an argument when the only allowed type is int. Is there a particular reason why this is allowed, or is this a bug?
I’ve looked through the source but can’t find anything specifically relating to this.
Behaviour can be reproduced as seen below:
@beartype
def find(id: int):
"""."""
print('hello', type(id))
def test_manager():
"""."""
find(False)
A quick check of built-in type checking shows that Python knows the difference between int and bool;
(Pdb) type(1) == int
True
(Pdb) type(1) == bool
False
(Pdb) type(False) == int
False
(Pdb) type(False) == bool
True
According to a discussion on SO, bool
is a subclass of int
for historic reasons. As such, there’s a conflict when using isinstance
, which could be the root cause of this behaviour?
>>> isinstance(True, int)
True
>>> isinstance(True, int)
True
>>> int(True)
1
This historic implementation of bool
could lead to surprising behaviour for unsuspecting developers. It would be nice if there was a way to override type checking behaviour for this specific use case. I’d be open to submitting a PR if such an approach was approved by maintainers.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5 (3 by maintainers)
Top GitHub Comments
Thank you both for taking the time to look at this!
Based on everything said, I would concur that a documentation patch is the most appropriate fix. The showcase snippet you provided gives flexibility to deviate from default behaviour in an explicit manner and solves the specific problem I was having with bool/int.
Despite having strong experience with Python, I was blissfully unaware of this typing behaviour (or the str/seq issue), in fact it was difficult to find any discussion or documentation about it. I’m hoping this thread and documentation patch may also help educate others in future.
ps. On a side note, I’d like to say that this is one of the best responses I’ve seen on a GitHub issue. It’s well thought out, considerate of others and an excellent example of how to be a great maintainer.
Huzzah! I couldn’t help myself. Beartype validators do indeed appear to successfully refine standard type hints for common edge cases like this. Specifically, running the following snippet…
…yields the following output:
This is sufficiently useful that I’ll probably append the above to our existing Validator Showcase. I’m satisfied, folks. How about everyone else?