Skip to content

Allow disabling implicit Any for type aliases #2696

@mohabusama

Description

@mohabusama

The issue is somehow discussed here #2690

Here is a sample code that mypy allows and eventually fails in runtime

from typing import *
T = TypeVar('T', List[int], Dict)
Processor = Callable[[T], None]
def output(inp: T, processor: Processor) -> None:
    processor(inp)
def process_dict(inp: Dict) -> None:
    print(inp.keys())
output([1, 2, 3], process_dict)

As described in #606 discussions and https://www.python.org/dev/peps/pep-0484/#type-aliases this is not a problem with mypy, but an overlooked mistake in non-parameterizing generic type aliasProcessor in output.

reveal_type for output:
Revealed type is 'def [T in (builtins.list[builtins.int], builtins.dict)] (inp: T-1, processor: def (Any))'`

Processor is implicitly treated as Processor[Any] in this case.

Changing output to def output(inp: T, processor: Processor[T]) -> None: resolves the issue and lets mypy catch the bug.

The problem is that implicit Any for type aliases can easily go unnoticed.

Suggestions:

  1. As suggested by @roganov & @ilevkivskyi : Add --disable-implicit-any flag to mypy, which will disable this behavior and forces the user to be explicit. Drawback, users who do not know about the flag might learn about the bug the hard way (in production 😉 )

  2. Disable implicit Any by default for type aliases, and force users to be explicit (either by parameterizing [Any] or [T]). Drawback, might introduce a lot of mypy errors for existing, "error free" code base (confusing/annoying to users). Also, not entirely sure about how this impacts other scenarios.

  3. Produce warning when used type alias has no explicit parameterization. This will make mypy exit without failure, but just point the user to potential bugs. Drawback, warnings might be annoying for users who are ok with their codebase (i.e. might require --suppress-implicit-any-warning)

  4. Any other suggestion ... 😄

Thanks,

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions