Top

goulash.settings module

goulash.settings

Standard configuration parser suitable to inherit for all kinds of applications. This parses ini files and command line options, then combines the information. As a result of having all the information it is convenient (if not exactly correct) to treat the settings object as an "entry point".

""" goulash.settings

    Standard configuration parser suitable to inherit
    for all kinds of applications.  This parses ini files
    and command line options, then combines the information.
    As a result of having all the information it is convenient
    (if not exactly correct) to treat the settings object
    as an "entry point".
"""
import os
import configparser
from argparse import ArgumentParser

class SettingsError(Exception):
    pass

class GoulashConfigParser(configparser.ConfigParser):
    pass

class Settings(object):

    default_file = None
    environ_key = None
    #__getitem__ = Dictionaryish.__getitem__

    def get_parser(self):
        """ build the default parser """
        parser = ArgumentParser()
        parser.add_argument(
            "-c", default='', dest='cmd',
            help=("just like python -c or sh -c (pass in a command)"))
        parser.add_argument(
            "-e", "--exec", default='', dest='execfile',
            help='a filename to execute')
        parser.add_argument(
            "-v", '--version', default=False, dest='version',
            action='store_true',
            help=("show version information"))
        parser.add_argument("--shell", dest="shell",
                          default=False, help="application shell",
                          action='store_true')
        parser.add_argument("--config", dest='config',
                          default="",
                          help="use config file")
        return parser

    def get_section(self, k, insist=False):
        try:
            return dict(self._wrapped)[k]
        except KeyError:
            if insist:
                error = 'Fatal: You need to specify a "{0}" section in {1}'
                raise SettingsError(error.format(k, self.settings_file))
            else:
                return None

    def get_setting(self, k, insist=False, default=None):
        """ TODO: move into goulash
            this function returns True for 'true', False for
            `false` or 'no', any other strings are passed through
        """
        _type = 'val'
        section, var = k.split('.')
        section_obj = self.get_section(section, insist=insist)
        try:
            tmp = section_obj[var]
        except KeyError:
            if insist:
                error = ('Fatal: You need to specify a "{0}" section '
                         'with an entry like  "{1}=<{2}>" in {3}')
                raise SettingsError(error.format(
                    section, var, _type, self.settings_file))
            elif default:
                tmp = default
            else:
                return None
        if isinstance(tmp, basestring):
            test = tmp not in ['0', 'false', 'no', 0]
            if not test:
                return test
        return tmp

    @property
    def settings_file(self):
        if self.options is not None and self.options.config:
            _file = self.options.config
        else:
            _file = self._init_filename or \
                    os.environ.get(self.environ_key) or \
                    self.default_file
        _file = os.path.expanduser(_file)
        return _file

    def pre_run(self):
        """ hook for subclassers.. """
        pass

    def load(self, file, config={}):
        """ returns a dictionary with key's of the form
            
.

Classes

class GoulashConfigParser

class GoulashConfigParser(configparser.ConfigParser):
    pass

Ancestors (in MRO)

  • GoulashConfigParser
  • backports.configparser.ConfigParser
  • backports.configparser.RawConfigParser
  • _abcoll.MutableMapping
  • _abcoll.Mapping
  • _abcoll.Sized
  • _abcoll.Iterable
  • _abcoll.Container
  • __builtin__.object

Class variables

var BOOLEAN_STATES

var NONSPACECRE

var OPTCRE

var OPTCRE_NV

var SECTCRE

Methods

def __init__(

self, defaults=None, dict_type=<class 'collections.OrderedDict'>, allow_no_value=False, **kwargs)

def __init__(self, defaults=None, dict_type=_default_dict,
             allow_no_value=False, **kwargs):
    # keyword-only arguments
    delimiters = kwargs.get('delimiters', ('=', ':'))
    comment_prefixes = kwargs.get('comment_prefixes', ('#', ';'))
    inline_comment_prefixes = kwargs.get('inline_comment_prefixes', None)
    strict = kwargs.get('strict', True)
    empty_lines_in_values = kwargs.get('empty_lines_in_values', True)
    default_section = kwargs.get('default_section', DEFAULTSECT)
    interpolation = kwargs.get('interpolation', _UNSET)
    self._dict = dict_type
    self._sections = self._dict()
    self._defaults = self._dict()
    self._proxies = self._dict()
    self._proxies[default_section] = SectionProxy(self, default_section)
    if defaults:
        for key, value in defaults.items():
            self._defaults[self.optionxform(key)] = value
    self._delimiters = tuple(delimiters)
    if delimiters == ('=', ':'):
        self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
    else:
        d = "|".join(re.escape(d) for d in delimiters)
        if allow_no_value:
            self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
                                      re.VERBOSE)
        else:
            self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
                                      re.VERBOSE)
    self._comment_prefixes = tuple(comment_prefixes or ())
    self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
    self._strict = strict
    self._allow_no_value = allow_no_value
    self._empty_lines_in_values = empty_lines_in_values
    self.default_section=default_section
    self._interpolation = interpolation
    if self._interpolation is _UNSET:
        self._interpolation = self._DEFAULT_INTERPOLATION
    if self._interpolation is None:
        self._interpolation = Interpolation()

def add_section(

self, section)

Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.

def add_section(self, section):
    """Create a new section in the configuration.  Extends
    RawConfigParser.add_section by validating if the section name is
    a string."""
    section, _, _ = self._validate_value_types(section=section)
    super(ConfigParser, self).add_section(section)

def clear(

self)

D.clear() -> None. Remove all items from D.

def clear(self):
    'D.clear() -> None.  Remove all items from D.'
    try:
        while True:
            self.popitem()
    except KeyError:
        pass

def defaults(

self)

def defaults(self):
    return self._defaults

def get(

self, section, option, **kwargs)

Get an option value for a given section.

If vars' is provided, it must be a dictionary. The option is looked up invars' (if provided), section', and inDEFAULTSECT' in that order. If the key is not found and fallback' is provided, it is used as a fallback value.None' can be provided as a `fallback' value.

If interpolation is enabled and the optional argument `raw' is False, all interpolations are expanded in the return values.

Arguments raw',vars', and `fallback' are keyword only.

The section DEFAULT is special.

def get(self, section, option, **kwargs):
    """Get an option value for a given section.
    If `vars' is provided, it must be a dictionary. The option is looked up
    in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
    If the key is not found and `fallback' is provided, it is used as
    a fallback value. `None' can be provided as a `fallback' value.
    If interpolation is enabled and the optional argument `raw' is False,
    all interpolations are expanded in the return values.
    Arguments `raw', `vars', and `fallback' are keyword only.
    The section DEFAULT is special.
    """
    # keyword-only arguments
    raw = kwargs.get('raw', False)
    vars = kwargs.get('vars', None)
    fallback = kwargs.get('fallback', _UNSET)
    try:
        d = self._unify_values(section, vars)
    except NoSectionError:
        if fallback is _UNSET:
            raise
        else:
            return fallback
    option = self.optionxform(option)
    try:
        value = d[option]
    except KeyError:
        if fallback is _UNSET:
            raise NoOptionError(option, section)
        else:
            return fallback
    if raw or value is None:
        return value
    else:
        return self._interpolation.before_get(self, section, option, value,
                                              d)

def getboolean(

self, section, option, **kwargs)

def getboolean(self, section, option, **kwargs):
    # keyword-only arguments
    raw = kwargs.get('raw', False)
    vars = kwargs.get('vars', None)
    fallback = kwargs.get('fallback', _UNSET)
    try:
        return self._get(section, self._convert_to_boolean, option,
                         raw=raw, vars=vars)
    except (NoSectionError, NoOptionError):
        if fallback is _UNSET:
            raise
        else:
            return fallback

def getfloat(

self, section, option, **kwargs)

def getfloat(self, section, option, **kwargs):
    # keyword-only arguments
    raw = kwargs.get('raw', False)
    vars = kwargs.get('vars', None)
    fallback = kwargs.get('fallback', _UNSET)
    try:
        return self._get(section, float, option, raw=raw, vars=vars)
    except (NoSectionError, NoOptionError):
        if fallback is _UNSET:
            raise
        else:
            return fallback

def getint(

self, section, option, **kwargs)

def getint(self, section, option, **kwargs):
    # keyword-only arguments
    raw = kwargs.get('raw', False)
    vars = kwargs.get('vars', None)
    fallback = kwargs.get('fallback', _UNSET)
    try:
        return self._get(section, int, option, raw=raw, vars=vars)
    except (NoSectionError, NoOptionError):
        if fallback is _UNSET:
            raise
        else:
            return fallback

def has_option(

self, section, option)

Check for the existence of a given option in a given section. If the specified section' is None or an empty string, DEFAULT is assumed. If the specifiedsection' does not exist, returns False.

def has_option(self, section, option):
    """Check for the existence of a given option in a given section.
    If the specified `section' is None or an empty string, DEFAULT is
    assumed. If the specified `section' does not exist, returns False."""
    if not section or section == self.default_section:
        option = self.optionxform(option)
        return option in self._defaults
    elif section not in self._sections:
        return False
    else:
        option = self.optionxform(option)
        return (option in self._sections[section]
                or option in self._defaults)

def has_section(

self, section)

Indicate whether the named section is present in the configuration.

The DEFAULT section is not acknowledged.

def has_section(self, section):
    """Indicate whether the named section is present in the configuration.
    The DEFAULT section is not acknowledged.
    """
    return section in self._sections

def items(

self, section=<object object at 0xb74755d8>, raw=False, vars=None)

Return a list of (name, value) tuples for each option in a section.

All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument raw' is true. Additional substitutions may be provided using thevars' argument, which must be a dictionary whose contents overrides any pre-existing defaults.

The section DEFAULT is special.

def items(self, section=_UNSET, raw=False, vars=None):
    """Return a list of (name, value) tuples for each option in a section.
    All % interpolations are expanded in the return values, based on the
    defaults passed into the constructor, unless the optional argument
    `raw' is true.  Additional substitutions may be provided using the
    `vars' argument, which must be a dictionary whose contents overrides
    any pre-existing defaults.
    The section DEFAULT is special.
    """
    if section is _UNSET:
        return super(RawConfigParser, self).items()
    d = self._defaults.copy()
    try:
        d.update(self._sections[section])
    except KeyError:
        if section != self.default_section:
            raise NoSectionError(section)
    # Update with the entry specific variables
    if vars:
        for key, value in vars.items():
            d[self.optionxform(key)] = value
    value_getter = lambda option: self._interpolation.before_get(self,
        section, option, d[option], d)
    if raw:
        value_getter = lambda option: d[option]
    return [(option, value_getter(option)) for option in d.keys()]

def iteritems(

self)

D.iteritems() -> an iterator over the (key, value) items of D

def iteritems(self):
    'D.iteritems() -> an iterator over the (key, value) items of D'
    for key in self:
        yield (key, self[key])

def iterkeys(

self)

D.iterkeys() -> an iterator over the keys of D

def iterkeys(self):
    'D.iterkeys() -> an iterator over the keys of D'
    return iter(self)

def itervalues(

self)

D.itervalues() -> an iterator over the values of D

def itervalues(self):
    'D.itervalues() -> an iterator over the values of D'
    for key in self:
        yield self[key]

def keys(

self)

D.keys() -> list of D's keys

def keys(self):
    "D.keys() -> list of D's keys"
    return list(self)

def options(

self, section)

Return a list of option names for the given section name.

def options(self, section):
    """Return a list of option names for the given section name."""
    try:
        opts = self._sections[section].copy()
    except KeyError:
        raise from_none(NoSectionError(section))
    opts.update(self._defaults)
    return list(opts.keys())

def optionxform(

self, optionstr)

def optionxform(self, optionstr):
    return optionstr.lower()

def pop(

self, key, default=<object object at 0xb7475048>)

D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.

def pop(self, key, default=__marker):
    '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
      If key is not found, d is returned if given, otherwise KeyError is raised.
    '''
    try:
        value = self[key]
    except KeyError:
        if default is self.__marker:
            raise
        return default
    else:
        del self[key]
        return value

def popitem(

self)

Remove a section from the parser and return it as a (section_name, section_proxy) tuple. If no section is present, raise KeyError.

The section DEFAULT is never returned because it cannot be removed.

def popitem(self):
    """Remove a section from the parser and return it as
    a (section_name, section_proxy) tuple. If no section is present, raise
    KeyError.
    The section DEFAULT is never returned because it cannot be removed.
    """
    for key in self.sections():
        value = self[key]
        del self[key]
        return key, value
    raise KeyError

def read(

self, filenames, encoding=None)

Read and parse a filename or a list of filenames.

Files that cannot be opened are silently ignored; this is designed so that you can specify a list of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the list will be read. A single filename may also be given.

Return list of successfully read files.

def read(self, filenames, encoding=None):
    """Read and parse a filename or a list of filenames.
    Files that cannot be opened are silently ignored; this is
    designed so that you can specify a list of potential
    configuration file locations (e.g. current directory, user's
    home directory, systemwide directory), and all existing
    configuration files in the list will be read.  A single
    filename may also be given.
    Return list of successfully read files.
    """
    if PY2 and isinstance(filenames, bytes):
        # we allow for a little unholy magic for Python 2 so that
        # people not using unicode_literals can still use the library
        # conveniently
        warnings.warn(
            "You passed a bytestring as `filenames`. This will not work"
            " on Python 3. Use `cp.read_file()` or switch to using Unicode"
            " strings across the board.",
            DeprecationWarning,
            stacklevel=2,
        )
        filenames = [filenames]
    elif isinstance(filenames, str):
        filenames = [filenames]
    read_ok = []
    for filename in filenames:
        try:
            with open(filename, encoding=encoding) as fp:
                self._read(fp, filename)
        except IOError:
            continue
        read_ok.append(filename)
    return read_ok

def read_dict(

self, dictionary, source=u'<dict>')

Read configuration from a dictionary.

Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order.

All types held in the dictionary are converted to strings during reading, including section names, option names and keys.

Optional second argument is the `source' specifying the name of the dictionary being read.

