Metadata-Version: 2.5
Name: members-csv
Version: 1.0.0
Summary: Load member records from CSV files into typed Python objects, with a small CLI.
Project-URL: Homepage, https://github.com/AlexandruSerbanescu/members-csv
Project-URL: Issues, https://github.com/AlexandruSerbanescu/members-csv/issues
Project-URL: Changelog, https://github.com/AlexandruSerbanescu/members-csv/blob/main/CHANGELOG.md
Author: Alexandru Serbanescu
License-Expression: MIT
License-File: LICENSE
Keywords: csv,members,parser
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# members-csv

[![CI](https://github.com/AlexandruSerbanescu/members-csv/actions/workflows/ci.yml/badge.svg)](https://github.com/AlexandruSerbanescu/members-csv/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.10%2B-blue)
![License: MIT](https://img.shields.io/badge/license-MIT-green)

Load member records from CSV files into typed, immutable Python objects, from your own code or from the command line.

- **No dependencies.** Uses only the Python standard library.
- **Fully typed.** It ships `py.typed`, so mypy, Pyright and your editor see every type.
- **Clear errors.** Every error has a specific exception type with a line number, so problems never pass silently.
- **Streaming.** `iter_members()` parses large files one row at a time.

---

## Installation

From GitHub (works today):

```bash
pip install git+https://github.com/AlexandruSerbanescu/members-csv.git
```

From PyPI (once a release is published):

```bash
pip install members-csv
```

Requires Python 3.10 or newer.

## Quick start

```python
from members_csv import load_members

members = load_members("members.csv")

for m in members:
    print(m.id, m.full_name, m.email)
```

## CSV format

The first row must be a header containing **at least** these columns, in any order. Extra columns are ignored.

| Column       | Python type | Notes                                   |
|--------------|-------------|-----------------------------------------|
| `id`         | `int`       | Must be an integer; otherwise `InvalidRowError` |
| `first_name` | `str`       |                                         |
| `last_name`  | `str`       |                                         |
| `email`      | `str`       | Not validated                           |
| `gender`     | `str`       | Free text                               |
| `ip_address` | `str`       | Not validated                           |

Files are read as UTF-8. Whitespace around every value is stripped.

```csv
id,first_name,last_name,email,gender,ip_address
1,Ada,Lovelace,ada@example.com,Female,192.0.2.1
```

## API reference

Everything below is importable directly from `members_csv`.

### `load_members(source) -> list[Member]`

Reads the whole file and returns all members in file order.

### `iter_members(source) -> Iterator[Member]`

Same as `load_members`, but yields members one at a time, so memory use stays constant for large files. Errors are raised when the bad row is reached, not up front.

**`source`** can be:

| Value                            | Example                          | Who closes it |
|----------------------------------|----------------------------------|---------------|
| `str` path                       | `"data/members.csv"`             | the library   |
| `pathlib.Path` / `os.PathLike`   | `Path("members.csv")`            | the library   |
| Open text stream                 | `open(...)`, `io.StringIO(...)`, `sys.stdin` | you |

If you pass a stream you opened yourself, open it with `newline=""`, as the `csv` module recommends.

### `class Member`

An immutable, hashable dataclass (`frozen=True, slots=True`).

| Attribute    | Type  |
|--------------|-------|
| `id`         | `int` |
| `first_name` | `str` |
| `last_name`  | `str` |
| `email`      | `str` |
| `gender`     | `str` |
| `ip_address` | `str` |
| `full_name`  | `str` (property: `"first last"`) |

Convert a member to a dict with `dataclasses.asdict(member)`.

### `REQUIRED_COLUMNS: tuple[str, ...]`

The column names listed in [CSV format](#csv-format).

### Exceptions

```
Exception
└── MembersError              # catch this to handle every parsing problem
    ├── MissingColumnsError   # .missing: list[str] of absent column names
    └── InvalidRowError       # .line: int (1-based, header = 1), .reason: str
```

`FileNotFoundError` and other `OSError`s from opening a path are raised unchanged.

```python
from members_csv import load_members, MembersError, InvalidRowError

try:
    members = load_members(path)
except FileNotFoundError:
    ...  # path does not exist
except InvalidRowError as e:
    print(f"Bad data on line {e.line}: {e.reason}")
except MembersError as e:
    print(f"Invalid members file: {e}")
```

## Recipes

**Look up members by email**

```python
by_email = {m.email: m for m in load_members("members.csv")}
```

**Filter while streaming a large file**

```python
from members_csv import iter_members

women = [m for m in iter_members("big.csv") if m.gender == "Female"]
```

**Parse CSV text you already have (from an HTTP response, a database, …)**

```python
import io

members = load_members(io.StringIO(csv_text))
```

**Export to JSON**

```python
import dataclasses
import json

json.dumps([dataclasses.asdict(m) for m in members])
```

## Command-line usage

Installing the package adds a `members-csv` command. You can also run it as `python -m members_csv`.

```console
$ members-csv members.csv
Ada Lovelace
Alan Turing

$ members-csv members.csv --format json
[
  {
    "id": 1,
    "first_name": "Ada",
    ...
  }
]

$ cat members.csv | members-csv -
$ members-csv --version
```

| Exit code | Meaning                                         |
|-----------|-------------------------------------------------|
| `0`       | Success                                         |
| `1`       | File not found or unreadable, or the CSV is malformed (message on stderr) |
| `2`       | Invalid command-line arguments                  |

## Development

```bash
git clone https://github.com/AlexandruSerbanescu/members-csv.git
cd members-csv
python -m venv .venv && source .venv/bin/activate
pip install -e '.[dev]'

pytest                       # tests + doctests
pytest tests/test_core.py::test_missing_columns   # a single test
ruff check . && ruff format --check .
mypy
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for the release process.

## License

[MIT](LICENSE)
