Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement 'repr' for 'auto' datafiles #263

Merged
merged 1 commit into from Apr 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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