Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

346
Visualizações
typed python: using the classes' own type inside class definition

The following code does not work as expected. Apparently, I cannot use the classes' own type inside class definition:

class Foo:
    def __init__(self, key :str) -> None:
        self.key = key

    def __eq__(self, other :Foo) -> bool:
        return self.key == other.key

print('should be true: ', Foo('abc') == Foo('abc'))
print('should be false: ', Foo('abc') == Foo('def'))

The result of running it is:

Traceback (most recent call last):
  File "class_own_type.py", line 1, in <module>
    class Foo:
  File "class_own_type.py", line 5, in Foo
    def __eq__(self, other :Foo) -> bool:
NameError: name 'Foo' is not defined

Also, checking the code with mypy returns:

class_own_type.py:5: error: Argument 1 of "__eq__" incompatible with supertype "object"

How can I correct this code to be valid, both for Python and for mypy?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The name Foo isn't bound yet, because the class itself has not yet been defined at the time that you try to use the name (remember: function arguments are evaluated at function definition time, not at function call time).

From Python 3.7+ you can postpone evaluation of annotations by adding this import at the top of the module:

from __future__ import annotations

In Python 3.10 postponed evaluation will become the default behavior. For Python < 3.7, you can use string literals to delay evaluation of the type:

class Foo:
    def __init__(self, key :str) -> None:
        self.key = key

    def __eq__(self, other: 'Foo') -> bool:
        return self.key == other.key

print('should be true: ', Foo('abc') == Foo('abc'))
print('should be false: ', Foo('abc') == Foo('def'))
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda