glideapps / glideapps/quicktype
Optional fields in Python dataclasses
- Dominant language
- TypeScript
- Stars
- 13.9k
- Forks
- 1.2k
- Avg merge
- 8h 53m
- Merged PRs (30d)
- 369
Description
I think optional fields should be optional in generated Python dataclasses.
[Demo link][1]. Source language: TypeScript
```ts
export interface Config {
a?: any;
b?: any;
}
```
Target language: Python 3.7 (abridged for clarity)
```py
from dataclasses import dataclass
from typing import Any
@dataclass
class Config:
a: Any
b: Any
```
The problem here is that, if you try to instantiate a `Config` object, the fields are both required:
```
>>> Config(a=12)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 Config(a=12)
TypeError: __init__() missing 1 required positional argument: 'b'
```
Since the properties are both optional, this should be OK. The way to make that happen with a dataclass would be to generate code like this:
```py
@dataclass
class Config:
a: Any = None
b: Any = None
```
Then I can construct a `Config` omitting either property:
```
>>> Config(a=12)
Config(a=12, b=None)
```
I realize you get the expected behavior if you use the generated `config_from_dict` method. But you also get worse type checking (via your linter) for `dict`s than for `dataclass`es with named parameters.
Thanks for the great tool!
[1]: https://app.quicktype.io?share=XBPvukZ1HNzpDIioKrRb
Contributor guide
Assessment
This issue has not been assessed yet.