Search code examples
pythontype-hintingpython-typing

Python Function Member of Class, Class as Parameter. How To, or Work Around


I have a Python class that represents a matix of integers. The Matrix class has a function that can cross tabulate itself (? better word), with another Matrix passed to its cross tabulate function as such,

class Matrix:
 
    def __init__(self, name: str, maximum: int, upperbound: int, rowcount: int) -> None:
        '''
        #### parameters:
            name (str): Name of the matrix
            maximum (int): Maximum value, the highest number in the matrix
            upperbound (int): Number of matrix columns
            rowcount (int): Number of matrix rows
        '''

        self.__name: str = name
        self.__maximum: int = maximum
        self.__upperbound: int = upperbound
        self.__rowcount: int = rowcount

        self.__data_matrix = [];    # matrix of integer data retrieved from a data source


    def crosstabulate(self, matrix_y: Matrix) -> list:
        '''
        cross tabulation functionality, 
        #### parameters:
            matrix_y (Matrix): Matrix to cross tabulate with this class's matrix
        '''

My questions being, the there a way to type hint the matrix_y parameter as the class it is define in? Or is there a work around that can make this happen?

Additional note, It just occurred to me, I could make a CrossTabulation class that takes two Matrix classes as constructor parameters, if all else doesn't really cut it.


Solution

  • You can always enclose type hints in quotes to make the Python interpreter accept them.

    def crosstabulate(self, matrix_y: 'Matrix') -> list:
    

    Alternatively, you can use a future import to do this automatically.

    from __future__ import annotations
    

    With this import, all type annotations in the current file get implicitly wrapped in quotes. This always does the right thing for type checkers but can cause problems if libraries are using annotations at runtime, since the library will see a string rather than a concrete value.