本文整理汇总了Python中collections.ChainMap类的典型用法代码示例。如果您正苦于以下问题:Python ChainMap类的具体用法?Python ChainMap怎么用?Python ChainMap使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ChainMap类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_settings
def load_settings(paths, default_config, oldsettings,
setting_callbacks, setting_types, refresh_only):
""" Load settings from the main config file. """
auto_settings, manual_settings\
= read_config(paths['config_file'], default_config)
settings = ChainMap(auto_settings, manual_settings)
def revert_setting(key):
if key in oldsettings:
reverted_value = oldsettings[key]
else:
reverted_value = default_config[key]
if key in auto_settings:
auto_settings[key] = reverted_value
elif key in manual_settings:
manual_settings[key] = reverted_value
error = False
# Make sure the settings aren't fucked up yo
for key, value in settings.items():
if refresh_only and oldsettings.get(key) == value:
continue
# First make a simple check to see if the value is the right type
if not valid_setting(key, value, setting_types):
print('Invalid type for setting: "{}"'.format(key))
error = True
revert_setting(key)
# Then do a live update and see if things blow up
try:
update_runtime_setting(key, value, setting_callbacks)
except SettingsError as e:
print(str(e))
error = True
revert_setting(key)
error_text = 'Errors while reading the config. Check terminal output.'
return settings, error_text if error else None
示例2: raw_lines
def raw_lines(self, node=None, style=None):
if node == None:
self.initialize()
style = ChainMap({"fontstyle": "n"})
node = self.root
for e in node.iterchildren():
if e.tag in ["html", "body", "pdf2xml"]:
yield from self.raw_lines(e, style)
continue
if e.tag in ["b", "i"]:
sstart, send = self.__class__.HTML_MARKUP[e.tag]
yield sstart
yield from self._texts(e,
style.new_child({"fontstyle": e.tag}))
yield send
continue
if e.tag in ["a"]:
sstart, send = self.__class__.HTML_MARKUP[e.tag]
yield sstart
yield from self._texts(e, style)
yield send
continue
if e.tag == "page":
yield from self._proc_page(e, style)
yield page_symbol
continue
#if e.tag == "text":
# yield from self._proc_text(e, style)
# continue
yield e
yield from self.raw_lines(e, style)
示例3: store_selections
def store_selections(view, selections, replace=False, **settings):
"""
Save selections to storage.
"""
id = get_id(settings)
if not replace:
# Add old selections to selections, so as not to remove them
selections = list(chain(selections, view.get_regions(id)))
# Filter "settings" to only have "flags", "scope" and "icon"
filtered = {"flags": parse_flags(**settings)}
# Chain settings with preset to provide fallback
settings = ChainMap(settings, presets[settings.get("preset", "")])
if "scope" in settings:
filtered["scope"] = settings["scope"]
if "icon" in settings:
filtered["icon"] = settings["icon"]
# Done! Finish up!
#
# Wrap the call in a timeout to appease adzenith who was kind enough
# to open my first bug report at github.com/Veedrac/Sublime-Extras/issues/1.
# This should make sure that you can switch panes with the mouse.
sublime.set_timeout(lambda: view.add_regions(id, selections, **filtered), 0)
示例4: __init__
def __init__(self, **kwargs):
# get dict fieldname:Field received as parameter
parameters = {
field: Field(value=Configuration.typed(field, value),
type=Configuration.ALL_FIELDS[field].type)
for field, value in kwargs.items()
}
# take parameters in priority, else the ALL_FIELDS dict
prioritized_fields = ChainMap(parameters, Configuration.ALL_FIELDS)
# save values as fields
for varname, field in prioritized_fields.items():
value, ftype = field
setattr(self, '_' + varname, ftype(value))
# access and setter definition
def field_access(instance, field):
return getattr(instance, '_' + field)
def field_setter(instance, value, field):
ftype = Configuration.ALL_FIELDS[field].type
if field in self.UNMUTABLE_FIELDS:
LOGGER.warning('CONFIG: The unmutable field ' + field
+ ' have been modified to ' + str(value))
elif field in self.GENERATED_FIELDS:
LOGGER.warning('CONFIG: The generated field ' + field
+ ' have been modified to ' + str(value))
setattr(instance, '_' + field, ftype(value))
# regenerate generated data
# add values as properties, eventually with a setter if field is mutable
for varname in Configuration.ALL_FIELDS:
new_prop = property(partial(field_access, field=varname))
setattr(Configuration, varname, new_prop)
if varname in Configuration.MUTABLE_FIELDS:
setter = new_prop.setter(partial(field_setter, field=varname))
setattr(Configuration, varname, setter)
# add other data
self.postprocess_data()
示例5: fromDocAndFlags
def fromDocAndFlags(document, flags):
"""
@param document: input document
@param flags: additional API parameters
@return: S2ApiInput corresponding to given document and flags
"""
docDict = {k: v for k, v in document._asdict().items() if v}
data = ChainMap(docDict, flags)
inputDict = {fldName : data.get(fldName, None) for fldName in S2ApiInput._fields}
return S2ApiInput(**inputDict)
示例6: simple_cm
def simple_cm():
from collections import ChainMap
c = ChainMap()
c['one'] = 1
c['two'] = 2
cc = c.new_child()
cc['one'] = 'one'
return c, cc
示例7: more
def more():
values = ChainMap()
values['x'] = 1
print(values)
values = values.new_child()
values['x'] = 2
print(values)
values = values.new_child()
values['x'] = 3
print(values, values['x'], values.parents['x'], values.parents.parents['x'])
示例8: get_raw_results
def get_raw_results(self):
columns = []
response_cols = []
for p, responses in self._stored_responses.items():
for i, response in responses.items():
response = ChainMap(
response, {'participant_id': p, 'active_item_id': i})
if not columns:
columns.extend(response.keys())
response_cols.append([response[c] for c in columns])
return columns, response_cols
示例9: test_bool
def test_bool(self):
from collections import ChainMap
c = ChainMap()
assert not(bool(c))
c['one'] = 1
c['two'] = 2
assert bool(c)
cc = c.new_child()
cc['one'] = 'one'
assert cc
示例10: __getitem__
def __getitem__(self, k):
"""Look up a variable.
Args:
k (str): The name of the variable to look up.
Returns:
LispVal: The value assigned to the variable.
Raises:
KeyError: If the variable has not been assigned to.
"""
chain = ChainMap(self.scopes, self.globals)
return chain.__getitem__(k)
示例11: instantiate_related_objects
def instantiate_related_objects(self, related_model, related_objects, meta_attrs):
new_objects = []
for obj_attrs in related_objects:
new_obj = related_model()
input_attrs = ChainMap(obj_attrs, meta_attrs)
for field_name, field_value in input_attrs.items():
f = self.interpolate(field_name, meta_attrs)
setattr(new_obj, field_name, f(field_value))
new_objects.append(new_obj)
return new_objects
示例12: __contains__
def __contains__(self, k):
"""Check whether a variable has been assigned to.
This is **not** the same kind of element-of as described in the
class documentation.
Args:
k (str): The name of the variable to check.
Returns:
bool: Whether or not the variable has been assigned to.
"""
chain = ChainMap(self.scopes, self.globals)
return chain.__contains__(k)
示例13: expand_rows
def expand_rows(self, apply_extended=True):
"""Generate CIB rows by expanding all CIBs pointing to current CIB """
paths = self.resolve_graph()
# for storing expanded rows
rows = []
for path in paths:
expanded_properties = (self.cib[uid].expand() for uid in path)
for pas in itertools.product(*expanded_properties):
chain = ChainMap(*pas)
# For debugging purposes, add the path list to the chain.
# Store as string to preserve path order (NEAT properties are not ordered).
dbg_path = '<<'.join(uid for uid in path)
# insert at position 0 to override any existing entries
# chain.maps.insert(0, PropertyArray(NEATProperty(('cib_uids', dbg_path))))
# convert back to normal PropertyArrays
row = PropertyArray(*(p for p in chain.values()))
row.meta['cib_uids'] = dbg_path
rows.append(row)
if not apply_extended:
return rows
if not self.cib.extenders:
# no extender CIB nodes loaded
return rows
# TODO optimize
extended_rows = rows.copy()
for entry in rows:
# TODO take priorities into account
# iterate extender cib_nodes
for uid, xs in self.cib.extenders.items():
for pa in xs.expand():
if xs.match_entry(entry):
entry_copy = copy.deepcopy(entry)
chain = ChainMap(pa, entry_copy)
new_pa = PropertyArray(*(p for p in chain.values()))
try:
del new_pa['uid']
except KeyError:
pass
extended_rows.append(new_pa)
return extended_rows
示例14: __init__
def __init__(self, functions, name="module"):
self.vars = ChainMap()
self.vars.update({fn.instructions[0][1]: fn for fn in functions})
# List of Python modules to search for external decls
external_libs = [ 'math', 'os' ]
self.external_libs = [ __import__(name) for name in external_libs]
示例15: __init__
def __init__(self, schema):
self.count = -1
self.lookup = ChainMap()
self.type_of_var = {}
self.schema = schema
self.constants = set()
self.backrefs = build_links(schema)