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

Expose required/non-required keys for mixed TypedDict or TypedDict base class, in runtime #7

Open
shamrin opened this issue Apr 24, 2019 · 2 comments
Labels

Comments

@shamrin
Copy link

@shamrin shamrin commented Apr 24, 2019

MyPy documentation mentions it's possible to mix required and non-required items in TypedDict:

class MovieBase(TypedDict):
    name: str
    year: int

class Movie(MovieBase, total=False):
    based_on: str

https://mypy.readthedocs.io/en/latest/more_types.html#mixing-required-and-non-required-items

Unfortunately, I couldn't find how to see which of Movie keys are required, in runtime. I can only get a list of all fields (__annotations__) and the fact Movie is non-total (__total__).

>>> from mypy_extensions import TypedDict
>>> class MovieBase(TypedDict):
...     name: str
...     year: int
... 
>>> class Movie(MovieBase, total=False):
...     based_on: str
... 
>>> Movie.__annotations__
{'based_on': <class 'str'>, 'name': <class 'str'>, 'year': <class 'int'>}
>>> Movie.__total__
False

Alternatively I could poke into original base classes to find out which keys are required, but I it doesn't work:

>>> Movie.__bases__
(<class 'dict'>,)

I'm trying to write a function that checks if data matches its TypedDict type, in runtime. I can't implement it without knowing which keys are required.

@shamrin
Copy link
Author

@shamrin shamrin commented Apr 25, 2019

@shamrin shamrin changed the title Expose required/non-required keys for mixed TypedDict, in runtime Expose required/non-required keys for mixed TypedDict or TypedDict base class, in runtime Apr 25, 2019
shamrin added a commit to shamrin/mypy_extensions that referenced this issue Apr 25, 2019
Potential fix for python#7.

The name for the attribute comes from PEP 560. It's not clear if it's the intended use for it.
@ilevkivskyi
Copy link
Collaborator

@ilevkivskyi ilevkivskyi commented Apr 25, 2019

On one hand, this is pretty niche, but on the other hand, if you have a simple addition to the private TypedDict API that would allow supporting this in typing_inspect, then we may accept the PRs (here and then in typing_inspect).

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

Successfully merging a pull request may close this issue.

None yet
2 participants
You can’t perform that action at this time.