Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do class methods shadowing names from outer scope in python class method type hints?

For example:

In [4]: In [17]: class X:
   ...:     def not_shadow(self, x: list[int]):
   ...:         pass
   ...: 
   ...:     def list(self):
   ...:          list()
   ...: 
   ...:     def shadow_by_X_list_method(self, x: list[int]):
   ...:         pass
   ...: 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 class X:
      2     def not_shadow(self, x: list[int]):
      3         pass

Cell In[4], line 8, in X()
      5 def list(self):
      6      list()
----> 8 def shadow_by_X_list_method(self, x: list[int]):
      9     pass

TypeError: 'function' object is not subscriptable

I expected that class function names would only be available as members of self variable.

like image 646
Fedor Goncharov Avatar asked Oct 29 '25 20:10

Fedor Goncharov


1 Answers

This is a quirk of the scoping rules!

While perhaps surprising, as @jonsharpe notes in a comment, this behavior is the same as everywhere in Python and allows later methods and their arguments to refer to earlier methods in general

In their example, they note @property, which adds additional methods directly to the wrapped method

Abridged from the docs https://docs.python.org/3/library/functions.html#property.getter

class Foo:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter            # <-- property of earlier x
    def x(self, value):
        self._x = value
like image 154
ti7 Avatar answered Oct 31 '25 12:10

ti7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!