return type same as class gives NameError.

Cameron Simpson cs at cskk.id.au
Sun Oct 22 18:06:54 EDT 2023


On 22Oct2023 17:50, Antoon Pardon <antoon.pardon at vub.be> wrote:
>I have the following small module:
>=-=-=-=-=-=-=-=-=-=-=-= 8< =-=-=-=-=-=-=-=-=-=-=-=-=
>class Pnt (NamedTuple):
>    x: float
>    y: float
>
>    def __add__(self, other: PNT) -> Pnt:
>        return Pnt(self[0] + other[0], self[1] + other[1])

When this function is defined, the class "Pnt" has not yet been defined.  
That happens afterwards.

You want a forward reference, eg:

     def __add__(self, other: PNT) -> "Pnt":

A type checker will resolve this after the fact, when it encounters the 
string in the type annotation.

This message:

     NameError: name 'Pnt' is not defined. Did you mean: 'PNT'?

is unfortunate, because you have a very similar "PNT" name in scope. But 
it isn't what you want.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list