def read_dict(self, dictionary, source=''):
    """Read configuration from a dictionary.
    Keys are section names, values are dictionaries with keys and values
    that should be present in the section. If the used dictionary type
    preserves order, sections and their keys will be added in order.
    All types held in the dictionary are converted to strings during
    reading, including section names, option names and keys.
    Optional second argument is the `source' specifying the name of the
    dictionary being read.
    """
    elements_added = set()
    for section, keys in dictionary.items():
        section = str(section)
        try:
            self.add_section(section)
        except (DuplicateSectionError, ValueError):
            if self._strict and section in elements_added:
                raise
        elements_added.add(section)
        for key, value in keys.items():
            key = self.optionxform(str(key))
            if value is not None:
                value = str(value)
            if self._strict and (section, key) in elements_added:
                raise DuplicateOptionError(section, key, source)
            elements_added.add((section, key))
            self.set(section, key, value)

def read_file(

self, f, source=None)

Like read() but the argument must be a file-like object.

The f' argument must be iterable, returning one line at a time. Optional second argument is thesource' specifying the name of the file being read. If not given, it is taken from f.name. If f' has noname' attribute, `<???>' is used.

def read_file(self, f, source=None):
    """Like read() but the argument must be a file-like object.
    The `f' argument must be iterable, returning one line at a time.
    Optional second argument is the `source' specifying the name of the
    file being read. If not given, it is taken from f.name. If `f' has no
    `name' attribute, `' is used.
    """
    if source is None:
        try:
            source = f.name
        except AttributeError:
            source = ''
    self._read(f, source)

def read_string(

self, string, source=u'<string>')

Read configuration from a given string.

def read_string(self, string, source=''):
    """Read configuration from a given string."""
    sfile = io.StringIO(string)
    self.read_file(sfile, source)

def readfp(

self, fp, filename=None)

Deprecated, use read_file instead.

def readfp(self, fp, filename=None):
    """Deprecated, use read_file instead."""
    warnings.warn(
        "This method will be removed in future versions.  "
        "Use 'parser.read_file()' instead.",
        DeprecationWarning, stacklevel=2
    )
    self.read_file(fp, source=filename)

def remove_option(

self, section, option)

Remove an option.

def remove_option(self, section, option):
    """Remove an option."""
    if not section or section == self.default_section:
        sectdict = self._defaults
    else:
        try:
            sectdict = self._sections[section]
        except KeyError:
            raise from_none(NoSectionError(section))
    option = self.optionxform(option)
    existed = option in sectdict
    if existed:
        del sectdict[option]
    return existed

def remove_section(

self, section)

Remove a file section.

def remove_section(self, section):
    """Remove a file section."""
    existed = section in self._sections
    if existed:
        del self._sections[section]
        del self._proxies[section]
    return existed

def sections(

self)

Return a list of section names, excluding [DEFAULT]

def sections(self):
    """Return a list of section names, excluding [DEFAULT]"""
    # self._sections will never have [DEFAULT] in it
    return list(self._sections.keys())

def set(

self, section, option, value=None)

Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.

def set(self, section, option, value=None):
    """Set an option.  Extends RawConfigParser.set by validating type and
    interpolation syntax on the value."""
    _, option, value = self._validate_value_types(option=option, value=value)
    super(ConfigParser, self).set(section, option, value)

def setdefault(

self, key, default=None)

D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

def setdefault(self, key, default=None):
    'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
    try:
        return self[key]
    except KeyError:
        self[key] = default
    return default

def update(

*args, **kwds)

D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

def update(*args, **kwds):
    ''' D.update([E, ]**F) -> None.  Update D from mapping/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
        In either case, this is followed by: for k, v in F.items(): D[k] = v
    '''
    if len(args) > 2:
        raise TypeError("update() takes at most 2 positional "
                        "arguments ({} given)".format(len(args)))
    elif not args:
        raise TypeError("update() takes at least 1 argument (0 given)")
    self = args[0]
    other = args[1] if len(args) >= 2 else ()
    if isinstance(other, Mapping):
        for key in other:
            self[key] = other[key]
    elif hasattr(other, "keys"):
        for key in other.keys():
            self[key] = other[key]
    else:
        for key, value in other:
            self[key] = value
    for key, value in kwds.items():
        self[key] = value

def values(

self)

D.values() -> list of D's values

def values(self):
    "D.values() -> list of D's values"
    return [self[key] for key in self]

def write(

self, fp, space_around_delimiters=True)

Write an .ini-format representation of the configuration state.

If `space_around_delimiters' is True (the default), delimiters between keys and values are surrounded by spaces.

def write(self, fp, space_around_delimiters=True):
    """Write an .ini-format representation of the configuration state.
    If `space_around_delimiters' is True (the default), delimiters
    between keys and values are surrounded by spaces.
    """
    if space_around_delimiters:
        d = " {0} ".format(self._delimiters[0])
    else:
        d = self._delimiters[0]
    if self._defaults:
        self._write_section(fp, self.default_section,
                                self._defaults.items(), d)
    for section in self._sections:
        self._write_section(fp, section,
                            self._sections[section].items(), d)

class Settings

class Settings(object):

    default_file = None
    environ_key = None
    #__getitem__ = Dictionaryish.__getitem__

    def get_parser(self):
        """ build the default parser """
        parser = ArgumentParser()
        parser.add_argument(
            "-c", default='', dest='cmd',
            help=("just like python -c or sh -c (pass in a command)"))
        parser.add_argument(
            "-e", "--exec", default='', dest='execfile',
            help='a filename to execute')
        parser.add_argument(
            "-v", '--version', default=False, dest='version',
            action='store_true',
            help=("show version information"))
        parser.add_argument("--shell", dest="shell",
                          default=False, help="application shell",
                          action='store_true')
        parser.add_argument("--config", dest='config',
                          default="",
                          help="use config file")
        return parser

    def get_section(self, k, insist=False):
        try:
            return dict(self._wrapped)[k]
        except KeyError:
            if insist:
                error = 'Fatal: You need to specify a "{0}" section in {1}'
                raise SettingsError(error.format(k, self.settings_file))
            else:
                return None

    def get_setting(self, k, insist=False, default=None):
        """ TODO: move into goulash
            this function returns True for 'true', False for
            `false` or 'no', any other strings are passed through
        """
        _type = 'val'
        section, var = k.split('.')
        section_obj = self.get_section(section, insist=insist)
        try:
            tmp = section_obj[var]
        except KeyError:
            if insist:
                error = ('Fatal: You need to specify a "{0}" section '
                         'with an entry like  "{1}=<{2}>" in {3}')
                raise SettingsError(error.format(
                    section, var, _type, self.settings_file))
            elif default:
                tmp = default
            else:
                return None
        if isinstance(tmp, basestring):
            test = tmp not in ['0', 'false', 'no', 0]
            if not test:
                return test
        return tmp

    @property
    def settings_file(self):
        if self.options is not None and self.options.config:
            _file = self.options.config
        else:
            _file = self._init_filename or \
                    os.environ.get(self.environ_key) or \
                    self.default_file
        _file = os.path.expanduser(_file)
        return _file

    def pre_run(self):
        """ hook for subclassers.. """
        pass

    def load(self, file, config={}):
        """ returns a dictionary with key's of the form
            
.

Ancestors (in MRO)

Class variables

var default_file

var environ_key

Instance variables

var settings_file

Methods

def __init__(

self, filename=None, use_argv=True)

first load the default config so that overrides don't need to mention everything. update default with the config specified by the command line optionparser, then update that with any other overrides delivered to the parser.

def __init__(self, filename=None, use_argv=True):
    """ first load the default config so that overrides don't need
        to mention everything.  update default with the config
        specified by the command line optionparser, then
        update that with any other overrides delivered to the parser.
    """
    self._init_filename = filename
    if use_argv:
        self.options, self.args = [self.get_parser().parse_args()] * 2
    else:
        self.options = self.args = None
    self._wrapped = self.load(file=self.settings_file)
    # build a special dynamic section for things the user wants,
    # ie, things that have been passed into the option
    # parser but are not useful in the .ini
    if not self.get_section('user'):
        self['user'] = {}
    if self.options is not None:
        self['user']['shell'] = self.options.shell and 'true' or ''
    else:
        self['user']['shell'] = ''

def get_parser(

self)

build the default parser

def get_parser(self):
    """ build the default parser """
    parser = ArgumentParser()
    parser.add_argument(
        "-c", default='', dest='cmd',
        help=("just like python -c or sh -c (pass in a command)"))
    parser.add_argument(
        "-e", "--exec", default='', dest='execfile',
        help='a filename to execute')
    parser.add_argument(
        "-v", '--version', default=False, dest='version',
        action='store_true',
        help=("show version information"))
    parser.add_argument("--shell", dest="shell",
                      default=False, help="application shell",
                      action='store_true')
    parser.add_argument("--config", dest='config',
                      default="",
                      help="use config file")
    return parser

def get_section(

self, k, insist=False)

def get_section(self, k, insist=False):
    try:
        return dict(self._wrapped)[k]
    except KeyError:
        if insist:
            error = 'Fatal: You need to specify a "{0}" section in {1}'
            raise SettingsError(error.format(k, self.settings_file))
        else:
            return None

def get_setting(

self, k, insist=False, default=None)

TODO: move into goulash this function returns True for 'true', False for false or 'no', any other strings are passed through

def get_setting(self, k, insist=False, default=None):
    """ TODO: move into goulash
        this function returns True for 'true', False for
        `false` or 'no', any other strings are passed through
    """
    _type = 'val'
    section, var = k.split('.')
    section_obj = self.get_section(section, insist=insist)
    try:
        tmp = section_obj[var]
    except KeyError:
        if insist:
            error = ('Fatal: You need to specify a "{0}" section '
                     'with an entry like  "{1}=<{2}>" in {3}')
            raise SettingsError(error.format(
                section, var, _type, self.settings_file))
        elif default:
            tmp = default
        else:
            return None
    if isinstance(tmp, basestring):
        test = tmp not in ['0', 'false', 'no', 0]
        if not test:
            return test
    return tmp

def keys(

self)

def keys(self):
    return self._wrapped.keys()

def load(

self, file, config={})

returns a dictionary with key's of the form

.
def load(self, file, config={}):
    """ returns a dictionary with key's of the form
        
.

def pre_run(

self)

hook for subclassers..

def pre_run(self):
    """ hook for subclassers.. """
    pass

def run(

self, *args, **kargs)

this is a thing that probably does not belong in a settings abstraction, but it is very useful..

def run(self, *args, **kargs):
    """ this is a thing that probably does not belong in a
        settings abstraction, but it is very useful..
    """
    self.pre_run()
    if self.options.cmd:
        ns = globals()
        ns.update(settings=self)
        exec self.options.cmd in self.shell_namespace()
        return True
    if self.options.execfile:
        ns = globals()
        ns.update(settings=self)
        execfile(self.options.execfile, self.shell_namespace())
        return True
    if self.options.version:
        return self.show_version()
    if self.get_setting('user.shell'):
        try:
            from smashlib import embed
        except ImportError:
            raise SettingsError("You need smashlib installed "
                                "if you want to use the shell.")
        else:
            embed(user_ns=self.shell_namespace())
        return True

def shell_namespace(

self)

when --shell is used, the dictionary returned by this function populates all the shell variables

def shell_namespace(self):
    """ when --shell is used, the dictionary
        returned by this function populates
        all the shell variables """
    return {}

def show_version(

self)

subclassers should call super and then print their own junk

def show_version(self):
    """ subclassers should call super
        and then print their own junk """
    from goulash import __version__
    print 'goulash=={0}'.format(__version__)

class SettingsError

class SettingsError(Exception):
    pass

Ancestors (in MRO)

  • SettingsError
  • exceptions.Exception
  • exceptions.BaseException
  • __builtin__.object

Class variables

var args

var message