Skip to content

Commit 59cbfda

Browse files
committed
Doc: Add docstrings to the to/from_dict functions
This commit adds docstrings (and tests!) to the to_dict and from_dict functions. The docstrings contain examples which can be discovered and run via doctest. This commit also adds a pytest config file which enables the doctest option.
1 parent d47e514 commit 59cbfda

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

howard/__init__.py

+28
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,20 @@
77

88

99
def from_dict(d: dict, t: Generic[T]) -> T:
10+
"""
11+
Initialise an instance of the dataclass t using the values in the dict d
12+
13+
Example:
14+
15+
>>> @dataclasses.dataclass
16+
... class Person:
17+
... name: str
18+
... age: int
19+
...
20+
>>> data = {'name': 'Howard', 'age': 24}
21+
>>> from_dict(data, Person)
22+
Person(name='Howard', age=24)
23+
"""
1024
if not isinstance(d, dict):
1125
raise TypeError("First argument must be of type dict")
1226
if not dataclasses.is_dataclass(t):
@@ -16,6 +30,20 @@ def from_dict(d: dict, t: Generic[T]) -> T:
1630

1731

1832
def to_dict(obj: T, public_only=False) -> dict:
33+
"""
34+
Marshall a dataclass instance into a dict
35+
36+
Example:
37+
38+
>>> @dataclasses.dataclass
39+
... class Person:
40+
... name: str
41+
... age: int
42+
...
43+
>>> instance = Person(name='Howard', age=24)
44+
>>> to_dict(instance)
45+
{'name': 'Howard', 'age': 24}
46+
"""
1947
if not dataclasses.is_dataclass(obj):
2048
raise TypeError('Argument must be a dataclass')
2149

pytest.ini

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[pytest]
2+
addopts = --doctest-modules

0 commit comments

Comments
 (0)