Skip to content

base¤

Reader ¤

Reader(file: ReadLike | str)

Bases: Root, ABC

Abstract base class for a Reader.

Parameters:

Name Type Description Default
file ReadLike | str

The file to read.

required
Source code in src/msl/io/base.py
160
161
162
163
164
165
166
167
def __init__(self, file: ReadLike | str) -> None:
    """Abstract base class for a [Reader][msl-io-readers].

    Args:
        file: The file to read.
    """
    super().__init__(file)
    self._file: ReadLike | str = file

file property ¤

file: ReadLike | str

ReadLike | str — The file object associated with the Reader.

can_read abstractmethod staticmethod ¤

can_read(file: ReadLike | str, **kwargs: Any) -> bool

Whether this Reader can read the file specified by file.

You must override this method.

Parameters:

Name Type Description Default
file ReadLike | str

The file to check whether the Reader can read it.

required
kwargs Any

Keyword arguments that the Reader class may need when checking if it can read the file.

{}

Returns:

Type Description
bool

Either True (can read) or False (cannot read).

Source code in src/msl/io/base.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
@staticmethod
@abstractmethod
def can_read(file: ReadLike | str, **kwargs: Any) -> bool:
    """Whether this [Reader][msl.io.base.Reader] can read the file specified by `file`.

    !!! warning "You must override this method."

    Args:
        file: The file to check whether the [Reader][msl.io.base.Reader] can read it.
        kwargs: Keyword arguments that the [Reader][msl.io.base.Reader] class may need
            when checking if it can read the `file`.

    Returns:
        Either `True` (can read) or `False` (cannot read).
    """

read abstractmethod ¤

read(**kwargs: Any) -> None

Read the file.

The file to read can be accessed by the file property.

You must override this method.

Parameters:

Name Type Description Default
kwargs Any

Keyword arguments that the Reader class may need when reading the file.

{}
Source code in src/msl/io/base.py
195
196
197
198
199
200
201
202
203
204
205
206
@abstractmethod
def read(self, **kwargs: Any) -> None:
    """Read the file.

    The file to read can be accessed by the [file][msl.io.base.Reader.file] property.

    !!! warning "You must override this method."

    Args:
        kwargs: Keyword arguments that the [Reader][msl.io.base.Reader] class may need
            when reading the file.
    """

Root ¤

Root(
    file: PathLike | ReadLike | WriteLike | None,
    **metadata: Any,
)

Bases: Group

The root Group.

Parameters:

Name Type Description Default
file PathLike | ReadLike | WriteLike | None

The file object to associate with the Root.

required
metadata Any

All keyword arguments are used as Metadata.

{}
Source code in src/msl/io/base.py
34
35
36
37
38
39
40
41
42
43
44
45
46
def __init__(
    self,
    file: PathLike | ReadLike | WriteLike | None,
    **metadata: Any,
) -> None:
    """The root [Group][msl.io.node.Group].

    Args:
        file: The file object to associate with the [Root][msl.io.base.Root].
        metadata: All keyword arguments are used as [Metadata][msl.io.metadata.Metadata].
    """
    super().__init__(name="/", parent=None, read_only=False, **metadata)
    self._root_file: PathLike | ReadLike | WriteLike | None = file

tree ¤

tree(*, indent: int = 2) -> str

Returns a string representation of the tree structure.

Shows all Groups and Datasets that are in Root.

Parameters:

Name Type Description Default
indent int

The amount of indentation to add for each recursive level.

2

Returns:

Type Description
str
Source code in src/msl/io/base.py
58
59
60
61
62
63
64
65
66
67
68
69
def tree(self, *, indent: int = 2) -> str:
    """Returns a string representation of the [tree structure](https://en.wikipedia.org/wiki/Tree_structure){:target="_blank"}.

    Shows all [Group][msl.io.node.Group]s and [Dataset][msl.io.node.Dataset]s that are in [Root][msl.io.base.Root].

    Args:
        indent: The amount of indentation to add for each recursive level.

    Returns:
        The [tree structure](https://en.wikipedia.org/wiki/Tree_structure){:target="_blank"}.
    """
    return repr(self) + "\n" + "\n".join(" " * (indent * k.count("/")) + repr(v) for k, v in sorted(self.items()))

Writer ¤

Writer(
    file: PathLike | WriteLike | None = None,
    **metadata: Any,
)

Bases: Root, ABC

Abstract base class for a Writer.

Parameters:

Name Type Description Default
file PathLike | WriteLike | None

The file to write the data to. Can also be specified in the write method.

None
metadata Any

All keyword arguments are used as Metadata.

{}
Source code in src/msl/io/base.py
75
76
77
78
79
80
81
82
83
84
def __init__(self, file: PathLike | WriteLike | None = None, **metadata: Any) -> None:
    """Abstract base class for a [Writer][msl-io-writers].

    Args:
        file: The file to write the data to. Can also be specified in the [write][msl.io.base.Writer.write] method.
        metadata: All keyword arguments are used as [Metadata][msl.io.metadata.Metadata].
    """
    super().__init__(file, **metadata)
    self._file: PathLike | WriteLike | None = file
    self._context_kwargs: dict[str, Any] = {}

file property ¤

file: PathLike | WriteLike | None

PathLike | WriteLike | None — The file object associated with the Writer.

save ¤

save(
    file: PathLike | WriteLike | None = None,
    *,
    root: Group | None = None,
    **kwargs: Any,
) -> None

