Skip to content

Commit

Permalink
Merge pull request #13499 from eerovaher/config-help
Browse files Browse the repository at this point in the history
Implement a `help()` method for the configuration system
  • Loading branch information
pllim committed Oct 6, 2023
2 parents d7ab377 + 4a477d0 commit 1ae2784
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 12 deletions.
39 changes: 39 additions & 0 deletions astropy/config/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,14 @@ def __iter__(self):
if isinstance(val, ConfigItem):
yield key

def __str__(self):
try:
header = f"{self.__doc__.strip()}\n\n"
except AttributeError:
current_module = str(find_current_module(2)).split("'")[1]
header = f"Configuration parameters for `{current_module}`\n\n"
return header + "\n\n".join(map(str, self.values()))

keys = __iter__
"""Iterate over configuration item names."""

Expand All @@ -127,6 +135,37 @@ def items(self):
if isinstance(val, ConfigItem):
yield key, val

def help(self, name=None):
"""Print info about configuration items.
Parameters
----------
name : `str`, optional
Name of the configuration item to be described. If no name is
provided then info about all the configuration items will be
printed.
Examples
--------
>>> from astropy import conf
>>> conf.help("unicode_output")
ConfigItem: unicode_output
cfgtype='boolean'
defaultvalue=False
description='When True, use Unicode characters when outputting values, and displaying widgets at the console.'
module=astropy
value=False
"""
if name is None:
print(self)
else:
try:
print(type(self).__dict__[name])
except KeyError:
raise KeyError(
f"'{name}' is not among configuration items {tuple(self)}"
) from None

def set_temp(self, attr, value):
"""
Temporarily set a configuration value.
Expand Down
51 changes: 51 additions & 0 deletions astropy/config/tests/test_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import subprocess
import sys
from inspect import cleandoc

import pytest

Expand Down Expand Up @@ -243,6 +244,19 @@ class Conf(ConfigNamespace):

assert conf.tstnm == 34

assert str(conf) == cleandoc(
"""
Configuration parameters for `astropy.config.tests.test_configs`
ConfigItem: tstnm
cfgtype='integer'
defaultvalue=34
description='this is a Description'
module=astropy.config.tests.test_configs
value=34
"""
)

sec = get_config(ci.module)
assert sec["tstnm"] == 34

Expand Down Expand Up @@ -344,6 +358,43 @@ class Conf(ConfigNamespace):
assert "tstnmo = op2" in lns


def test_help(capsys):
from astropy import conf

use_color_msg = cleandoc(
"""
ConfigItem: use_color
cfgtype='boolean'
defaultvalue={is_not_windows}
description='When True, use ANSI color escape sequences when writing to the console.'
module=astropy
value={is_not_windows}
"""
).format(is_not_windows=sys.platform != "win32")
conf.help("use_color")
assert capsys.readouterr().out == use_color_msg + "\n"

conf.help()
help_text = capsys.readouterr().out
assert help_text.startswith(
"Configuration parameters for `astropy`.\n\nConfigItem: unicode_output"
)
assert use_color_msg in help_text


def test_help_invalid_config_item():
from astropy import conf

with pytest.raises(
KeyError,
match=(
"'bad_name' is not among configuration items "
r"\('unicode_output', 'use_color', 'max_lines', 'max_width'\)"
),
):
conf.help("bad_name")


def test_config_noastropy_fallback(monkeypatch):
"""
Tests to make sure configuration items fall back to their defaults when
Expand Down
2 changes: 2 additions & 0 deletions docs/changes/config/13499.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
The new ``ConfigNamespace.help()`` method provides a convenient way to get
information about configuration items.
37 changes: 25 additions & 12 deletions docs/config/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -220,22 +220,35 @@ To see what configuration parameters are defined for a given ``conf``::
'auto_max_age',
...,
'ietf_leap_second_auto_url']
>>> conf.auto_max_age
30.0

You can see more detailed information about a configuration parameter by
calling the :meth:`~astropy.config.ConfigNamespace.help` method::

>>> conf.help("auto_max_age")
ConfigItem: auto_max_age
cfgtype='float'
defaultvalue=30.0
description='Maximum age (days) of predictive data before auto-downloading. See "Auto refresh behavior" in astropy.utils.iers documentation for details. Default is 30.'
module=astropy.utils.iers.iers
value=30.0

You can see information about all the configuration parameters by calling
:meth:`~astropy.config.ConfigNamespace.help` without arguments::

>>> conf.help()
Configuration parameters for `astropy.utils.iers`.
<BLANKLINE>
ConfigItem: auto_download
cfgtype='boolean'
...

You can also iterate through ``conf`` in a dictionary-like fashion::

>>> list(conf.values())
[<ConfigItem: name='auto_download' value=True at ...>,
<ConfigItem: name='auto_max_age' value=30.0 at ...>,
...,
<ConfigItem: name='ietf_leap_second_auto_url' value=...>]
>>> for (key, cfgitem) in conf.items():
... if key == 'auto_max_age':
... print(f'{cfgitem.description} Value is {cfgitem()}')
Maximum age (days) of predictive data before auto-downloading. See "Auto
refresh behavior" in astropy.utils.iers documentation for details. Default
is 30. Value is 30.0
... print(f'{key} default value is {cfgitem.defaultvalue}')
auto_download default value is True
auto_max_age default value is 30.0
...

Upgrading ``astropy``
---------------------
Expand Down

0 comments on commit 1ae2784

Please sign in to comment.