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

build a typeddict from another #10585

Closed
dfroger opened this issue Jun 7, 2021 · 5 comments
Closed

build a typeddict from another #10585

dfroger opened this issue Jun 7, 2021 · 5 comments

Comments

@dfroger
Copy link
Contributor

dfroger commented Jun 7, 2021

I'm looking for a way to build a typeddict from another:

given:

class Foo(TypedDict):
    a: int
    b: int


class Bar(Foo):
    c: int


foo = Foo(a=1, b=2)

I would like to do bar = Bar(**foo, c=5), because we perform this operation many times with many dict and many keys, and bar = Bar(a=foo["a"], b=foo["b"], c=3) would be really too verbose.

I fear this is not possible yet. Any chance that such a functionality could be implemented?

I don't see a better workaround than bar = Bar(**foo, c=5) # type: ignore, maybe I'm missing something?

Thanks!

@sameershaik-tech
Copy link

can i work on this?

@wimax-grapl
Copy link

(Regardless of the TypedDict stuff, I think mypy just currently doesn't have any support for inferring the keys contained in a **kwargs splat.)

@dfroger
Copy link
Contributor Author

dfroger commented Jun 9, 2021

So I think I will use a cast. The scope of the dangerous code (ie, not type checked) is limited, it's flexible and not verbose, so it's not so bad.

foo = Foo(a=1, b=2)

# dangerous code (not type checked): developper must ensure the missing keys are added
foo = cast(Bar, foo)
foo["c"] = 1
# end of dangerous code

@dfroger
Copy link
Contributor Author

dfroger commented Jun 9, 2021

Adding this kind of code to the above snippet could be useful to remember to update the dangerous code when Foo or Bar is changed:

assert Bar.__annotations__ == {**Foo.__annotations__, "c": int}

Wonder if this assertion could be done statically?

@AlexWaygood
Copy link
Member

Duplicate of #9408

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

5 participants