Alias for write.

Source code in src/msl/io/base.py
136
137
138
139
140
141
142
143
144
def save(
    self,
    file: PathLike | WriteLike | None = None,
    *,
    root: Group | None = None,
    **kwargs: Any,
) -> None:
    """Alias for [write][msl.io.base.Writer.write]."""
    self.write(file=file, root=root, **kwargs)

set_root ¤

set_root(root: Group) -> None

Set a new Root for the Writer.

Info

This will clear the Metadata of the Writer and all Groups and Datasets that the Writer currently contains. The file that was specified when the Writer was created does not change.

Parameters:

Name Type Description Default
root Group

The new root.

required
Source code in src/msl/io/base.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def set_root(self, root: Group) -> None:
    """Set a new [Root][msl.io.base.Root] for the [Writer][msl.io.base.Writer].

    !!! info
        This will clear the [Metadata][msl.io.metadata.Metadata] of the [Writer][msl.io.base.Writer]
        and all [Group][msl.io.node.Group]s and [Dataset][msl.io.node.Dataset]s that the
        [Writer][msl.io.base.Writer] currently contains. The `file` that was specified when
        the [Writer][msl.io.base.Writer] was created does not change.

    Args:
        root: The new `root`.
    """
    self.clear()
    self.metadata.clear()
    self.add_metadata(**root.metadata)
    if root:  # only do this if there are Groups and/or Datasets in the new root
        self.add_group("", root)

update_context_kwargs ¤

update_context_kwargs(**kwargs: Any) -> None

Update the keyword arguments when used as a context manager.

When a Writer is used as a context manager the write method is automatically called when exiting the context manager. You can specify the keyword arguments that will be passed to the write method by calling update_context_kwargs with the appropriate keyword arguments before the context manager exits. You may call this method multiple times.

Source code in src/msl/io/base.py
109
110
111
112
113
114
115
116
117
118
119
120
def update_context_kwargs(self, **kwargs: Any) -> None:
    """Update the keyword arguments when used as a [context manager][with]{:target="_blank"}.

    When a [Writer][msl.io.base.Writer] is used as a [context manager][with]{:target="_blank"}
    the [write][msl.io.base.Writer.write] method is automatically called when exiting the
    [context manager][with]{:target="_blank"}. You can specify the keyword arguments
    that will be passed to the [write][msl.io.base.Writer.write] method by calling
    [update_context_kwargs][msl.io.base.Writer.update_context_kwargs] with the appropriate
    keyword arguments before the [context manager][with]{:target="_blank"} exits. You may
    call this method multiple times.
    """
    self._context_kwargs.update(**kwargs)

write abstractmethod ¤

write(
    file: PathLike | WriteLike | None = None,
    root: Group | None = None,
    **kwargs: Any,
) -> None

Write to a file.

You must override this method.

Parameters:

Name Type Description Default
file PathLike | WriteLike | None

The file to write the root to. If None then uses the file value that was specified when the Writer was instantiated.

None
root Group | None

Write the root object in the file format of this Writer. This argument is useful when converting between different file formats.

None
kwargs Any

Keyword arguments to use when writing the file.

{}
Source code in src/msl/io/base.py
122
123
124
125
126
127
128
129
130
131
132
133
134
@abstractmethod
def write(self, file: PathLike | WriteLike | None = None, root: Group | None = None, **kwargs: Any) -> None:
    """Write to a file.

    !!! warning "You must override this method."

    Args:
        file: The file to write the `root` to. If `None` then uses the `file` value
            that was specified when the [Writer][msl.io.base.Writer] was instantiated.
        root: Write the `root` object in the file format of this [Writer][msl.io.base.Writer].
            This argument is useful when converting between different file formats.
        kwargs: Keyword arguments to use when writing the file.
    """

read ¤

read(file: PathLike | ReadLike, **kwargs: Any) -> Reader

Read a file that has a Reader implemented.

See the Overview for an example.

Parameters:

Name Type Description Default
file PathLike | ReadLike

The file to read.

required
kwargs Any

All keyword arguments are passed to the abstract can_read and read methods.

{}

Returns:

Type Description
Reader

The data from the file.

Source code in src/msl/io/base.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def read(file: PathLike | ReadLike, **kwargs: Any) -> Reader:
    """Read a file that has a [Reader][msl-io-readers] implemented.

    !!! example "See the [Overview][read-a-file] for an example."

    Args:
        file: The file to read.
        kwargs: All keyword arguments are passed to the abstract [can_read][msl.io.base.Reader.can_read]
            and [read][msl.io.base.Reader.read] methods.

    Returns:
        The data from the file.
    """
    if isinstance(file, (bytes, str, os.PathLike)):
        file = os.fsdecode(file)
        readable = is_file_readable(file, strict=True)
    else:
        readable = hasattr(file, "read")

    if readable:
        logger.debug("finding Reader for %r", file)
        for r in _readers:
            logger.debug("checking %s", r.__name__)
            try:
                can_read = r.can_read(file, **kwargs)
            except Exception as e:  # noqa: BLE001
                logger.debug("%s: %s [%s]", e.__class__.__name__, e, r.__name__)
                continue

            if can_read:
                logger.debug("reading file with %s", r.__name__)
                root = r(file)
                root.read(**kwargs)
                root.read_only = True
                return root

    msg = f"No Reader exists to read {file!r}"
    raise OSError(msg)