def _unify_values(self, section, variables): """Create a sequence of lookups with 'variables' taking priority over the 'section' which takes priority over the DEFAULTSECT. """ try: sectiondict = self._sections[section] except KeyError: if section != self.default_section: raise NoSectionError(section) else: sectiondict = {} # Update with the entry specific variables vardict = {} if variables: for key, value in variables.items(): if value is not None: value = str(value) vardict[self.optionxform(key)] = value prefix = section.split(".", 1)[0] + ".DEFAULT" # print("searched for {0}".format(prefix)) try: defaultdict = self._sections[prefix] return _ChainMap(vardict, sectiondict, defaultdict, self._defaults) except KeyError: return _ChainMap(vardict, sectiondict, self._defaults)
def _unify_values(self, section, variables): """Create a sequence of lookups with 'variables' taking priority over the 'section' which takes priority over the DEFAULTSECT. """ try: sectiondict = self._sections[section] except KeyError: if section != self.default_section: raise NoSectionError(section) else: sectiondict = {} # Update with the entry specific variables vardict = {} if variables: for key, value in variables.items(): if value is not None: value = str(value) vardict[self.optionxform(key)] = value prefix = section.split(".",1)[0] + ".DEFAULT" # print("searched for {0}".format(prefix)) try: defaultdict = self._sections[prefix] return _ChainMap(vardict, sectiondict, defaultdict, self._defaults) except KeyError: return _ChainMap(vardict, sectiondict, self._defaults)
def substitute(*args, **kws): if not args: raise TypeError("descriptor 'substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: if ':-' in named: var, _, default = named.partition(':-') return mapping.get(var) or default if '-' in named: var, _, default = named.partition('-') return mapping.get(var, default) val = mapping[named] return '%s' % (val,) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template)
def substitute(*args, **kws): if not args: raise TypeError("descriptor 'substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: val = mapping[named] # We use this idiom instead of str() because the latter will # fail if val is a Unicode containing non-ASCII characters. return '%s' % (val, ) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template)
def safe_substitute(*args, **kws): if not args: raise TypeError("descriptor 'safe_substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') or mo.group('braced') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % (mapping[named],) except KeyError: return mo.group() if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return mo.group() raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template)
def substitute(*args, **kws): if not args: raise TypeError( "descriptor 'substitute' of 'Template' object needs an argument" ) self, *args = args if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] def convert(mo): named = mo.group('named') or mo.group('braced') if named is not None: return str(mapping[named]) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template)
def substitute(*args, **kws): if not args: raise TypeError("descriptor 'substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError("Too many positional arguments") if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group("named") or mo.group("braced") if named is not None: return self.extract_value(mapping, named) if mo.group("escaped") is not None: return self.delimiter if mo.group("invalid") is not None: self._invalid(mo) raise ValueError("Unrecognized named group in pattern", self.pattern) return _infer_type(self.pattern.sub(convert, self.template))
def substitute(*args, **kws): if not args: raise TypeError("descriptor 'substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: return str(mapping[named]) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template)
def safe_substitute(*args, **kws): if not args: raise TypeError("descriptor 'safe_substitute' of 'Template' object " "needs an argument") self, *args = args # allow the "self" keyword be passed if len(args) > 1: raise TypeError('Too many positional arguments') if not args: mapping = kws elif kws: mapping = _ChainMap(kws, args[0]) else: mapping = args[0] # Helper function for .sub() def convert(mo): named = mo.group('named') or mo.group('braced') if named is not None: try: return str(mapping[named]) except KeyError: return mo.group() if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return mo.group() raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template)
def __init__(self, config, handler_reg=None, version=1): self.config = config self._api = None self.version = version if handler_reg is None: handler_reg = {} self.handler_reg = _ChainMap(handler_reg) self._datum_cache = boltons.cacheutils.LRU(max_size=1000000) self._handler_cache = boltons.cacheutils.LRU() self._resource_cache = boltons.cacheutils.LRU(on_miss=self._r_on_miss) self.known_spec = dict(self.KNOWN_SPEC)
def _unify_values(self, section, vars): sectiondict = {} try: sectiondict = self._sections[section] except KeyError: if section != self.default_section: raise NoSectionError(section) vardict = {} if vars: for (key, value) in vars.items(): if value is not None: value = str(value) vardict[self.optionxform(key)] = value return _ChainMap(vardict, sectiondict, self._defaults)
class Template(metaclass=_TemplateMetaclass): """A string class for supporting $-substitutions.""" delimiter = '$' # r'[a-z]' matches to non-ASCII letters when used with IGNORECASE, but # without the ASCII flag. We can't add re.ASCII to flags because of # backward compatibility. So we use the ?a local flag and [a-z] pattern. # See https://bugs.python.org/issue31672 idpattern = r'(?a:[_a-z][_a-z0-9]*)' braceidpattern = None flags = _re.IGNORECASE def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(keepends=True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, mapping=_sentinel_dict, /, **kws): if mapping is _sentinel_dict: mapping = kws elif kws: mapping = _ChainMap(kws, mapping) # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: return str(mapping[named]) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template)
def __init__(self, flags=None, path=None, files=None, converters=None, namespace=None): """Create a new Reader. Argument `flags` defines the open flags of the journal, which can be one of, or ORed combination of constants: LOCAL_ONLY (default) opens journal on local machine only; RUNTIME_ONLY opens only volatile journal files; and SYSTEM_ONLY opens only journal files of system services and the kernel. Argument `path` is the directory of journal files, either a file system path or a file descriptor. Specify `namespace` to read from specific journal namespace. Note that `flags`, `path`, `files` and `namespace` are exclusive. Argument `converters` is a dictionary which updates the DEFAULT_CONVERTERS to convert journal field values. Field names are used as keys into this dictionary. The values must be single argument functions, which take a `bytes` object and return a converted value. When there's no entry for a field name, then the default UTF-8 decoding will be attempted. If the conversion fails with a ValueError, unconverted bytes object will be returned. (Note that ValueEror is a superclass of UnicodeDecodeError). Reader implements the context manager protocol: the journal will be closed when exiting the block. """ if flags is None: if path is None and files is None: # This mimics journalctl behaviour of default to local journal only flags = LOCAL_ONLY else: flags = 0 super(Reader, self).__init__(flags, path, files, namespace) if _sys.version_info >= (3, 3): self.converters = _ChainMap() if converters is not None: self.converters.maps.append(converters) self.converters.maps.append(DEFAULT_CONVERTERS) else: self.converters = DEFAULT_CONVERTERS.copy() if converters is not None: self.converters.update(converters)
def _unify_values(self, section, vars): """Create a sequence of lookups with 'vars' taking priority over the 'section' which takes priority over the DEFAULTSECT. """ sectiondict = {} try: sectiondict = self._sections[section] except KeyError: if section != self.default_section: raise NoSectionError(section) # Update with the entry specific variables vardict = {} if vars: for key, value in vars.items(): if value is not None: value = str(value) vardict[self.optionxform(key)] = value return _ChainMap(vardict, sectiondict, self._defaults)
def __init__(self, flags=None, path=None, files=None, converters=None): """Create a new Reader. Argument `flags` defines the open flags of the journal, which can be one of, or ORed combination of constants: LOCAL_ONLY (default) opens journal on local machine only; RUNTIME_ONLY opens only volatile journal files; and SYSTEM_ONLY opens only journal files of system services and the kernel. Argument `path` is the directory of journal files, either a file system path or a file descriptor. Note that `flags`, `path`, and `files` are exclusive. Argument `converters` is a dictionary which updates the DEFAULT_CONVERTERS to convert journal field values. Field names are used as keys into this dictionary. The values must be single argument functions, which take a `bytes` object and return a converted value. When there's no entry for a field name, then the default UTF-8 decoding will be attempted. If the conversion fails with a ValueError, unconverted bytes object will be returned. (Note that ValueEror is a superclass of UnicodeDecodeError). Reader implements the context manager protocol: the journal will be closed when exiting the block. """ if flags is None: if path is None and files is None: # This mimics journalctl behaviour of default to local journal only flags = LOCAL_ONLY else: flags = 0 super(Reader, self).__init__(flags, path, files) if _sys.version_info >= (3,3): self.converters = _ChainMap() if converters is not None: self.converters.maps.append(converters) self.converters.maps.append(DEFAULT_CONVERTERS) else: self.converters = DEFAULT_CONVERTERS.copy() if converters is not None: self.converters.update(converters)
def __init__(self, flags=0, path=None, converters=None): """Create an instance of Reader, which allows filtering and return of journal entries. Argument `flags` sets open flags of the journal, which can be one of, or ORed combination of constants: LOCAL_ONLY (default) opens journal on local machine only; RUNTIME_ONLY opens only volatile journal files; and SYSTEM_ONLY opens only journal files of system services and the kernel. Argument `path` is the directory of journal files. Note that `flags` and `path` are exclusive. Argument `converters` is a dictionary which updates the DEFAULT_CONVERTERS to convert journal field values. Field names are used as keys into this dictionary. The values must be single argument functions, which take a `bytes` object and return a converted value. When there's no entry for a field name, then the default UTF-8 decoding will be attempted. If the conversion fails with a ValueError, unconverted bytes object will be returned. (Note that ValueEror is a superclass of UnicodeDecodeError). Reader implements the context manager protocol: the journal will be closed when exiting the block. """ super(Reader, self).__init__(flags, path) if _sys.version_info >= (3, 3): self.converters = _ChainMap() if converters is not None: self.converters.maps.append(converters) self.converters.maps.append(DEFAULT_CONVERTERS) else: self.converters = DEFAULT_CONVERTERS.copy() if converters is not None: self.converters.update(converters)
class Template: """A string class for supporting $-substitutions.""" delimiter = '$' # r'[a-z]' matches to non-ASCII letters when used with IGNORECASE, but # without the ASCII flag. We can't add re.ASCII to flags because of # backward compatibility. So we use the ?a local flag and [a-z] pattern. # See https://bugs.python.org/issue31672 idpattern = r'(?a:[_a-z][_a-z0-9]*)' braceidpattern = None flags = _re.IGNORECASE def __init_subclass__(cls): super().__init_subclass__() if 'pattern' in cls.__dict__: pattern = cls.pattern else: delim = _re.escape(cls.delimiter) id = cls.idpattern bid = cls.braceidpattern or cls.idpattern pattern = fr""" {delim}(?: (?P<escaped>{delim}) | # Escape sequence of two delimiters (?P<named>{id}) | # delimiter and a Python identifier {{(?P<braced>{bid})}} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) """ cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE) def __init__(self, template): self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo): i = mo.start('invalid') lines = self.template[:i].splitlines(keepends=True) if not lines: colno = 1 lineno = 1 else: colno = i - len(''.join(lines[:-1])) lineno = len(lines) raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno)) def substitute(self, mapping=_sentinel_dict, /, **kws): if mapping is _sentinel_dict: mapping = kws elif kws: mapping = _ChainMap(kws, mapping) # Helper function for .sub() def convert(mo): # Check the most common path first. named = mo.group('named') or mo.group('braced') if named is not None: return str(mapping[named]) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template)
if named is not None: return str(mapping[named]) if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: self._invalid(mo) raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) def safe_substitute(self, mapping=_sentinel_dict, /, **kws): if mapping is _sentinel_dict: mapping = kws elif kws: mapping = _ChainMap(kws, mapping) # Helper function for .sub() def convert(mo): named = mo.group('named') or mo.group('braced') if named is not None: try: return str(mapping[named]) except KeyError: return mo.group() if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: return mo.group() raise ValueError('Unrecognized named group in pattern', self.pattern)
#def safe_eval(expression, /, locals=None): #def safe_eval(expression, /, locals=None, *, nonlocals=None): def safe_eval(expression, /,*, locals=None, nonlocals=None): # assume expression cannot setitem in locals # but expression can getitem in locals and update it # if locals is None: locals = {} locals = _MappingProxyType(locals) if 1: #although nonlocals is useless, here to match API-of-safe_eval with safe_exec #r'''[[[ if nonlocals: nonlocals = _MappingProxyType(nonlocals) locals_nonlocals = _ChainMap(locals, nonlocals) else: locals_nonlocals = locals #]]]''' else: locals_nonlocals = locals return _global_eval(expression, dict(_globals), locals_nonlocals) r''' Help on built-in function eval in module builtins: eval(source, globals=None, locals=None, /) Evaluate the given source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals.
def new_child(self, m=None): if m is None: m = {} return _ChainMap(m, self)
def clear(self): self._mapping = _ChainMap()
def __init__(self, inst, bdict, instance_data, _ChainMap=_ChainMap): self.inst = inst self._mapping = _ChainMap(instance_data, bdict)