Unnamed
Unnamed

Reputation: 153

Pylance strict mode issues

I am using strict-mode pylance in vscode, python3.11. I have the following code that gives me a red highlight error.

def foo() -> object:
    node = {
        "parent": None,
        "full_name": "/root",
        "depth": 0,
        "children": []
    }
    return node

The word "node" (line 2) is highlighted in red with the message «Type of "node" is partially unknown. Type of "node" is "dict[str, str | int | list[Unknown] | None]. PylancereportUnknownVariableType»

"node" is also highlighted in the final line, with the similar message «Return type, "dict[str, str | int | list[Unknown] | None]", is partially unknown. PylancereportUnknownVariableType»

Changing the return type did not help, I tried to be a little more specific.

def foo() -> dict[str, object]:
    node = {
        "parent": None,
        "full_name": "/root",
        "depth": 0,
        "children": []
    }
    return node

I also found no similar issues online.

Upvotes: 0

Views: 280

Answers (1)

Holt
Holt

Reputation: 37661

What pyright (which is the underlying type checker used by Pylance by default) tells you is that the type of node is partially unknown and thus does not match the expected return type of the function dict[str, object].

The type checker cannot deduce the type of node from a statement (the return statement) after the declaration of node, and since your dictionary contains a non-typed list, the type of the whole dictionary is partially unknown.

You need to either tell pyright the type of node by adding a type-hint (node: dict[str, object] = ...), or remove the intermediate varialbe (return {...}).

You can also force the type of the list (cast("list[dict[str, object]]", [])) but then you will have incompatible dict type, so you would need to use a Mapping type for the return type instead of dict.

Final option, maybe the best, it to use a custom class for the node type, either using TypedDict or dataclass.

Upvotes: 0

Related Questions