I use a class which subclasses the built-in list.
class Qry(list):
"""Stores a list indexable by attributes."""
def filter(self, **kwargs):
"""Returns the items in Qry that has matching attributes.
Example:
obj.filter(portfolio='123', account='ABC').
"""
values = tuple(kwargs.values())
def is_match(item):
if tuple(getattr(item, y) for y in kwargs.keys()) == values:
return True
else:
return False
result = Qry([x for x in self if is_match(x)], keys=self._keys)
return result
Now I want to type hint:
class C:
a = 1
def foo(qry: Qry[C]):
"""Do stuff here."""
How do you type hint a custom container class in python 3.5+?
PEP 484, which provides a specification about what a type system should look like in Python3, introduced the concept of type hints.
Type hints are performed using Python annotations (introduced since PEP 3107). They are used to add types to variables, parameters, function arguments as well as their return values, class attributes, and methods. Adding type hints has no runtime effect: these are only hints and are not enforced on their own.
Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5.
Type hinting in PyCharm Last modified: 19 September 2022. PyCharm provides various means to assist inspecting and checking the types of the objects in your script. PyCharm supports type hinting in function annotations and type comments using the typing module and the format defined by PEP 484.
You can do this rather easily:
from typing import TypeVar, List
T = TypeVar('T')
class MyList(List[T]): # note the upper case
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With