Skip to content
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

TypedDict with forward references do not work in argument conversion #4945

Closed
pekkaklarck opened this issue Nov 15, 2023 · 1 comment
Closed

Comments

@pekkaklarck
Copy link
Member

If we use a TypedDict like below as a type hint, type conversion is done for key x but not for y.

from typing import TypedDict

class Example(TypedDict):
    x: int
    y: 'int'

This is different compared to functions and methods where argument conversion is done both for x and y if we have def example(x: int, y: 'int'). The reason is that with TypedDict the annotation assigned to y by Python is ForwardRef, while with functions and methods we get the original string. Our conversion logic handles strings as aliases but doesn't know that to do with ForwardRefs.

A simple fix for this issue is using typing.get_type_hints for getting types instead of accessing __annotations__ like we currently do. That has a problem that using something like x: 'int | float' will cause an error with Python < 3.10. We just added support for such stringified types in arguments (#4711) and supporting them with TypedDict would be good as well. I guess we need to use get_type_hints first and then access __annotations__ as a fall-back. Then we may get ForwardRefs and need to handle them as well.

@pekkaklarck
Copy link
Member Author

pekkaklarck commented Nov 15, 2023

This issue was initially reported by @aaltat on our Slack. He had used from __future__ import annotations instead of using stringified types, but that special import basically turns all annotations to strings and thus has the same effect.

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

No branches or pull requests

1 participant