<!-- HILSTER htf 4.3.1 -->
**htf 4.3.1** · [HTML](../settings.html) · [Complete PDF manual](../_downloads/htf-4.3.1.pdf)

<a id="settings"></a>

# Settings

[`htf.Settings`](#htf.Settings) is used to store and modify local settings that can easily be used within your test cases or
components. The local settings are stored in [JSON](http://www.json.org/)  or [YAML](http://yaml.org/) format.
JSON is the default format. YAML is assumed if the settings file extension is `.yml` or `.yaml`.

If no `filename` parameter is given and no [`htf.Settings`](#htf.Settings) instance exists the settings file is searched for using
the following algorithm.

First the environment variable `$HTF_SETTINGS` is checked.
If it does not exist or settings cannot be loaded, settings are searched for in `$HOME`
and the current working directory. The expected file name is `settings` followed by the extensions
`.txt`, `.json`, `.yml` or `.yaml`.

The first file that exists is loaded. If it contains errors no settings are loaded and an exception is raised.

[`htf.Settings`](#htf.Settings) behaves like a dictionary. So you can read and write values by keys, update it and iterate items.
It is also possible to access keys without indexing like these were normal attributes

```python
assert settings["key"] == settings.key  # True
```

It can be pretty-printed, too to inspect its contents.

[`htf.Settings`](#htf.Settings) is a singleton. This means that the settings are loaded once and every other
created instance is always the same.

If you want distinct instances use [`htf.SettingsNoSingleton`](#htf.SettingsNoSingleton) which offer the same behaviour without being
a singleton.

## JSON Example

A JSON settings file named `settings.json` and the contents

```json
{
    "comport": "/dev/ttyUSB0",
    "debug_flags": {
        "filename": "debug.txt",
        "level": 1
    },
    "last_updated": 1552207883,
    "report_server": "reports.hilster.io"
}
```

can easily be loaded with

```python
s = htf.Settings(filename="settings.json")
print(s)
# <htf.Settings filename='settings.yml' data={
# "comport": "/dev/ttyUSB0",
# "debug_flags": {
#     "filename": "debug.txt",
#     "level": 1
# },
# "last_updated": 1552207883,
# "report_server": "reports.hilster.io"
# }>
```

To access members use

```python
s.comport  # or
s["comport"]
```

To set a single member use

```python
s.another_comport = "/dev/ttyUSB1"  # or
s["another_comport"] = "/dev/ttyUSB1"
```

To update the settings with another dictionary or other settings use

```python
s.update(dict(a=1, b=2))
print(s)
# <htf.Settings filename='settings.json' data={
# "a": 1,
# "b": 2,
# "comport": "/dev/ttyUSB0",
# "debug_flags": {
#     "filename": "debug.txt",
#     "level": 1
# },
# "last_updated": 1552207883,
# "report_server": "reports.hilster.io"
# }>
```

To save settings use

```python
s.save()
```

## YAML Example

A YAML settings file named `settings.yml` and the contents

```yaml
# This is a comment within a settings file that JSON does not support
comport: "/dev/ttyUSB0"
debug_flags:
    filename: "debug.txt"
    level: 1
last_updated: 1552207883
report_server: "reports.hilster.io"
```

can easily be loaded with

```python
s = htf.Settings(filename="settings.yml")
print(s)
# <htf.Settings filename='settings.yml' data={
# "comport": "/dev/ttyUSB0",
# "debug_flags": {
#     "filename": "debug.txt",
#     "level": 1
# },
# "last_updated": 1552207883,
# "report_server": "reports.hilster.io"
# }>
```

Attention: when saving YAML all comments are lost!

## Create a Settings File

To create new settings use

```python
s = htf.Settings(
        filename="new_settings.yml",
        create="True",
        defaults={
            "foo": "bar",
        })
# save settings
s.save()
# cat new_settings.yml
# foo: "bar"
```

## htf.Settings

### *class* htf.Settings(\*args: [Any](https://docs.python.org/3/library/typing.html#typing.Any), \*\*kwargs: [Any](https://docs.python.org/3/library/typing.html#typing.Any))

`Settings` can be used to access local settings easily.
It is a singleton.

The local settings file is automatically searched looking in
`$HTF_SETTINGS`, `$HOME/settings.{txt,json,yml,yaml}` or `./settings.{txt,json,yml,yaml}`
in this order. If no settings file was found an exception is raised except `create` is `True`.

Settings are stored in JSON or YAML format. If the file extension is `.yml` or `.yaml`
YAML data is assumed else JSON.

Instantiate a Settings instance.

* **Parameters:**
  * **filename=None** – the filename to load explicitly
  * **create=False** – if set to `True` no exception is raised if no settings are found to create new
    settings
  * **defaults=None** – if set to a dict these values are used as default values before loading the settings
    file

#### get(key: [str](https://docs.python.org/3/builtins/stdtypes.html#str), default: [Any](https://docs.python.org/3/library/typing.html#typing.Any) | [None](https://docs.python.org/3/builtins/constants.html#None) = None) → [Any](https://docs.python.org/3/library/typing.html#typing.Any)

Get an item and return `default` if the item was not found.

* **Parameters:**
  * **key** – key for item
  * **default=None** – is returned if `key` was not found.
* **Returns:**
  self[key]
* **Return type:**
  [object](https://docs.python.org/3/builtins/functions.html#object)

#### get_filename() → [str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None)

Return the currently used settings filename.

#### get_settings_filenames() → [List](https://docs.python.org/3/library/typing.html#typing.List)[[str](https://docs.python.org/3/builtins/stdtypes.html#str)]

Return a list of possible settings filenames that are tried in order. The first available file is used.
You can overwrite this method in your specialized `Settings`.

* **Returns:**
  a list of filenames that are tried to be opened from left to right.
  : The first file that is opened will be used to read settings from.
* **Return type:**
  [list](https://docs.python.org/3/builtins/stdtypes.html#list)

#### items() → [Iterator](https://docs.python.org/3/library/typing.html#typing.Iterator)[[Any](https://docs.python.org/3/library/typing.html#typing.Any)]

Iterate over items like in a dict.

* **Returns:**
  Iterator over the items (key, value)

#### save() → [None](https://docs.python.org/3/builtins/constants.html#None)

Save current settings to current filename (useful after modification).

Attention: YAML comments are lost when overwriting an existing YAML file!

#### update(data: [Dict](https://docs.python.org/3/library/typing.html#typing.Dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)]) → [None](https://docs.python.org/3/builtins/constants.html#None)

Update settings with `data`.

* **Parameters:**
  **data** – data to use for update

## htf.SettingsNoSingleton

### *class* htf.SettingsNoSingleton(\*args: [Any](https://docs.python.org/3/library/typing.html#typing.Any), \*\*kwargs: [Any](https://docs.python.org/3/library/typing.html#typing.Any))

Settings without being a singleton.

Instantiate a Settings instance.

* **Parameters:**
  * **filename=None** – the filename to load explicitly
  * **create=False** – if set to `True` no exception is raised if no settings are found to create new
    settings
  * **defaults=None** – if set to a dict these values are used as default values before loading the settings
    file

#### get(key: [str](https://docs.python.org/3/builtins/stdtypes.html#str), default: [Any](https://docs.python.org/3/library/typing.html#typing.Any) | [None](https://docs.python.org/3/builtins/constants.html#None) = None) → [Any](https://docs.python.org/3/library/typing.html#typing.Any)

Get an item and return `default` if the item was not found.

* **Parameters:**
  * **key** – key for item
  * **default=None** – is returned if `key` was not found.
* **Returns:**
  self[key]
* **Return type:**
  [object](https://docs.python.org/3/builtins/functions.html#object)

#### get_filename() → [str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None)

Return the currently used settings filename.

#### get_settings_filenames() → [List](https://docs.python.org/3/library/typing.html#typing.List)[[str](https://docs.python.org/3/builtins/stdtypes.html#str)]

Return a list of possible settings filenames that are tried in order. The first available file is used.
You can overwrite this method in your specialized `Settings`.

* **Returns:**
  a list of filenames that are tried to be opened from left to right.
  : The first file that is opened will be used to read settings from.
* **Return type:**
  [list](https://docs.python.org/3/builtins/stdtypes.html#list)

#### items() → [Iterator](https://docs.python.org/3/library/typing.html#typing.Iterator)[[Any](https://docs.python.org/3/library/typing.html#typing.Any)]

Iterate over items like in a dict.

* **Returns:**
  Iterator over the items (key, value)

#### save() → [None](https://docs.python.org/3/builtins/constants.html#None)

Save current settings to current filename (useful after modification).

Attention: YAML comments are lost when overwriting an existing YAML file!

#### update(data: [Dict](https://docs.python.org/3/library/typing.html#typing.Dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)]) → [None](https://docs.python.org/3/builtins/constants.html#None)

Update settings with `data`.

* **Parameters:**
  **data** – data to use for update
