[Python] reportAssignmentType Pylance error when using TypeVar

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to make a function that replaces some substrings inside strings with a preassigned value,
    and I've extended it so that it works for list, dict, and tuple as well.

    I used TypeVar to denote that the input type and output types are the same, but I keep getting pylance warning messages.

    How should I type hint the following code so I don't get these messages?

    T = TypeVar("T")
    PLACEHOLDERS = ["1", "2", "3"]
    VALUE = "value"

    def replace_string(obj: T) -> T:
    if isinstance(obj, str):
    for placeholder in PLACEHOLDERS:
    # Cannot access attribute "replace" for class "object*"
    # Attribute "replace" is unknown, Type "str | Unknown" is not assignable to declared type "T@replace_string"
    obj = obj.replace(placeholder, VALUE)
    elif isinstance(obj, list):
    # Type "list[Unknown]" is not assignable to declared type "T@replace_string"
    obj = [replace_string(item) for item in obj]
    elif isinstance(obj, tuple):
    # Type "tuple[Unknown, ...]" is not assignable to declared type "T@replace_string"
    obj = tuple(replace_string(item) for item in obj)
    elif isinstance(obj, dict):
    # Type "dict[Unknown, Unknown]" is not assignable to declared type "T@replace_string"
    obj = {key: replace_string(value) for key, value in obj.items()}
    return obj

    Continue reading...

Compartilhe esta Página