Skip to content

Commit

Permalink
allow string representation of conveted yaml #369
Browse files Browse the repository at this point in the history
  • Loading branch information
donaldcampbelljr committed Jul 12, 2024
1 parent b7a4aca commit d429294
Showing 1 changed file with 27 additions and 18 deletions.
45 changes: 27 additions & 18 deletions peppy/sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from copy import copy as cp
from logging import getLogger
from string import Formatter
from typing import Optional, Union

import pandas as pd
import yaml
Expand Down Expand Up @@ -134,31 +135,39 @@ def _obj2dict(obj, name=None):
serial.update({"prj": grab_project_data(self[PRJ_REF])})
return serial

def to_yaml(self, path, add_prj_ref=False):
def to_yaml(
self, path: Optional[str] = None, add_prj_ref=False
) -> Union[str, None]:
"""
Serializes itself in YAML format.
Serializes itself in YAML format. Writes to file if path is provided, else returns string representation.
:param str path: A file path to write yaml to; provide this or
the subs_folder_path
the subs_folder_path, defaults to None
:param bool add_prj_ref: whether the project reference bound do the
Sample object should be included in the YAML representation
:return str | None: returns string representation of sample yaml or None
"""
serial = self.to_dict(add_prj_ref=add_prj_ref)
path = os.path.expandvars(path)
if not os.path.exists(os.path.dirname(path)):
_LOGGER.warning(
"Could not write sample data to: {}. "
"Directory does not exist".format(path)
)
return
with open(path, "w") as outfile:
try:
yaml_data = yaml.safe_dump(serial, default_flow_style=False)
except yaml.representer.RepresenterError:
_LOGGER.error("Serialized sample data: {}".format(serial))
raise
outfile.write(yaml_data)
_LOGGER.debug("Sample data written to: {}".format(path))
if path:
path = os.path.expandvars(path)
if os.path.exists(os.path.dirname(path)):
with open(path, "w") as outfile:
try:
yaml_data = yaml.safe_dump(serial, default_flow_style=False)
except yaml.representer.RepresenterError:
_LOGGER.error("Serialized sample data: {}".format(serial))
raise
outfile.write(yaml_data)
_LOGGER.debug("Sample data written to: {}".format(path))
else:
_LOGGER.warning(
"Could not write sample data to: {}. "
"Directory does not exist".format(path)
)
return
else:
yaml_data = yaml.safe_dump(serial, stream=None, default_flow_style=False)
return yaml_data

def derive_attribute(self, data_sources, attr_name):
"""
Expand Down

0 comments on commit d429294

Please sign in to comment.