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 support #134

Closed
sobolevn opened this issue Aug 15, 2021 · 2 comments
Closed

TypedDict support #134

sobolevn opened this issue Aug 15, 2021 · 2 comments

Comments

@sobolevn
Copy link
Contributor

Right now if you want to write a TypedDict that will work with isinstance - you need to write:

from typing_extensions import TypedDict

class User(TypedDict):
    name: str
    registered: bool

class UserDictMeta(type):
    def __instancecheck__(cls, arg: object) -> bool:
        return (
            isinstance(arg, dict) and
            # The part below can be really long if `user` has lots of fields
            isinstance(arg.get('name'), str) and
            isinstance(arg.get('registered'), bool)
        )

UserMeta = type('UserMeta', (UserDictMeta, type(TypedDict)), {})

class UserDict(User, metaclass=UserMeta):
    ...

a = {'name': 'sobolevn', 'registered': True}
print(isinstance(a, UserDict))  # True

I see that people can benefit from a better API, like:

from phantom.structure import TypedDictWithStructure
from typing_extensions import TypedDict

class User(TypedDict):
    name: str
    registered: bool

class UserDict(User, TypedDictWithStructure):
   ...

a = {'name': 'sobolevn', 'registered': True}
print(isinstance(a, UserDict))  # True

Possible problems:

  1. Phantom types for mutable base types #128
  2. mypy right now does not allow to call isinstance with TypedDict subtypes: error: Cannot use isinstance() with TypedDict type

What do you think?

@sobolevn
Copy link
Contributor Author

sobolevn commented Aug 15, 2021

Related https://bugs.python.org/issue44919

@antonagestam
Copy link
Owner

I think this is better solved in a library focused on runtime type checking of TypedDict. It doesn't seem like narrowing a dict to a TypedDict can ever be safe (since the dict could be manipulated by another context). I personally have only found TypedDict useful for describing i.e. dict literals in config and so I don't find this compelling.

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

No branches or pull requests

2 participants