Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Last active January 23, 2023 23:50
Show Gist options
  • Save carymrobbins/097f18904d67e82430ea1946b401a6dd to your computer and use it in GitHub Desktop.
Save carymrobbins/097f18904d67e82430ea1946b401a6dd to your computer and use it in GitHub Desktop.

Revisions

  1. carymrobbins revised this gist Jan 23, 2023. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion dataclass_csv.py
    Original file line number Diff line number Diff line change
    @@ -12,7 +12,7 @@ class Widget:


    def deserialize_csv_row(typ: type[T], row: str) -> T:
    if not is_dataclass(x):
    if not is_dataclass(typ):
    raise TypeError(
    f'Cannot deserialize type from CSV row: {type(x)}'
    )
  2. carymrobbins revised this gist Jan 23, 2023. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions dataclass_csv.py
    Original file line number Diff line number Diff line change
    @@ -14,7 +14,7 @@ class Widget:
    def deserialize_csv_row(typ: type[T], row: str) -> T:
    if not is_dataclass(x):
    raise TypeError(
    f'Cannot deserialize value from CSV row: {x}; type was {type(x)}'
    f'Cannot deserialize type from CSV row: {type(x)}'
    )
    values = []
    for cells in csv.reader([row]):
    @@ -37,5 +37,5 @@ def deserialize_csv_cell(typ: type[T], cell: str) -> T:
    if typ is int:
    return int(cell)
    raise TypeError(
    f'Cannot deserialize value from CSV cell: {x}; type was {type(x)}'
    f'Cannot deserialize type from CSV cell: type was {type(x)}'
    )
  3. carymrobbins created this gist Jan 23, 2023.
    41 changes: 41 additions & 0 deletions dataclass_csv.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    import csv
    from dataclasses import dataclass, fields, is_dataclass
    from typing import TypeVar

    @dataclass
    class Widget:
    name: str
    amount: int


    T = TypeVar('T')


    def deserialize_csv_row(typ: type[T], row: str) -> T:
    if not is_dataclass(x):
    raise TypeError(
    f'Cannot deserialize value from CSV row: {x}; type was {type(x)}'
    )
    values = []
    for cells in csv.reader([row]):
    x_fields = fields(x)
    x_fields_len = len(x_fields)
    cells_len = len(cells)
    if x_fields_len != cells_len:
    raise ValueError(
    f'Row length mismatch: type {typ} expects {x_fields_len} cells '
    f'but got {cells_len}'
    )
    for f, cell in zip(x_fields, cells):
    values.append(deserialize_csv_cell(f.type, cell))
    return typ(*values)


    def deserialize_csv_cell(typ: type[T], cell: str) -> T:
    if typ is str:
    return cell
    if typ is int:
    return int(cell)
    raise TypeError(
    f'Cannot deserialize value from CSV cell: {x}; type was {type(x)}'
    )