Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

427
Vistas
Why does mypy not accept a list[str] as a list[Optional[str]]?

Example 1:

from typing import List, Optional

def myfunc() -> List[Optional[str]]:
    some_list = [x for x in "abc"]
    return some_list

Mypy complains on example 1:

Incompatible return value type (got "List[str]", expected "List[Optional[str]]")

However, this example gets no complaint:

Example 2:

def myfunc() -> List[Optional[str]]:
    some_list = [x for x in "abc"]
    return list(some_list)

What is the explanation for the inconsistent behavior?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Since in Python lists are invariant (see the examples here and here).

If we pass List[str] to someone that expects List[Optional[str]], that someone may add a None to our list and break our assumptions. The second example is valid however as the output of list() in the return statement is not saved anywhere and no one can depend on the the returned value being mutated illegally .

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda