Search code examples
pythonpython-typingshadowing

Does type hinting class members shadow previously defined or built-in variables?


With type-hinting, defining a class in Python goes from

class SomeClass:
    def __init__(self):
        self.id = 5

to something like this

class SomeClass:
    id: int

    def __init__(self) -> None:
        self.id = 5

However, a linter like ruff has an issue with the id: int line, which apparently would shadow the built-in id. That feels like a suprising behaviour to me, since in previous, type-hint-less times, id would have always been used as self.id with no shadowing whatsoever.

So I would like to know: is there really shadowing occurring and if so, to which extent, i.e. what is the scope of this shadowing?


Solution

  • The builtin id will be shadowed in the scope of the class definition block. Consider the following example:

    class SomeClass:
        id = lambda _: "overriden!"
        print(id(42))  # prints 'overriden'
    
        def __init__(self) -> None:
            print(id(42))
    
    
    SomeClass()  # prints an address
    print(id(42))  # prints an address