smarie / python-pyfields

Define fields in python classes. Easily.
https://smarie.github.io/python-pyfields
BSD 3-Clause "New" or "Revised" License
45 stars 10 forks source link

`Optional` type hint is not correctly interpreted by `@autofields` #74

Closed smarie closed 3 years ago

smarie commented 3 years ago
from pyfields import autofields
from typing import Optional

@autofields
class City:
    name: Optional[str]
    buildings: List[str] = []

Calling the constructor without arguments : City() leads to TypeError: __init__() missing 1 required positional argument: 'name'

smarie commented 3 years ago

This is actually not a bug. typing.Optional is a misleading term saying that the type is optional (not the value). Therefore, the field can be none (is nonable), but that does not mean that it has a default value.

So this works : City(name=None)

Unfortunately the "Optional" name was not refactored in typing, and the very interesting discussion on candidate replacement names ended by "it is too late" :) https://github.com/python/typing/issues/452#issuecomment-364919052