-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
_asdict returns OrderedDict in 3.1 and up #1690
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
Conversation
stdlib/3/typing.pyi
Outdated
@@ -520,7 +520,10 @@ class NamedTuple(tuple): | |||
@classmethod | |||
def _make(cls, iterable: Iterable[Any]) -> NamedTuple: ... | |||
|
|||
def _asdict(self) -> dict: ... | |||
if sys.version_info >= (3, 1): | |||
def _asdict(self) -> collections.OrderedDict: ... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you add type arguments (probably [str, Any]
)?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added on the Dict block but for OrderedDict it crashes. Is there any workaround to allow typed OrderedDict?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you mean by crashes? What errors do you get?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this would cause an exception as in the example below:
(.venv3) luka-mbp:typeshed luka$ cat test.py
from collections import OrderedDict
def new_dict() -> OrderedDict[str, str]:
return OrderedDict()
print(new_dict())
(.venv3) luka-mbp:typeshed luka$ python3 test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
def new_dict() -> OrderedDict[str, str]:
TypeError: 'type' object is not subscriptable
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@JelleZijlstra how do you want to proceed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I had written a comment here but I guess I forgot to post it.
It's true that OrderedDict with type arguments doesn't work at runtime, but they should work fine in stubs, because OrderedDict is generic in the stub.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice, didn't know that 👍
As per documentation here: https://docs.python.org/3.6/library/collections.html#collections.somenamedtuple._asdict
Changed in version 3.1: Returns an OrderedDict instead of a regular dict.