Skip to content

TypeCheckError when tuple unpacking to properties of method parameter #506

@nachos5

Description

@nachos5

Things to check first

  • I have searched the existing issues and didn't find my bug already reported there

  • I have checked that my bug is still present in the latest release

Typeguard version

4.4.1

Python version

3.12.2

What happened?

When using Typeguard 4.4.1 (does not happen in 4.4.0), tuple unpacking to attributes of an object that was passed as a parameter raises an incorrect TypeCheckError:

typeguard.TypeCheckError: value assigned to <param>. <attr> (<type>) is not an instance of <class>

The error message incorrectly claims we're trying to assign a value to the entire object, when we're actually assigning to one of its attributes.

The same operation works correctly:

  • When using individual attribute assignments (<param>.<attr> = <value>)
  • When tuple unpacking to attributes of locally created objects
  • In Typeguard version 4.4.0

How can we reproduce the bug?

"""Bug in Typeguard 4.4.1. Does not happen in 4.4.0."""

from dataclasses import dataclass
from typeguard import typechecked


@dataclass
class Foo:
    bar: str = "bar"
    baz: int = 123


@typechecked
def run() -> None:
    foo = Foo()

    # Case 1: Direct attribute assignment works fine.
    foo.bar = "bar"
    foo.baz = 123

    # Case 2: Tuple unpacking in main scope works fine.
    foo.bar, foo.baz = ("bar", 123)

    mutate(foo)


@typechecked
def mutate(obj: Foo) -> None:
    # Case 3: Direct attribute assignment in method works fine.
    obj.bar = "bar"
    obj.baz = 123

    # Case 4: BUG - Tuple unpacking in method raises incorrect error.
    # Expected: Should work like Case 2.
    # Actual: Raises typeguard.TypeCheckError claiming str is not an instance of Foo.
    obj.bar, obj.baz = ("bar", 123)


if __name__ == "__main__":
    run()

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions