Option Types#

Types for creating section definitions.

A section definition consists of a subclass of StaticSection, on which any number of subclasses of BaseValidated (a few common ones of which are available in this module) are assigned as attributes. These descriptors define how to read values from, and write values to, the config file.

As an example, if one wanted to define the [spam] section as having an eggs option, which contains a list of values, they could do this:

>>> class SpamSection(StaticSection):
...     eggs = ListAttribute('eggs')
...
>>> SpamSection(config, 'spam')
>>> print(config.spam.eggs)
[]
>>> config.spam.eggs = ['goose', 'turkey', 'duck', 'chicken', 'quail']
>>> print(config.spam.eggs)
['goose', 'turkey', 'duck', 'chicken', 'quail']
>>> config.spam.eggs = 'herring'
Traceback (most recent call last):
    ...
ValueError: ListAttribute value must be a list.
class sopel.config.types.BaseValidated(name, default=None, is_secret=False)#

The base type for a setting descriptor in a StaticSection.

Parameters:
  • name (str) – the attribute name to use in the config file

  • default (mixed) – the value to be returned if the setting has no value (optional; defaults to None)

  • is_secret (bool) – tell if the attribute is secret/a password (optional; defaults to False)

default also can be set to sopel.config.types.NO_DEFAULT, if the value must be configured by the user (i.e. there is no suitable default value). Trying to read an empty NO_DEFAULT value will raise AttributeError.

Important

Setting names SHOULD follow snake_case naming rules:

  • use only lowercase letters, digits, and underscore (_)

  • SHOULD NOT start with a digit

Deviations from snake_case can break the following operations:

configure(prompt, default, parent, section_name)#

Parse and return a value from user’s input.

Parameters:
  • prompt (str) – text to show the user

  • default (mixed) – default value used if no input given

  • parent (Config) – usually the parent Config object

  • section_name (str) – the name of the containing section

This method displays the prompt and waits for user’s input on the terminal. If no input is provided (i.e. the user just presses “Enter”), the default value is returned instead.

If is_secret is True, the input will be hidden, using the built-in getpass() function.

default#

Default value for this attribute.

If not specified, the attribute’s default value will be None.

is_secret#

Tell if the attribute is secret/a password.

The default value is False (not secret).

Sopel’s configuration can contain passwords, secret keys, and other private information that must be treated as sensitive data. Such options should be marked as “secret” with this attribute.

name#

Name of the attribute.

abstract parse(value, *args, **kwargs)#

Take a string from the file, and return the appropriate object.

abstract serialize(value, *args, **kwargs)#

Take some object, and return the string to be saved to the file.

class sopel.config.types.BooleanAttribute(name, default=False)#

A descriptor for Boolean settings in a StaticSection.

Parameters:
  • name (str) – the attribute name to use in the config file

  • default (bool) – the default value to use if this setting is not present in the config file

If the default value is not specified, it will be False.

configure(prompt, default, parent, section_name)#

Parse and return a value from user’s input.

Parameters:
  • prompt (str) – text to show the user

  • default (bool) – default value used if no input given

  • parent (Config) – usually the parent Config object

  • section_name (str) – the name of the containing section

This method displays the prompt and waits for user’s input on the terminal. If no input is provided (i.e. the user just presses “Enter”), the default value is returned instead.

parse(value)#

Parse a limited set of values/objects into Boolean representations.

Parameters:

value (mixed) – the value to parse

The literal values True or 1 will be parsed as True. The strings '1', 'yes', 'y', 'true', 'enable', 'enabled', and 'on' will also be parsed as True, regardless of case. All other values will be parsed as False.

serialize(value)#

Convert a Boolean value to a string for saving to the config file.

Parameters:

value (bool) – the value to serialize

class sopel.config.types.ChoiceAttribute(name, choices, default=None)#

A config attribute which must be one of a set group of options.

Parameters:
  • name (str) – the attribute name to use in the config file

  • choices (list or tuple) – acceptable values; currently, only strings are supported

  • default (str) – which choice to use if none is set in the config file; to require explicit configuration, use sopel.config.types.NO_DEFAULT (optional)

parse(value)#

Check the loaded value against the valid choices.

Parameters:

value (str) – the value loaded from the config file

Returns:

the value, if it is valid

Return type:

str

Raises:

ValueError – if value is not one of the valid choices

serialize(value)#

Make sure value is valid and safe to write in the config file.

Parameters:

value (str) – the value needing to be saved

Returns:

the value, if it is valid

Return type:

str

Raises:

ValueError – if value is not one of the valid choices

class sopel.config.types.FilenameAttribute(name, relative=True, directory=False, default=None)#

A config attribute which must be a file or directory.

Parameters:
  • name (str) – the attribute name to use in the config file

  • relative (bool) – whether the path should be relative to the location of the config file (optional; note that absolute paths will always be interpreted as absolute)

  • directory (bool) – whether the path should indicate a directory, rather than a file (optional)

  • default (str) – the value to use if none is defined in the config file; to require explicit configuration, use sopel.config.types.NO_DEFAULT (optional)

parse(value)#

Parse value as a path on the filesystem to check.

Parameters:

value (str) – the path to check

Return type:

str

Raises:

ValueError – if the directory or file doesn’t exist and cannot be created

If there is no value, then this returns None. Otherwise, it’ll check if the directory or file exists. If it doesn’t, it’ll try to create it.

serialize(value)#

Directly return the value without modification.

Parameters:

value (str) – the value needing to be saved

Returns:

the unaltered value, if it is valid

Return type:

str

Managing the filename is done by other methods (parse()), and this method is a no-op: this way it ensures that relative paths won’t be replaced by absolute ones.

class sopel.config.types.ListAttribute(name, strip=True, default=None)#

A config attribute containing a list of string values.

Parameters:
  • name (str) – the attribute name to use in the config file

  • strip (bool) – whether to strip whitespace from around each value (optional, deprecated; applies only to legacy comma-separated lists; multi-line lists are always stripped)

  • default (list) – the default value if the config file does not define a value for this option; to require explicit configuration, use sopel.config.types.NO_DEFAULT (optional)

From this StaticSection:

class SpamSection(StaticSection):
    cheeses = ListAttribute('cheeses')

the option will be exposed as a Python list:

>>> config.spam.cheeses
['camembert', 'cheddar', 'reblochon', '#brie']

which comes from this configuration file:

[spam]
cheeses =
    camembert
    cheddar
    reblochon
    "#brie"

Note that the #brie item starts with a #, hence the double quote: without these quotation marks, the config parser would think it’s a comment. The quote/unquote is managed automatically by this field, and if and only if it’s necessary (see parse() and serialize()).

Changed in version 7.0: The option’s value will be split on newlines by default. In this case, the strip parameter has no effect.

See the parse() method for more information.

Note

About: backward compatibility with comma-separated values.

A ListAttribute option used to allow to write, on a single line, the values separated by commas. It is still technically possible while raising a deprecation warning.

In Sopel 7.x this behavior was discouraged; as of Sopel 8.x it is now deprecated with warnings, and it will be removed in Sopel 9.x.

Bot owners should update their configurations to use newlines instead of commas.

The comma delimiter fallback does not support commas within items in the list.

DELIMITER = ','#
QUOTE_REGEX = re.compile('^"(?P<value>#.*)"$')#

Regex pattern to match value that requires quotation marks.

This pattern matches values that start with # inside quotation marks only: "#sopel" will match, but "sopel" won’t, and neither will any variant that doesn’t conform to this pattern.

configure(prompt, default, parent, section_name)#

Parse and return a value from user’s input.

Parameters:
  • prompt (str) – text to show the user

  • default (mixed) – default value used if no input given

  • parent (Config) – usually the parent Config object

  • section_name (str) – the name of the containing section

