Skip to content

Commit 23a11b3

Browse files
author
notactuallyfinn
committed
add/ update comments and doc strings
1 parent 3e7c83d commit 23a11b3

7 files changed

Lines changed: 74 additions & 43 deletions

File tree

src/hermes/model/api.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from hermes.model.types.ld_container import PYTHONIZED_LD_CONTAINER
1313
from hermes.model.types.ld_context import ALL_CONTEXTS
1414
from hermes.model.types.pyld_util import bundled_loader
15+
1516
from .context_manager import HermesContext
1617
from .error import HermesContextError
1718

@@ -37,7 +38,9 @@ def __init__(
3738
Returns:
3839
None:
3940
"""
41+
# create context object
4042
ctx = ALL_CONTEXTS + [{**extra_vocabs}] if extra_vocabs is not None else ALL_CONTEXTS
43+
# initialize underlying ld_dict
4144
super().__init__([ld_dict.from_dict(data, context=ctx).data_dict if data else {}], context=ctx)
4245

4346
@classmethod
@@ -92,7 +95,9 @@ def write_to_cache(self: Self, ctx: HermesContext, target_dir: str) -> None:
9295
Returns:
9396
None:
9497
"""
98+
# open cache dir
9599
with ctx[target_dir] as cache:
100+
# write expanded, context and compact version of self
96101
cache["codemeta"] = self.compact()
97102
cache["context"] = {"@context": self.full_context}
98103
cache["expanded"] = self.ld_value

src/hermes/model/context_manager.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33
# SPDX-License-Identifier: Apache-2.0
44

55
# SPDX-FileContributor: Michael Meinel
6+
# SPDX-FileContributor: Michael Fritzsche
67

78
import json
89
import os.path
910
from pathlib import Path
1011
from types import TracebackType
11-
from typing import Union
12+
from typing import Optional
1213
from typing_extensions import Self
1314

1415
from .error import HermesContextError
@@ -42,11 +43,14 @@ def __enter__(self: Self) -> None:
4243
Returns:
4344
None:
4445
"""
46+
# check if the cache_dir exists
4547
if self._cache_dir.is_dir():
48+
# load all files from the cache dir and cache the contents
4649
for filepath in self._cache_dir.glob('*'):
4750
basename, _ = os.path.splitext(filepath.name)
4851
self._cached_data[basename] = json.load(filepath.open('r'))
4952

53+
# return the cache object
5054
return self
5155

5256
def __getitem__(self: Self, item: str) -> dict:
@@ -59,11 +63,14 @@ def __getitem__(self: Self, item: str) -> dict:
5963
Returns:
6064
dict: The JSON value in the given file.
6165
"""
66+
# check whether or not the given file was already loaded
6267
if item not in self._cached_data:
68+
# construct the file path as well as load and cache the file
6369
filepath = self._cache_dir / f'{item}.json'
6470
if filepath.is_file():
6571
self._cached_data[item] = json.load(filepath.open('r'))
6672

73+
# return the loaded json
6774
return self._cached_data[item]
6875

6976
def __setitem__(self: Self, key: str, value: dict) -> None:
@@ -78,13 +85,14 @@ def __setitem__(self: Self, key: str, value: dict) -> None:
7885
Returns:
7986
None:
8087
"""
88+
# update the value of the cache
8189
self._cached_data[key] = value
8290

8391
def __exit__(
8492
self: Self,
85-
exc_type: Union[type[BaseException], None],
86-
exc_val: Union[BaseException, None],
87-
exc_tb: Union[TracebackType, None]
93+
exc_type: Optional[type[BaseException]],
94+
exc_val: Optional[BaseException],
95+
exc_tb: Optional[TracebackType]
8896
) -> None:
8997
"""
9098
Updates the files from the cache.
@@ -98,9 +106,12 @@ def __exit__(
98106
None:
99107
"""
100108
if exc_type is None:
109+
# If the exit did not happen because of an exception:
110+
# create the cache dir (if necessary) and write the cached json data
101111
self._cache_dir.mkdir(exist_ok=True, parents=True)
102112

103113
for basename, data in self._cached_data.items():
114+
# create complete file path and write the data
104115
cachefile = self._cache_dir / f'{basename}.json'
105116
json.dump(data, cachefile.open('w'))
106117

@@ -158,10 +169,12 @@ def finalize_step(self: Self, step: str) -> None:
158169
ValueError: If no step can be removed.
159170
ValueError: If the given step is not the last one.
160171
"""
172+
# check if the given step was prepared last
161173
if len(self._current_step) < 1:
162174
raise ValueError("There is no step to end.")
163175
if self._current_step[-1] != step:
164176
raise ValueError(f"Cannot end step {step} while in {self._current_step[-1]}.")
177+
# remove the last step (i.e. the given one)
165178
self._current_step.pop()
166179

167180
def __getitem__(self: Self, source_name: str) -> HermesCache:
@@ -177,7 +190,9 @@ def __getitem__(self: Self, source_name: str) -> HermesCache:
177190
Raises:
178191
HermesContextError: If no step has been prepared (i.e. no current cache dir is set).
179192
"""
193+
# check if a step is prepared
180194
if len(self._current_step) < 1:
181195
raise HermesContextError("Prepare a step first.")
196+
# build the dir of the cache and return the HermesCache for it
182197
subdir = self.cache_dir / self._current_step[-1] / source_name
183198
return HermesCache(subdir)

src/hermes/model/merge/container.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,16 @@
77

88
from __future__ import annotations
99

10-
from typing import TYPE_CHECKING, Any, Callable, Union
10+
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
1111
from typing_extensions import Self
1212

1313
from hermes.model.types import ld_container, ld_context, ld_dict, ld_list
1414
from hermes.model.types.ld_container import (
1515
BASIC_TYPE, EXPANDED_JSON_LD_VALUE, JSON_LD_CONTEXT_DICT, JSON_LD_VALUE, TIME_TYPE
1616
)
1717
from hermes.model.types.pyld_util import bundled_loader
18-
from .action import MergeError
1918

19+
from .action import MergeError
2020
if TYPE_CHECKING:
2121
from .action import MergeAction
2222

@@ -83,11 +83,11 @@ def __init__(
8383
self: "ld_merge_list",
8484
data: Union[list[str], list[dict[str, EXPANDED_JSON_LD_VALUE]]],
8585
*,
86-
parent: Union[ld_container, None] = None,
87-
key: Union[str, None] = None,
88-
index: Union[int, None] = None,
89-
context: Union[list[Union[str, JSON_LD_CONTEXT_DICT]], None] = None,
90-
strategies: dict[Union[str, None], dict[Union[str, None], MergeAction]] = {}
86+
parent: Optional[ld_container] = None,
87+
key: Optional[str] = None,
88+
index: Optional[int] = None,
89+
context: Optional[list[Union[str, JSON_LD_CONTEXT_DICT]]] = None,
90+
strategies: dict[Optional[str], dict[Optional[str], MergeAction]] = {}
9191
) -> None:
9292
"""
9393
Create a new ld_merge_list.
@@ -124,11 +124,11 @@ def __init__(
124124
self: Self,
125125
data: list[dict[str, EXPANDED_JSON_LD_VALUE]],
126126
*,
127-
parent: Union[ld_dict, ld_list, None] = None,
128-
key: Union[str, None] = None,
129-
index: Union[int, None] = None,
130-
context: Union[list[Union[str, JSON_LD_CONTEXT_DICT]], None] = None,
131-
strategies: dict[Union[str, None], dict[Union[str, None], MergeAction]] = {}
127+
parent: Optional[Union[ld_dict, ld_list]] = None,
128+
key: Optional[str] = None,
129+
index: Optional[int] = None,
130+
context: Optional[list[Union[str, JSON_LD_CONTEXT_DICT]]] = None,
131+
strategies: dict[Optional[str], dict[Optional[str], MergeAction]] = {}
132132
) -> None:
133133
"""
134134
Create a new instance of an ld_merge_dict. See also :meth:`ld_dict.__init__`.
@@ -199,7 +199,7 @@ def update(self: Self, other: ld_dict) -> None:
199199
# this works implicitly because ld_dict.update invokes self.__setitem__ which is overwritten by ld_merge_dict
200200
super().update(other)
201201

202-
def add_strategy(self: Self, strategy: dict[Union[str, None], dict[Union[str, None], MergeAction]]) -> None:
202+
def add_strategy(self: Self, strategy: dict[Optional[str], dict[Optional[str], MergeAction]]) -> None:
203203
"""
204204
Adds ``strategy`` to the ``self.strategies``.
205205

src/hermes/model/types/ld_container.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from __future__ import annotations
1111

1212
from datetime import date, datetime, time
13-
from typing import Any, TypeAlias, TYPE_CHECKING, Union
13+
from typing import Any, Optional, TypeAlias, TYPE_CHECKING, Union
1414
from typing_extensions import Self
1515

1616
from .pyld_util import JsonLdProcessor, bundled_loader
@@ -70,10 +70,10 @@ def __init__(
7070
self: Self,
7171
data: EXPANDED_JSON_LD_VALUE,
7272
*,
73-
parent: Union[ld_dict, ld_list, None] = None,
74-
key: Union[str, None] = None,
75-
index: Union[int, None] = None,
76-
context: Union[list[Union[str, JSON_LD_CONTEXT_DICT]], None] = None,
73+
parent: Optional[Union[ld_dict, ld_list]] = None,
74+
key: Optional[str] = None,
75+
index: Optional[int] = None,
76+
context: Optional[list[Union[str, JSON_LD_CONTEXT_DICT]]] = None,
7777
) -> None:
7878
"""
7979
Create a new instance of an ld_container.
@@ -303,7 +303,7 @@ def __str__(self: Self) -> str:
303303
return str(self.to_python())
304304

305305
def compact(
306-
self: Self, context: Union[list[Union[JSON_LD_CONTEXT_DICT, str]], JSON_LD_CONTEXT_DICT, str, None] = None
306+
self: Self, context: Optional[Union[list[Union[JSON_LD_CONTEXT_DICT, str]], JSON_LD_CONTEXT_DICT, str]] = None
307307
) -> COMPACTED_JSON_LD_VALUE:
308308
"""
309309
Returns the compacted version of the given ld_container using its context only if none was supplied.

src/hermes/model/types/ld_context.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
# SPDX-FileContributor: Michael Meinel
66
# SPDX-FileContributor: Stephan Druskat <stephan.druskat@dlr.de>
7+
# SPDX-FileContributor: Michael Fritzsche
78

89
from typing import Union
910
from typing_extensions import Self
@@ -69,7 +70,7 @@ class ContextPrefix:
6970
context dict[str | None, str]: The mapping of prefix its expanded IRI.
7071
"""
7172

72-
def __init__(self: Self, vocabularies: list[str | dict]) -> None:
73+
def __init__(self: Self, vocabularies: list[Union[str, dict]]) -> None:
7374
"""
7475
If the list contains more than one string item, the last one will be used as the default vocabulary. If a prefix
7576
string is used more than once across all dictionaries in the list, the last item with this key will be included
@@ -86,10 +87,12 @@ def __init__(self: Self, vocabularies: list[str | dict]) -> None:
8687
self.vocabularies = vocabularies
8788
self.context = {}
8889

90+
# add every entry in the vocabulary to the context
8991
for vocab in self.vocabularies:
9092
if isinstance(vocab, str):
9193
vocab = {None: vocab}
9294

95+
# add all prefix, base_iri pairs from vocab to context
9396
self.context.update(
9497
{
9598
prefix: base_iri
@@ -98,7 +101,7 @@ def __init__(self: Self, vocabularies: list[str | dict]) -> None:
98101
}
99102
)
100103

101-
def __getitem__(self: Self, compressed_term: str | tuple) -> str:
104+
def __getitem__(self: Self, compressed_term: Union[str, tuple]) -> str:
102105
"""
103106
Gets the fully qualified IRI for a term from a vocabulary inside the initialized context.
104107
The vocabulary must have been added to the context at initialization.
@@ -121,7 +124,11 @@ def __getitem__(self: Self, compressed_term: str | tuple) -> str:
121124
122125
Returns:
123126
str: The fully qualified IRI for the passed term
127+
128+
Raises:
129+
HermesContextError: If the compressed term is '' or its prefix can't be expanded.
124130
"""
131+
# seperate the prefix from the term
125132
if not isinstance(compressed_term, str):
126133
prefix, term = compressed_term
127134
elif ":" in compressed_term:
@@ -133,11 +140,13 @@ def __getitem__(self: Self, compressed_term: str | tuple) -> str:
133140
else:
134141
raise HermesContextError(compressed_term)
135142

143+
# expand the prefix
136144
try:
137145
base_iri = self.context[prefix]
138146
except KeyError as ke:
139147
raise HermesContextError(prefix) from ke
140148

149+
# return the expanded term
141150
return base_iri + term
142151

143152

src/hermes/model/types/ld_dict.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from __future__ import annotations
99

1010
from collections.abc import Generator, Iterator, KeysView
11-
from typing import Any, Literal, Union, TYPE_CHECKING
11+
from typing import Any, Literal, Optional, Union, TYPE_CHECKING
1212
from typing_extensions import Self
1313

1414
from .ld_container import (
@@ -41,10 +41,10 @@ def __init__(
4141
self: Self,
4242
data: list[dict[str, EXPANDED_JSON_LD_VALUE]],
4343
*,
44-
parent: Union[ld_dict, ld_list, None] = None,
45-
key: Union[str, None] = None,
46-
index: Union[int, None] = None,
47-
context: Union[list[Union[str, JSON_LD_CONTEXT_DICT]], None] = None
44+
parent: Optional[Union[ld_dict, ld_list]] = None,
45+
key: Optional[str] = None,
46+
index: Optional[int] = None,
47+
context: Optional[list[Union[str, JSON_LD_CONTEXT_DICT]]] = None
4848
) -> None:
4949
"""
5050
Create a new instance of an ld_dict.
@@ -133,7 +133,6 @@ def __contains__(self: Self, key: str) -> bool:
133133
"""
134134
# expand the key and check if self contains a key, value pair with it
135135
full_iri = self.ld_proc.expand_iri(self.active_ctx, key)
136-
# FIXME: is that good?
137136
return full_iri in self.data_dict
138137

139138
def __eq__(
@@ -364,10 +363,10 @@ def from_dict(
364363
cls: type[Self],
365364
value: dict[str, PYTHONIZED_LD_CONTAINER],
366365
*,
367-
parent: Union[ld_dict, ld_list, None] = None,
368-
key: Union[str, None] = None,
369-
context: Union[str, JSON_LD_CONTEXT_DICT, list[Union[str, JSON_LD_CONTEXT_DICT]], None] = None,
370-
ld_type: Union[str, list[str], None] = None
366+
parent: Optional[Union[ld_dict, ld_list]] = None,
367+
key: Optional[str] = None,
368+
context: Optional[Union[str, JSON_LD_CONTEXT_DICT, list[Union[str, JSON_LD_CONTEXT_DICT]]]] = None,
369+
ld_type: Optional[Union[str, list[str]]] = None
371370
) -> ld_dict:
372371
"""
373372
Creates a ld_dict from the given dict with the given parent, key, context and ld_type.\n

src/hermes/model/types/ld_list.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from collections import deque
1313
from collections.abc import Generator, Hashable
14-
from typing import Any, Union, TYPE_CHECKING
14+
from typing import Any, Optional, Union, TYPE_CHECKING
1515
from typing_extensions import Self
1616

1717
from .ld_container import (
@@ -42,10 +42,10 @@ def __init__(
4242
self: Self,
4343
data: EXPANDED_JSON_LD_VALUE,
4444
*,
45-
parent: Union[ld_dict, ld_list, None] = None,
46-
key: Union[str, None] = None,
47-
index: Union[int, None] = None,
48-
context: Union[list[Union[str, JSON_LD_CONTEXT_DICT]], None] = None,
45+
parent: Optional[Union[ld_dict, ld_list]] = None,
46+
key: Optional[str] = None,
47+
index: Optional[int] = None,
48+
context: Optional[list[Union[str, JSON_LD_CONTEXT_DICT]]] = None,
4949
) -> None:
5050
"""
5151
Create a new instance of an ld_list.
@@ -132,6 +132,9 @@ def __setitem__(
132132
133133
Returns:
134134
None:
135+
136+
Raises:
137+
TypeError: If a slice is not assigned an iterable.
135138
"""
136139
if not isinstance(index, slice):
137140
# expand the value
@@ -582,9 +585,9 @@ def from_list(
582585
cls: type[Self],
583586
value: list[Union[JSON_LD_VALUE, BASIC_TYPE, TIME_TYPE]],
584587
*,
585-
parent: Union[ld_dict, ld_list, None] = None,
586-
key: Union[str, None] = None,
587-
context: Union[str, JSON_LD_CONTEXT_DICT, list[Union[str, JSON_LD_CONTEXT_DICT]], None] = None,
588+
parent: Optional[Union[ld_dict, ld_list]] = None,
589+
key: Optional[str] = None,
590+
context: Optional[Union[str, JSON_LD_CONTEXT_DICT, list[Union[str, JSON_LD_CONTEXT_DICT]]]] = None,
588591
container_type: str = "@set"
589592
) -> ld_list:
590593
"""

0 commit comments

Comments
 (0)