Search code examples
python-3.xparameter-passingreadability

specify the type inside a class method


What is the pythonic way to properly specify the type of the arguments of a method?

Checking How do Python functions handle the types of the parameters that you pass in? and How do I ensure parameter is correct type in Python? only works for primitive data types.

Consider the minimum following example, where I want to pass an object of same type to the method. This does not work because the method is defined inside the class.

class num:
    def __init__(self,val:int) -> None:
        self.x=val
    def print(self,other:num) -> None:
        pass

def main():
    n=num(3)
    n.print()

main()


Solution

  • You can use forward references:

    class num:
        def __init__(self,val:int) -> None:
            self.x=val
        def print(self,other:'num') -> None:
            pass
    
    

    This works because Python (and any checkers complying to PEP 484) will understand your hint and register it appropriately, this is a common scenario.