attrs
attrs copied to clipboard
Assign None as default for Optional Type
Hi, I think it would be awesome if the default value for Optional types would be set to None. Here is a snippet I hoped would work:
import attr
@attr.s(auto_attribs=True)
class Book:
name: str
author: Optional[str]
data = {'name': 'Fluent Python'}
Book(**data)
TypeError: __init__() missing 1 required positional argument: 'author'
You can very easily add = None to the class definition.
Also default args don't play nice if they are in the middle. e.g.
@attr.s(auto_attribs=True)
class Book:
name: str
author: Optional[str]
isbn: str
This is what I am currently doing - assigning None to every field in 20-field schema and it is looking ugly. I believe this is extra information which is already indicated by the Optional type.
I'm not sure I agree that the optional type indicates that the default should be None; it only indicates that the value may be None.
That said, it does seem a reasonable default-default. But I'm a little wary of doing that implicitly, and @euresti's point about defaults in the middle would have to be addressed.
it would be viable if one could as choose a class creation policy that implied convenient defaults
having it as implicit default limits the control of a class creator over expressing behaviour
If technically viable, this could be part of our new attrs namespace.