-
I'm using collections.UserList to create a custom list class. See this example. import collections
class TestClass(collections.UserList):
def __init__(self) -> None:
super().__init__()
def lower_all(self) -> None:
for count, s in enumerate(self.data):
self.data[count] = s.lower()
test = TestClass()
test.append("Hello")
test.append("World")
test.lower_all()
print(test[0]) In this example, TestClass should always be a list of strings. How can I annotate that? |
Beta Was this translation helpful? Give feedback.
Answered by
Daverball
Oct 24, 2023
Replies: 1 comment 3 replies
-
It depends on the Python version, if you're still on 3.8 you will need to add some Starting with 3.9 it should be as simple as: import collections
class TestClass(collections.UserList[str]):
def __init__(self) -> None:
super().__init__()
def lower_all(self) -> None:
for count, s in enumerate(self.data):
self.data[count] = s.lower() With 3.8 you would need to do something like the following: import collections
from typing import TYPE_CHECKING
if TYPE_CHECKING:
BaseList = collections.UserList[str]
else:
BaseList = collections.UserList
class TestClass(BaseList):
def __init__(self) -> None:
super().__init__()
def lower_all(self) -> None:
for count, s in enumerate(self.data):
self.data[count] = s.lower() |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
JakobDev
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It depends on the Python version, if you're still on 3.8 you will need to add some
if TYPE_CHECKING
blocks to deal with the fact thatABCMeta
(or rathercollections.abc.MutableSequence
, whichcollections.UserList
inherits from) is not subscriptable.Starting with 3.9 it should be as simple as:
With 3.8 you would need to do something like the following: