Container Types

Various container types are supported to defined collections of objects.

Lists

The List annotation can be used to define a homogeneous collection of any other type.

from typing import List, Optional
Type Annotation Python Value YAML Content
foobar: List[int] foobar = [] foobar:
    -
foobar: List[int] foobar = [1.23] foobar:
    - 1
foobar: List[int] foobar = None foobar:
    -
foobar: Optional[List[int]] foobar = None foobar:

More examples can be found in this Jupyter Notebook.

Sets

The Set annotation can be used to define a homogeneous collection of unique elements of any other type.

from typing import Set, Optional
Type Annotation Python Value YAML Content
foobar: Set[int] foobar = [] foobar:
    -
foobar: Set[int] foobar = [1.23] foobar:
    - 1
foobar: Set[int] foobar = None foobar:
    -
foobar: Optional[Set[int]] foobar = None foobar:

Dictionaries

The Dict annotation can be used to define a loose mapping of multiple types.

from typing import Dict, Optional
Type Annotation Python Value YAML Content
foobar: Dict[str, int] foobar = {} foobar: {}
foobar: Dict[str, int] foobar = {"a": 42} foobar:
    a: 42
foobar: Dict[str, int] foobar = None foobar: {}
foobar: Optional[Dict[str, int]] foobar = None foobar:

⚠ Schema enforcement is not available with the Dict annotation.

Dataclasses

Other dataclasses can serve as the annotation for an attribute to create nested structure:

from dataclasses import dataclass

from datafiles import datafile


@dataclass
class Nested:
    qux: str


@datafile("sample.yml")
class Sample:
    foo: int
    bar: Nested

which can be constructed like so:

sample = Sample(42, Nested("Hello, world!"))

to save this sample.yml file:

foo: 42
bar:
  qux: Hello, world!

For convenience, @datafile can also be used in place of @dataclass to minimize the number of imports:

from datafiles import datafile


@datafile
class Nested:
    qux: str

More examples can be found in this Jupyter Notebook.