I'm working with Python 3.10 and I have this class (which I have simplified):
class Greetings:
def list(self) -> list[str]:
return ['ab', 'cd']
def hello(self, names: list[str]) -> None:
for name in names:
print("Hello", name)
While testing it, I got this error:
... in Greetings
def hello(self, names: list[str]) -> None:
E TypeError: 'function' object is not subscriptable` error.
I know that the issue comes from my list
method, which Python is trying to use in the typing of the names
parameter. But I don't understand why this is happening or if it an issue with Python language. It is suppose that starting with Python 3.10 I can use list
as typing instead of importing List
from the typing
module.
Any guess?
After you define def list
, the name list
inside your class
block refers to that def list
method. You've shadowed the name. You can work around this by aliasing list
, or by using builtins
:
import builtins
class Greetings:
...
def hello(self, names: builtins.list[str]) -> None:
...