Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hint a subclass of list

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+?

like image 642
ChaimG Avatar asked May 02 '18 21:05

ChaimG


People also ask

What is PEP 484?

PEP 484, which provides a specification about what a type system should look like in Python3, introduced the concept of type hints.

Is type hinting enforced?

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.

What is type hinting in Python?

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.

What are type hints PyCharm?

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.


1 Answers

You can do this rather easily:

from typing import TypeVar, List
T = TypeVar('T')
class MyList(List[T]): # note the upper case
    pass
like image 139
Jared Smith Avatar answered Oct 27 '22 00:10

Jared Smith