Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
danhje committed Jun 13, 2024
0 parents commit 967d7f5
Show file tree
Hide file tree
Showing 9 changed files with 1,604 additions and 0 deletions.
75 changes: 75 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
*.py[cod]
__pycache__

# C extensions
*.so

# Packages
*.egg
*.egg-info
dist
build
eggs
.eggs
parts
bin
var
sdist
wheelhouse
develop-eggs
.installed.cfg
lib
lib64
venv*/
pyvenv*/
pip-wheel-metadata/

# Installer logs
pip-log.txt

# Unit test / coverage reports
.coverage
.tox
.coverage.*
.pytest_cache/
nosetests.xml
coverage.xml
htmlcov

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject
.idea
*.iml
*.komodoproject

# Complexity
output/*.html
output/*/index.html

# Sphinx
docs/_build

.DS_Store
*~
.*.sw[po]
.build
.ve
.env
.cache
.pytest
.benchmarks
.bootstrap
.appveyor.token
*.bak
**/pytest.log

# Mypy Cache
.mypy_cache/

# Template specific
local.dockerfile # only for local pycharm use
21 changes: 21 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
default_language_version:
python: python3
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-json
- id: check-merge-conflict
- id: debug-statements
- id: detect-private-key
- id: check-yaml
- id: check-toml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.4
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- id: ruff-format
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2024, Statnett

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
83 changes: 83 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# grammarie

