Skip to content

Commit 3947e74

Browse files
author
Nathan Richard
committed
refactor: support also generators, tuples, etc.
1 parent 4ebbb71 commit 3947e74

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ ___
3131
- Familiar syntax. The `BasemodelCSVReader` is used almost the same way as the `DictReader` in the standard library.
3232
- It uses `BaseModel` features that let you define Field properties or Config so the data can be parsed exactly the way you want.
3333
- Make the code cleaner. No more extra loops to convert data to the correct type, perform validation, set default values, the `BasemodelCSVReader` will do all this for you.
34-
- In addition to the `BasemodelCSVReader`, the library also provides a `BasemodelCSVWriter` which enables creating a CSV file using a list of instances of a BaseModel.
34+
- In addition to the `BasemodelCSVReader`, the library also provides a `BasemodelCSVWriter` which enables creating a CSV file using an Iterable with instances of a BaseModel.
3535
- Because [sqlmodel](https://github.com/tiangolo/sqlmodel) uses pydantic.BaseModels too, you can directly fill a database with data from a CSV
3636

3737

@@ -298,7 +298,7 @@ class User(BaseModel):
298298
age: int
299299
```
300300

301-
And in your program we have a list of users:
301+
And in your program we have a list (also supports Generator and Tuples. Just any Iterable that supports storing Objects) of users:
302302

303303
```python
304304
users = [

pydantic_csv/basemodel_csv_writer.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44

55
import csv
6+
from collections.abc import Iterable
67
from typing import Any
78

89
import pydantic
@@ -19,7 +20,7 @@ class BasemodelCSVWriter:
1920
def __init__(
2021
self,
2122
file_obj: Any,
22-
data: list[Any],
23+
data: Iterable,
2324
model: type[BaseModel],
2425
*,
2526
use_alias: bool = True,
@@ -29,8 +30,11 @@ def __init__(
2930
if not file_obj:
3031
raise ValueError("The 'file_obj' argument is required")
3132

32-
if not isinstance(data, list):
33-
raise ValueError("Invalid 'data' argument. It must be a list")
33+
if not isinstance(data, Iterable) or isinstance(data, (str, BaseModel)):
34+
raise ValueError(
35+
"Invalid 'data' argument. It must be an Iterable which can hold multiple BaseModel "
36+
"instances. eg: list, generator, tuple"
37+
)
3438

3539
if model is None or not issubclass(model, pydantic.BaseModel):
3640
raise ValueError("Invalid 'cls' argument. It must be a pydantic BaseModel")

0 commit comments

Comments
 (0)