Skip to content

Conversation

@marcelm
Copy link

@marcelm marcelm commented Oct 13, 2022

I could not find how to do this in the documentation, but eventually saw the example in
#6580 (comment)
Reading this helped me improve my mental model of how overloads work, and perhaps others would benefit as well.

…tional argument

I could not find how to do this in the documentation, but eventually saw the
example in
python#6580 (comment)
# This overload variant applies when "rounded" is omitted or set to False.
@overload
def pi(rounded: Literal[False] = ...) -> float: ...
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not correct. This function will always be matched. Without a default should be the first one.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’m happy to change this, but at least in this case, both overloads are apparently matched. I tested with this file:

from typing import overload, Literal

@overload
def pi(rounded: Literal[False] = ...) -> float: ...

@overload
def pi(rounded: Literal[True]) -> int: ...

def pi(rounded=False):
    return 3 if rounded else 3.14159

reveal_type(pi(rounded=False))
reveal_type(pi())
reveal_type(pi(rounded=True))

mypy 0.982 tells me:

default.py:12: note: Revealed type is "builtins.float"
default.py:13: note: Revealed type is "builtins.float"
default.py:14: note: Revealed type is "builtins.int"

Swapping the order of the overloads doesn’t change the output. There’s also no warning about shadowing, wouldn’t that be printed otherwise?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I made the change.

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

Successfully merging this pull request may close these issues.

2 participants