Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent an implementation for int class from operating on bool values #310

Open
anatoly-scherbakov opened this issue Sep 13, 2021 · 1 comment

Comments

@anatoly-scherbakov
Copy link

Context. Consider the following piece of code.

from classes import typeclass

@typeclass
def render(data_value) -> str:
    """Pretty-print a value."""

@render.instance(int)
def _render_int(data_value: int) -> str:
    return f'🔢 {data_value}'

render(True) == '🔢 True'

(this should be runnable as-is on classes 0.4.0.)

I would have expected this code to fail with a NotImplementedError because the bool case wasn't specified; but instead, that case is handled by the int implementation because

In [3]: issubclass(bool, int)
Out[3]: True

Decision. In an int implementation, recognize if the provided value is actually a bool and refuse to process that value.

Consequences. I have been writing in Python for quite a few years now and I might even have encountered this relationship between int and bool types before, but that is not quite a type of thing that I keep in my short-term memory to be able to instantly recognize.

I believe this change can help avert bugs which might be hard to trace otherwise.

@sobolevn
Copy link
Member

Related python/mypy#8363

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants