python / python/mypy

Allow __new__ to return type(None)

Abierto
#10,394 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug Report

__new__ should be allowed to return type(None)
I know that the usual way to do this is to define a parameter as:
param: typing.Optional[str]
Sometimes developers want to customize __new__ and returning a None instance is possible and should be allowed
Adding functionality like this might be desired when they want a class to be able to do run time type checking that either str or None was ingested in new and returning the correct instance.

Here are real life samples where people using this pattern of returning None inside of __new__:

  1. https://github.com/igor-rodrigues-ss/vectorio/blob/5c77ba15eea48d2de6c5cf3000148eb149e4e790/build/lib/vectorio/vector/output/geojson/geometry.py#L10
  2. https://github.com/jpolitz/lambda-py-paper/blob/746ef63fc1123714b4adaf78119028afbea7bd76/base/pylib/none.py#L3
  3. https://www.code-learner.com/how-to-use-python-__new__-method-example/
  4. https://github.com/MrainFly/WarIV/blob/2bd7e674f715c0784fdc86358a69edea1fc3940c/Warrior/warrior.py#L67
  5. https://github.com/ClearAerospace/faa-aircraft-registry/blob/749983ca9888c3c33cc1a2522c06b186f8bc2578/faa_aircraft_registry/types.py#L192
  6. https://github.com/AGProjects/sylkserver/blob/315109881273057cd91180c93589b6fa613ef8ff/sylk/configuration/datatypes.py#L68
  7. https://github.com/romaroman/visulast/blob/8e9e89db90f8c1ecd092bef2649411b275e5e143/visulast/core/models.py#L24
  8. https://github.com/saghul/TunnelIt/blob/a1fe1c54b02dd5dc3b237f4e668952e117e769bf/tunnelit/datatypes.py#L15
  9. https://github.com/brettchien/PyBLEWrapper/blob/9ea894be978c7aab8dbd46c92e80b2bd6cfc24c2/pyble/__init__.py#L37
  10. https://github.com/maddox/vlc/blob/0dedb23704b49806c2ae4a50a72fed2fbfada4c2/bindings/python-ctypes/override.py#L168
  11. https://github.com/openstate/open-raadsinformatie/blob/10895c8e23c3e41a39886d5c61e62c8099bbb49d/ocd_backend/models/misc.py#L37

When mypy analyses the below code, an error is thrown when it should not be

To Reproduce

Run mypy on this file:

import typing

NoneType = type(None)

class NullableString:
    @typing.overload
    def __new__(cls: type, arg: None) -> 'NoneType':
        pass
    @typing.overload
    def __new__(cls: type, arg: str) -> 'NullableString':
        pass
    def __new__(cls: type, arg: typing.Optional[str]):
        if arg is None:
            return NoneType.__new__(type(None))
        elif isinstance(arg, str):
            return str.__new__(cls)

NullableString(None)

Expected Behavior

I expected mypy to not throw errors

Actual Behavior

mypy reports:

(venv) Justins-MacBook-Air:scratch justinblack$ mypy typhint/primitive.py 
typhint/primitive.py:7: error: "__new__" must return a class instance (got "None")
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used:mypy==0.812, mypy-extensions==0.4.3
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: Python 3.8.6 (default, Nov 20 2020, 18:02:11) [Clang 11.0.0 (clang-1100.0.33.17)] on darwin
  • Operating system and version: MacOS 10.14.6 (18G8022)

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza reproduciendo el diagnóstico informado con el fragmento de NullableString proporcionado y el comando de mypy indicado. Rastrea cómo mypy valida los tipos de retorno de new y, después, añade cobertura de regresión para devolver type(None); el trabajo estará terminado cuando el ejemplo se compruebe en cuanto a tipos sin errores y las comprobaciones habituales de new sigan siendo correctas.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Tranquilo
Claridad
Bastante claro
Aptitud para principiantes
48/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.