Skip to content

Commit

Permalink
Provide HydepSettings.fromFile class method
Browse files Browse the repository at this point in the history
Create an instance of HydepSettings from a config file with
validation. Basically reads the file using a ConfigParser, and
passes relevant sections to updateAll.

Supports a strict argument that will either raise an error
if no appropriate settings are found, or make a warning.
  • Loading branch information
Andrew Johnson committed Mar 11, 2020
1 parent efef9d9 commit 72fb964
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/hydep/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
settings and individual solvers
"""

import warnings
import copy
import os
import pathlib
Expand Down Expand Up @@ -621,6 +622,62 @@ def validate(self):
f"{self.numFittingPoints} points"
)

@classmethod
def fromFile(
cls,
configFile: typing.Union[str, pathlib.Path],
strict: bool = True,
encoding: typing.Optional[str] = None,
):
"""Load settings directly from config file
Parameters
----------
configFile : str or pathlib.Path
File to be read containing settings
strict : bool, optional
Controls behavior if not ``hydep`` settings are found.
True [default] -> KeyError, otherwise warn
encoding : str, optional
Encoding to be used when reading the file
Returns
-------
HydepSettings
See Also
--------
*. :meth:`updateAll` - Update directly in memory
*. :meth:`validate` - Validation of settings
"""
settings = cls()

cfg = configparser.ConfigParser()
with open(configFile, encoding=encoding) as s:
cfg.read_file(s, configFile)

options = {}

for key, section in cfg.items():
if key.startswith(f"{settings.name}.") or key == settings.name:
options[key] = dict(section)

if not options:
msg = (
f"No [{settings.name}] nor [{settings.name}.*] sections "
f"found in {configFile}"
)
if strict:
raise KeyError(msg)
warnings.warn(msg, UserWarning)

settings.updateAll(options)

settings.validate()

return settings


class SerpentSettings(SubSetting, sectionName="serpent"):
"""Main settings for Serpent solver
Expand Down

0 comments on commit 72fb964

Please sign in to comment.