Skip to content

mypy gives error on PEP 484 bound= example #8889

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

Closed
mcolen opened this issue May 26, 2020 · 3 comments
Closed

mypy gives error on PEP 484 bound= example #8889

mcolen opened this issue May 26, 2020 · 3 comments

Comments

@mcolen
Copy link

mcolen commented May 26, 2020

https://www.python.org/dev/peps/pep-0484/#type-variables-with-an-upper-bound

Here is the code example in question. I added some missing imports at the top.

from abc import abstractmethod, ABCMeta
from typing import Any, TypeVar

class Comparable(metaclass=ABCMeta):
    @abstractmethod
    def __lt__(self, other: Any) -> bool: ...
    ...  # __gt__ etc. as well

CT = TypeVar('CT', bound=Comparable)

def min(x: CT, y: CT) -> CT:
    if x < y:
        return x
    else:
        return y

min(1, 2)      # ok, return type int
min('x', 'y')  # ok, return type str

mypy gives me this error:

test.py:17: error: Value of type variable "CT" of "min" cannot be "int"  [type-var]
test.py:18: error: Value of type variable "CT" of "min" cannot be "str"  [type-var]
Found 2 errors in 1 file (checked 1 source file)

Here is the pre-commit configuration I am using to run mypy:

-   repo: https://github.com/pre-commit/mirrors-mypy
    rev: v0.770
    hooks:
    -   id: mypy
        args: [--disallow-untyped-defs, --show-error-codes]

I am on Python 3.7.3.

@russelldavis
Copy link

Not sure about the history of that code in the PEP, but I believe Comparable has to be defined as a Protocol for it to work like that with mypy. For a working implementation, see: python/typing#59 (comment)

@JelleZijlstra
Copy link
Member

Yes, that example seems wrong. We should update the PEP.

@mcolen
Copy link
Author

mcolen commented Jun 1, 2020

I'm going to close this because it is not an issue with mypy. We will update the PEP (python/peps#1419).

@mcolen mcolen closed this as completed Jun 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants