pythonpython-typingtypeddict

Make all keys in a typed dict not required


I have an existing TypedDict containing multiple entries:

from typing import TypedDict
class Params(TypedDict):
    param1:str
    param2:str
    param3:str

I want to create the exact same TypedDict but with all the keys being optional so that the user can specify only certain parameters. I know I can do something like:

class OptionalParams(TypedDict, total=False):
    param1:str
    param2:str
    param3:str

but the problem with this method is that I have to duplicate the code. Is there a way to inherit from Params by making the keys optional ? I tried to do

class OptionalParams(Params, total=False):
    pass

but the linter does not understand that the parameters are optional


Solution

  • What you ask for is not possible - at least if you use mypy - as you can read in the comments of Why can a Final dictionary not be used as a literal in TypedDict? and on mypy's github: TypedDict keys reuse?. Pycharm seems to have the same limitation, as tested in the two other "Failed attempts" answers to your question.

    When trying to run this code:

    from typing import TypeDict
    
    params = {"a": str, "b": str}
    Params = TypedDict("Params", params)
    

    mypy will give error: TypedDict() expects a dictionary literal as the second argument, thrown here in the source code.