attrs icon indicating copy to clipboard operation
attrs copied to clipboard

Assign None as default for Optional Type

Open dmfigol opened this issue 7 years ago • 5 comments

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'

dmfigol avatar Nov 01 '18 00:11 dmfigol

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

euresti avatar Nov 02 '18 20:11 euresti

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.

dmfigol avatar Nov 03 '18 01:11 dmfigol

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.

wsanchez avatar Nov 03 '18 01:11 wsanchez

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

RonnyPfannschmidt avatar Nov 03 '18 10:11 RonnyPfannschmidt

If technically viable, this could be part of our new attrs namespace.

hynek avatar Nov 03 '18 12:11 hynek