jacebrowning / datafiles

A file-based ORM for Python dataclasses.
https://datafiles.readthedocs.io
MIT License
198 stars 18 forks source link

Configure a dynamic root path #319

Closed PeterSR closed 7 months ago

PeterSR commented 7 months ago

Hi! This seems like a pretty cool package and looks like a very good fit for my project, but I need to be able to read the path to the root of the files from a config file. What are my options of configuring the root dynamically?

From #17 it looks like the default is to read relative to the file the model is defined in.

It would be nice if it was possible to configure from datafile.settings, but perhaps I can just have the first key be the root and do something like


@datafile("{self.root}/my_models/{self.key}.yml")
class MyModel:

    root: str
    key: str
    ...

and make sure I have the root available everywhere I need to instantiate MyModel.

Any thoughts?

jacebrowning commented 7 months ago

If the filename is absolute (starting with a /) then you can create the synchronized files wherever you want:

https://datafiles.readthedocs.io/en/latest/api/model/#filename

So I think your approach should work. "/{self.root}/my_models/{self.key}.yml" might work as well.

Let me know if you run into any issues!

PeterSR commented 7 months ago

Thank you for the reply. Let me try it out and get back to you.

PeterSR commented 7 months ago

Hi again, just testing it out and it works like a charm!

I ended up with this setup

@dataclass
class A:
    ...

@datafile("{self.root}/config.yaml")
@dataclass(kw_only=True)
class AOrm(A):
    root: str

...

a = AOrm(root=str(some_pathlib_obj.resolve()))

Such that I can use A as a normal dataclass and type everywhere else in the application.