This method displays the prompt and waits for user’s input on the terminal. If no input is provided (i.e. the user just presses “Enter”), the default value is returned instead.

If is_secret is True, the input will be hidden, using the built-in getpass() function.

parse(value)#

Parse value into a list.

Parameters:

value (str) – a multi-line string of values to parse into a list

Returns:

a list of items from value

Return type:

list

Changed in version 7.0: The value is now split on newlines, with fallback to comma when there is no newline in value.

When modified and saved to a file, items will be stored as a multi-line string (see serialize()).

Changed in version 8.0: When the value contains a delimiter without newline, it warns the user to switch to a multi-line value, without a delimiter.

parse_item(item)#

Parse one item from the list.

Parameters:

item (str) – one item from the list to parse

Return type:

str

If item matches the QUOTE_REGEX pattern, then it will be unquoted. Otherwise it’s returned as-is.

serialize(value)#

Serialize value into a multi-line string.

Parameters:

value (list) – the input list

Return type:

str

Raises:

ValueError – if value is the wrong type (i.e. not a list)

serialize_item(item)#

Serialize an item from the list value.

Parameters:

item (str) – one item of the list to serialize

Return type:

str

If item starts with a # it will be quoted in order to prevent the config parser from thinking it’s a comment.

class sopel.config.types.NO_DEFAULT#

A special value to indicate that there should be no default.

class sopel.config.types.SecretAttribute(name, parse=None, serialize=None, default=None)#

A config attribute containing a value which must be kept secret.

This attribute is always considered to be secret/sensitive data, but otherwise behaves like other any option.

class sopel.config.types.StaticSection(config, section_name, validate=True)#

A configuration section with parsed and validated settings.

This class is intended to be subclassed and customized with added attributes containing BaseValidated-based objects.

Note

By convention, subclasses of StaticSection are named with the plugin’s name in CamelCase, plus the suffix Section. For example, a plugin named editor might name its subclass EditorSection; a do_stuff plugin might name its subclass DoStuffSection (its name converted from snake_case to CamelCase).

However, this is only a convention. Any class name that is legal in Python will work just fine.

configure_setting(name, prompt, default=NO_DEFAULT)#

Return a validated value for this attribute from the terminal.

Parameters:
  • name (str) – the name of the attribute to configure

  • prompt (str) – the prompt text to display in the terminal

  • default (depends on subclass) – the value to be used if the user does not enter one

If default is passed, it will be used if no value is given by the user. If it is not passed, the current value of the setting, or the default value if it’s unset, will be used. Note that if default is passed, the current value of the setting will be ignored, even if it is not the attribute’s default.

class sopel.config.types.ValidatedAttribute(
name,
parse=None,
serialize=None,
default=None,
is_secret=False,
)#

A descriptor for settings in a StaticSection.

Parameters:
  • name (str) – the attribute name to use in the config file

  • parse (function) – a function to be used to read the string and create the appropriate object (optional; the string value will be returned as-is if not set)

  • serialize (function) – a function that, given an object, should return a string that can be written to the config file safely (optional; defaults to str)

  • is_secret (bool) – True when the attribute should be considered a secret, like a password (default to False)

configure(prompt, default, parent, section_name)#

Parse and return a value from user’s input.

Parameters:
  • prompt (str) – text to show the user

  • default (mixed) – default value used if no input given

  • parent (Config) – usually the parent Config object

  • section_name (str) – the name of the containing section

This method displays the prompt and waits for user’s input on the terminal. If no input is provided (i.e. the user just presses “Enter”), the default value is returned instead.

If is_secret is True, the input will be hidden, using the built-in getpass() function.

parse(value)#

No-op: simply returns the given value, unchanged.

Parameters:

value (str) – the string read from the config file

Return type:

str

serialize(value)#

Return the value as a Unicode string.

Parameters:

value – the option value

Return type:

str