Skip to content

Commit

Permalink
SinglefileData: Add the from_string classmethod (#6022)
Browse files Browse the repository at this point in the history
This allows the construction of a `SinglefileData` from content that is
already in memory as a `str`. Although this was already possible through
`SinglefileData(io.StringIO(content))`, the classmethod has advantages:

* No need for separate import of `io`
* Method can be found easily through introspection
* Overall is more intuitive than turning string content into a stream
  • Loading branch information
sphuber committed May 17, 2023
1 parent 220a65c commit c25de61
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions aiida/orm/nodes/data/singlefile.py
Expand Up @@ -11,6 +11,7 @@
from __future__ import annotations

import contextlib
import io
import os
import pathlib

Expand All @@ -26,6 +27,15 @@ class SinglefileData(Data):

DEFAULT_FILENAME = 'file.txt'

@classmethod
def from_string(cls, content: str, filename: str | pathlib.Path | None = None, **kwargs):
"""Construct a new instance and set ``content`` as its contents.
:param content: The content as a string.
:param filename: Specify filename to use (defaults to ``file.txt``).
"""
return cls(io.StringIO(content), filename, **kwargs)

def __init__(self, file, filename: str | pathlib.Path | None = None, **kwargs):
"""Construct a new instance and set the contents to that of the file.
Expand Down
14 changes: 14 additions & 0 deletions tests/orm/nodes/data/test_singlefile.py
Expand Up @@ -184,3 +184,17 @@ def test_binary_file(check_singlefile_content_with_store):
filename=basename,
open_mode='rb',
)


def test_from_string():
"""Test the :meth:`aiida.orm.nodes.data.singlefile.SinglefileData.from_string` classmethod."""
content = 'some\ncontent'
node = SinglefileData.from_string(content).store()
assert node.get_content() == content
assert node.filename == SinglefileData.DEFAULT_FILENAME

content = 'some\ncontent'
filename = 'custom_filename.dat'
node = SinglefileData.from_string(content, filename).store()
assert node.get_content() == content
assert node.filename == filename

0 comments on commit c25de61

Please sign in to comment.