TypedDict cannot declare attribute named "not"

Viewed 416

I am trying to declare a type for the JSON Schema spec so I can validate types with passing around schemas with the jsonschema Python package. It is a Dict, so I am using Python 3.8 TypedDict. Here is what I have so far:

from typing import List, Dict, Any, TypedDict, Optional

class JSONSchema(TypedDict):
    """A type for the JSONSchema spec"""
    type: str
    title: Optional[str]
    description: Optional[str]
    properties: Optional[Dict[str, JSONSchema]]
    required: Optional[List[str]]
    additionalProperties: Optional[bool]
    definitions: Optional[Dict[str, JSONSchema]]
    minLength: Optional[int]
    maxLength: Optional[int]
    allOf: Optional[List[JSONSchema]]
    anyOf: Optional[List[JSONSchema]]
    oneOf: Optional[List[JSONSchema]]
    not: Optional[JSONSchema]

However, I get the following syntax error:

  File "autocoder_ocr/schemas.py", line 39
    not: Optional[JSONSchema]
       ^
SyntaxError: invalid syntax

This is because not is a language keyword. However, "not" is a valid dict key. So how can I declare it in the type definition?

I'm using Python 3.8.2

1 Answers

Hey you could use this style, it will let you use not as a key.

from typing import List, Dict, Any, TypedDict, Optional
JSONSchema = TypedDict(
    "JSONSchema",
    {
        "type": str,
        "title": Optional[str],
        "description": Optional[str],
        "properties": Optional[Dict[str, JSONSchema]],
        "required": Optional[List[str]],
        "additionalProperties": Optional[bool],
        "definitions": Optional[Dict[str, JSONSchema]],
        "minLength": Optional[int],
        "maxLength": Optional[int],
        "allOf": Optional[List[JSONSchema]],
        "anyOf": Optional[List[JSONSchema]],
        "oneOf": Optional[List[JSONSchema]],
        "not": Optional[JSONSchema],
    },
)

The second error in your code is that JSONSchema is not defined in the class body or in this way on the right hand side of the assignment. Eventually you might be able to write something like Optional["JSONSchema"], but that is not implemented.

Recursive or cyclic type definitions are not currently supported. Here's the github issue: https://github.com/python/mypy/issues/731 , you might be able to find a work around somewhere in there.

Related