Skip to content

Any inferred when overloaded function called with None argument #3256

Closed

Description

@JukkaL

Mypy infers Any when calling a precisely typed overloaded function with a None argument (without strict optional checking). This is undesirable, since an Any is silently generated:

from typing import overload

@overload
def f(x: int) -> int:
    pass
@overload
def f(x: str) -> str:
    pass

def f(x): pass

reveal_type(f(None))  # Any

Not sure what's the right thing to do here -- we can either generate a message that says that the overload target is ambiguous, or infer Union[int, str] as the return type.

Note that explicitly including a None overload variant does not work as a workaround:

from typing import overload

@overload
def f(x: None) -> int:  # Overloaded function signatures 1 and 3 overlap with 
                        # incompatible return types
    pass
@overload
def f(x: int) -> int:
    pass
@overload
def f(x: str) -> str:
    pass

def f(x): pass

This is related to #1322.

Activity

  1. ilinum commented on Jul 6, 2017

    @ilinum
    Collaborator

    Without the --strict-optional flag, the functions in the example are essentially overlapping, so we should treat them as such (because any type could be None).

    It seems to me that this issue is more or less a duplicate #1322.

  2. JukkaL commented on Jul 6, 2017

    @JukkaL
    CollaboratorAuthor

    This is a special case of #1322. Not sure if it's useful to track these as separate issues.

  3. ilinum commented on Jul 6, 2017

    @ilinum
    Collaborator

    I think it's useful to keep it open, just to make sure we don't forget to test this case.

  4. Michael0x2a commented on Jun 15, 2018

    @Michael0x2a
    Collaborator

    I think this is working in a reasonable way on master now: mypy reports a 'No overload variant of "f" matches argument type "None"` in strict-optional mode and infers 'int' in no-strict-optional mode.

    If we add a 'None' fallback, we infer int in both cases.

    I guess the remaining question is whether or not it would be nice to add a command line flags that tells mypy to do something more stricter then just picking the first match, but I think we already have an issue for that.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions