当前位置: 首页>>代码示例>>Python>>正文


Python collections.ChainMap类代码示例

本文整理汇总了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
开发者ID:nycz,项目名称:lcars-tem,代码行数:34,代码来源:settingsmanager.py

示例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)
开发者ID:eugeneai,项目名称:icc.studprogs,代码行数:31,代码来源:popplerxml.py

示例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)
开发者ID:Veedrac,项目名称:Sublime-Extras,代码行数:28,代码来源:store_selections.py

示例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()
开发者ID:Aluriak,项目名称:neural_world,代码行数:35,代码来源:config.py

示例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)
开发者ID:Geneea,项目名称:geneea-sdk,代码行数:10,代码来源:restutil.py

示例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
开发者ID:PythonCharmers,项目名称:python-future,代码行数:10,代码来源:test_chainmap.py

示例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'])
开发者ID:Chiva-Zhao,项目名称:pproject,代码行数:10,代码来源:combindict.py

示例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
开发者ID:foolswood,项目名称:questioneer,代码行数:11,代码来源:in_memory.py

示例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
开发者ID:PythonCharmers,项目名称:python-future,代码行数:12,代码来源:test_chainmap.py

示例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)
开发者ID:benzrf,项目名称:parthial,代码行数:14,代码来源:context.py

示例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
开发者ID:bgrace,项目名称:wagtail-commons,代码行数:14,代码来源:bootstrap_models.py

示例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)
开发者ID:benzrf,项目名称:parthial,代码行数:14,代码来源:context.py

示例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
开发者ID:NEAT-project,项目名称:neat,代码行数:49,代码来源:cib.py

示例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]
开发者ID:geraldstanje,项目名称:gone,代码行数:7,代码来源:goneinterp.py

示例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)
开发者ID:hardware-forest-utopia,项目名称:caldera,代码行数:7,代码来源:schema.py


注:本文中的collections.ChainMap类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。