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

Forbid mixing generics from typing and builtins #1626

Closed
orsinium opened this issue Sep 29, 2020 · 3 comments
Closed

Forbid mixing generics from typing and builtins #1626

orsinium opened this issue Sep 29, 2020 · 3 comments
Labels
rule request Adding a new rule

Comments

@orsinium
Copy link
Collaborator

orsinium commented Sep 29, 2020

Rule request

Thesis

Python 3.9 introduces a new way to create generics which is great:

# before 3.9:
from typing import List, Type
lst: List[int] = [1, 2, 3]
t: Type[int] = float

# from python 3.9:
lst: list[int] = [1, 2, 3]
t: type[int] = float

So, we should be ready that some projects will use the new style. However, this thing should be consistent across the project or at least in one context. In other words, let's forbid mixing list and List in one context.

Good:

def f(a: list, b: list):
   ...

def f(a: List, b: List):
   ...

def f(a: list[str], b: list[str]):
   ...

def f(a: List[str], b: List[str]):
   ...

def f(a: list, b: list[str]):
   ...

def f(a: List, b: List[str]):
   ...

Bad:

def f(a: list, b: List):
   ...

def f(a: list, b: Dict):
   ...

def f(a: list[str], b: List):
   ...

def f(a: list, b: List[str]):
   ...

def f(a: list[str], b: List[str]):
   ...

The same for Dict, type, and so on. See PEP 585 for the full list.

Reasoning

Consistency about what style should be used.

For the older Python versions, there is not much choice what you can use for parametrized generics, so in some cases, the rule will advise you to use typing module even for unparametrized generics. While it sounds like one more import, asking users to do that import helps to avoid cases when the generic wasn't parametrized not because of complex annotation but because of lazyness.

@orsinium orsinium added the rule request Adding a new rule label Sep 29, 2020
@sobolevn
Copy link
Member

I will implement this in typed-linter someday. It would very hard to do correctly in flake8.

@orsinium
Copy link
Collaborator Author

I think it is ok to have the rule to check only names, like if name in ('typing.List', 'List'). It looks like a good assumption that users have no their own List class or typing module. Otherwise, it would lead to conflicts with typing module anyway, and conflicting with stdlib isn't good.

@orsinium
Copy link
Collaborator Author

(consider adding typed-linter label on all such issues there)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
rule request Adding a new rule
Projects
None yet
Development

No branches or pull requests

2 participants