Skip to content

Invalid setattr() call

Detects invalid usage of setattr() built-in function, which bypasses type checking and can lead to runtime type errors.

setattr() allows dynamic attribute assignment, letting you assign any type to any attribute regardless of type annotations. Type checkers can't track these dynamic modifications.

What gets flagged

Python
1
2
3
4
5
6
class Foo:
    def __init__(self) -> None:
        self.x: str = "hello"

foo = Foo()
setattr(foo, "x", 1)
Unsoundness Checker Output
Text Only
1
2
3
4
5
6
7
8
9
error[invalid-setattr]: Using `setattr()` bypasses type checking and can lead to runtime type errors.
 --> main.py:6:1
  |
5 | foo = Foo()
6 | setattr(foo, "x", 1)
  | ^^^^^^^^^^^^^^^^^^^^
  |
info: Object of type Literal[1] is not assignable to type str
info: rule `invalid-setattr` was selected in the configuration file

Mypy: No Diagnostic Emitted

Pyright: No Diagnostic Emitted

Ty: No Diagnostic Emitted