Grammarie is a type of [Fae magic](https://kingkiller.fandom.com/wiki/Fae_magic) that is the craft
of making things be. This package helps you shape your data into its proper form.

More specifically, this package defines a set of types annotated in a way that let's Pydantic validate and/or coerce
data into the target type and form.

In the example below, data is provided with wrong types and formats, but are coerced by the types defined by the model
and its fields.

```python
from datetime import UTC, datetime

from pydantic import BaseModel

from grammarie import Decimal1, IntTimestampMS, LowercaseStr, UppercaseStr


class PowerTransformer(BaseModel):
id: LowercaseStr
name: UppercaseStr
voltage_primary: Decimal1
voltage_secondary: Decimal1
installation_date: IntTimestampMS


transformers = [
PowerTransformer(
id="d37dca6f-6f23-4401-8cc8-e3ee422939e4",
name="S Ulven T1 Transformator",
voltage_primary=420.00056,
voltage_secondary="132",
installation_date="2023-05-03 11:15:01",
),
PowerTransformer(
id="26381360-959A-4D39-8049-D20889FAE0d6",
name="S Ofoten T2 Transformator",
voltage_primary="420",
voltage_secondary=300,
installation_date=datetime(2021, 8, 16, 8, 35, 1, tzinfo=UTC),
),
]

print(transformers)
# [
# PowerTransformer(
# id='d37dca6f-6f23-4401-8cc8-e3ee422939e4',
# name='S ULVEN T1 TRANSFORMATOR',
# voltage_primary=Decimal('420.0'),
# voltage_secondary=Decimal('132.0'),
# installation_date=1683105301000
# ),
# PowerTransformer(
# id='26381360-959a-4d39-8049-d20889fae0d6',
# name='S OFOTEN T2 TRANSFORMATOR',
# voltage_primary=Decimal('420.0'),
# voltage_secondary=Decimal('300.0'),
# installation_date=1629102901000
# )
# ]
```

## Installation

This package is available on PyPI and can be installed with pip, uv, pdm, poetry or any other package manager.

## Development

This project uses [Poetry](https://python-poetry.org/) to manage the environment and Python dependencies.

To install the development environment and run the test suite:
```bash
poetry install
poetry run pytest
```

It's recommended to also install the pre-commit hooks:
```bash
poetry run pre-commit install
```

This ensures that linting and formatting are run automatically on every commit.
6 changes: 6 additions & 0 deletions grammarie/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from grammarie.types import * # nopycln: import # noqa: F403

__version__ = "0.0.0"

# So users can do `from grammarie import <Type>` instead of `from grammarie.types import <Type>`
__all__ = [str(o) for o in dir() if not o.startswith("_")]
125 changes: 125 additions & 0 deletions grammarie/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
"""This module contains types and validators meant to be used with Pydantic."""

from datetime import datetime
from decimal import Decimal
from functools import partial
from typing import Annotated
from zoneinfo import ZoneInfo

from pydantic import AfterValidator, BeforeValidator, Field, TypeAdapter


def timestamp_from_dt(dt: datetime) -> float:
return dt.timestamp()


def s_to_ms(seconds: float) -> float:
return seconds * 1000


def assert_str(s: str) -> str:
"""Validate string."""
if not isinstance(s, str):
raise ValueError(f"Invalid string: {s}") # noqa: TRY004
return s


def str_to_zoneinfo(tz: str) -> ZoneInfo:
"""Validate and convert to ZoneInfo."""
try:
return ZoneInfo(tz)
except Exception as e:
raise ValueError(f"Invalid timezone string: {tz}") from e


def to_decimal(value: str | float | int | Decimal, decimal_places: int, round_digits: int | None = None) -> Decimal:
"""Converts the given value to a decimal value.
Args:
value: The value to convert.
decimal_places: The number of digits after the decimal point.
round_digits: Only use this if you want trailing zeros. For example, if you want the input rounded to the
nearest integer, but represented as a decimal with a single 0 after the decimal point, set round_digits to
0 and decimal_places to 1.
Example:
>>> to_decimal(3.14159265358979, 2)
3.12
>>> to_decimal(3.14159265358979, 2, round_digits=0)
3.00
"""
if isinstance(value, str):
value = Decimal(value)
value = round(value, round_digits if round_digits is not None else decimal_places)
return Decimal(f"{value:.{decimal_places}f}")


"""Convert to Decimal with a whole number followed by a decimal point and a single 0."""
WholeNumberDecimal = Annotated[
Decimal,
BeforeValidator(partial(to_decimal, decimal_places=1, round_digits=0)),
]

"""Convert to Decimal with 1 decimal place."""
Decimal1 = Annotated[
Decimal,
BeforeValidator(partial(to_decimal, decimal_places=1)),
]

"""Convert to Decimal with 2 decimal places."""
Decimal2 = Annotated[
Decimal,
BeforeValidator(partial(to_decimal, decimal_places=2)),
]

"""Validate string and convert to lowercase."""
LowercaseStr = Annotated[str, Field(validate_default=True), AfterValidator(str.lower)]

"""Validate string and convert to uppercase."""
UppercaseStr = Annotated[str, Field(validate_default=True), AfterValidator(str.upper)]

"""
Validate and convert to timestamp (seconds).
The input could be a datetime object, a string, a float, an int, or anything Pydantic is able to parse as a datetime.
"""
IntTimestampS = Annotated[
datetime,
Field(validate_default=True),
AfterValidator(timestamp_from_dt),
AfterValidator(int),
]

IntTimestampMS = Annotated[
datetime,
Field(validate_default=True),
AfterValidator(timestamp_from_dt),
AfterValidator(s_to_ms),
AfterValidator(int),
]

FloatTimestampS = Annotated[datetime, Field(validate_default=True), AfterValidator(timestamp_from_dt)]

FloatTimestampMS = Annotated[
datetime,
Field(validate_default=True),
AfterValidator(timestamp_from_dt),
AfterValidator(s_to_ms),
]

"""Validate a datetime string by converting to datetime and back to string."""
StrTimestampISO = Annotated[
str,
Field(validate_default=True),
BeforeValidator(assert_str),
AfterValidator(lambda s: TypeAdapter(datetime).validate_python(s)),
AfterValidator(lambda dt: dt.isoformat(sep=" ", timespec="seconds")),
]

"""Validate and convert to ZoneInfo."""
TimeZone = Annotated[ZoneInfo, Field(validate_default=True), BeforeValidator(str_to_zoneinfo)]

"""Validate timezone string."""
TimeZoneString = Annotated[str, Field(validate_default=True), AfterValidator(str_to_zoneinfo), AfterValidator(str)]
Loading

0 comments on commit 967d7f5

Please sign in to comment.