Home > Net >  how to define an object method that takes an argument of the object's type
how to define an object method that takes an argument of the object's type

Time:05-29

Here is a case where it would be sensible to give the type hint of an argument of an object's method as the object itself.

class ImagePath:
def __init__(self, path:Path, size:int):
    self.path = path
    self.size = size

def __eq__(self, other:ImagePath):
    return self.path == other.path and self.size == other.size

However, this gives an error:

    NameError: name 'ImagePath' is not defined

Is there a way to construct the method with the correct type hint?

PS. I am aware that the method will respond the same way without the equality method, but this was a simple example.

CodePudding user response:

Put ImagePath in quotes, like this:

class ImagePath:
    def __init__(self, path:Path, size:int):
        self.path = path
        self.size = size

    def __eq__(self, other:'ImagePath'):
        return self.path == other.path and self.size == other.size

See PEP 484 section Forward Reference

CodePudding user response:

Starting from Python 3.7, with PEP 563, you can use from __future__ import annotations to store annotations as strings. From PEP 563:

This PEP proposes changing function annotations and variable annotations so that they are no longer evaluated at function definition time. Instead, they are preserved in __annotations__ in string form.

This change is being introduced gradually, starting with a __future__ import in Python 3.7.

from __future__ import annotations

class ImagePath:
    def __init__(self, path:tuple, size:int):
        self.path = path
        self.size = size

    def __eq__(self, other:ImagePath):
        return self.path == other.path and self.size == other.size
    
ImagePath((10,22),20) == ImagePath((10,22),20)
# True
ImagePath((10,22),20) == ImagePath((10,), 20)
# False
  • Related