Skip to content

Commit

Permalink
Merge pull request #263 from jacebrowning/auto-repr
Browse files Browse the repository at this point in the history
Implement 'repr' for 'auto' datafiles
  • Loading branch information
jacebrowning committed Apr 17, 2022
2 parents 02da937 + f3dea79 commit 7d828a4
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 12 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -3,6 +3,7 @@
## 1.4 (beta)

- Added support for accessing `Dict` keys as attributes.
- Added a proper `repr()` implementation for `auto()` datafiles.

## 1.3 (2022-04-09)

Expand Down
8 changes: 7 additions & 1 deletion datafiles/decorators.py
Expand Up @@ -45,7 +45,13 @@ def auto(filename: str, **kwargs):
kwargs["infer"] = True

path = Path.cwd() / filename
name = path.stem.strip(".").capitalize()

cls = type(path.stem.strip("."), (), {})
def auto_repr(self):
items = (f"{k}={v!r}" for k, v in self.__dict__.items() if k != "datafile")
params = ", ".join(items)
return f"{name}({params})"

cls = type(name, (), {"__repr__": auto_repr})

return datafile(str(path), **kwargs)(cls)()
17 changes: 17 additions & 0 deletions notebooks/profile_default/startup/samples.py
@@ -0,0 +1,17 @@
from datafiles import datafile, auto, Missing


@datafile("./notebooks/files/items/{self.name}.yml")
class InventoryItem:
"""Class for keeping track of an item in inventory."""

name: str
unit_price: float
quantity_on_hand: int = 0

def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand


item = InventoryItem("foobar", Missing)
sample = auto("./notebooks/files/sample.yml")
20 changes: 12 additions & 8 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions pyproject.toml
@@ -1,7 +1,7 @@
[tool.poetry]

name = "datafiles"
version = "1.4b1"
version = "1.4b2"
description = "File-based ORM for dataclasses."

license = "MIT"
Expand Down Expand Up @@ -44,8 +44,8 @@ classifiers = [
python = "^3.7"

# Formats
"ruamel.yaml" = "^0.17.20"
tomlkit = "^0.7.2"
"ruamel.yaml" = "^0.17.21"
tomlkit = "^0.10.1"

# ORM
parse = "^1.12"
Expand Down
16 changes: 16 additions & 0 deletions tests/test_file_inference.py
Expand Up @@ -7,6 +7,22 @@


def describe_auto():
def it_implements_repr(expect):
write(
"tmp/sample.yml",
"""
items:
- 1
- 2
value: abc
""",
)

logbreak("Inferring object")
sample = auto("tmp/sample.yml")

expect(repr(sample)) == "Sample(items=[1, 2], value='abc')"

@pytest.mark.parametrize(
("filename", "count"),
[
Expand Down

0 comments on commit 7d828a4

Please sign in to comment.