Skip to content

Change the return type of __reduce__ and __reduce_ex__ to Union[str, Tuple[Any, ...]]#3453

Merged
srittau merged 1 commit intopython:masterfrom
MSeifert04:reduce-return-union
Nov 10, 2019
Merged

Change the return type of __reduce__ and __reduce_ex__ to Union[str, Tuple[Any, ...]]#3453
srittau merged 1 commit intopython:masterfrom
MSeifert04:reduce-return-union

Conversation

@MSeifert04
Copy link
Copy Markdown
Contributor

This allows subclasses to return strings (which are allowed) from these
methods without having mypy throwing an error.

This fixes #3452

However this violates the following item from the Contributing file:

def __sizeof__(self) -> int: ...
def __reduce__(self) -> Tuple[Any, ...]: ...
def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ...
def __reduce_ex__(self, protocol: int) -> Tuple[Any, ...]: ...
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could you also add this to __reduce_ex__?

…Tuple[Any, ...]]

This allows subclasses to return strings (which are allowed) from these
methods without having mypy throwing an error.
@srittau
Copy link
Copy Markdown
Collaborator

srittau commented Nov 10, 2019

However this violates the following item from the Contributing file:

This is fine in this case. Normally we prefer non-Union return types, because it means the caller needs to use assert isinstance or a cast on the return value, even if they know the return type because of the way they call a function. In this case, this function is mainly called by Python itself, but even in cases where it's called manually, it probably makes sense that the caller does an ambiguation or at least an assert. In the rare cases where this is not the case, there is always # type: ignore.

@MSeifert04
Copy link
Copy Markdown
Contributor Author

Ah, thank you for the clarification!

@srittau srittau merged commit 97ecd2b into python:master Nov 10, 2019
@MSeifert04 MSeifert04 deleted the reduce-return-union branch November 10, 2019 14:55
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.

object.__reduce__ might return a string

2 participants