本文整理汇总了Python中collections.MutableMapping.register方法的典型用法代码示例。如果您正苦于以下问题:Python MutableMapping.register方法的具体用法?Python MutableMapping.register怎么用?Python MutableMapping.register使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.MutableMapping
的用法示例。
在下文中一共展示了MutableMapping.register方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: keys
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
if sys.version_info[0] == 3: # pragma: no cover
items = _iterate_items
keys = _iterate_keys
values = _iterate_values
else:
def keys(self):
return list(self)
def items(self):
return list(self._iterate_items())
def values(self):
return list(self._iterate_values())
MutableMapping.register(DictAttribute)
class ConfigurationView(AttributeDictMixin):
"""A view over an applications configuration dicts.
Custom (but older) version of :class:`collections.ChainMap`.
If the key does not exist in ``changes``, the ``defaults`` dicts
are consulted.
:param changes: Dict containing changes to the configuration.
:param defaults: List of dicts containing the default configuration.
"""
key_t = None
示例2: __reversed__
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
__iter__ = iterkeys
def __reversed__(self):
"""Iterate over the values in the cache dict, oldest items
coming first.
"""
return iter(tuple(self._queue))
__copy__ = copy
# register the LRU cache as mutable mapping if possible
try:
from collections import MutableMapping
MutableMapping.register(LRUCache)
except ImportError:
pass
class Cycler(object):
"""A cycle helper for templates."""
def __init__(self, *items):
if not items:
raise RuntimeError('at least one item has to be provided')
self.items = items
self.reset()
def reset(self):
"""Resets the cycle."""
示例3: _proxied_to_fwd
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
self._bwd = merged._bwd
def _proxied_to_fwd(method):
"""
Decorator which proxies calls to the given bidict method on to the
self._fwd dict.
"""
@wraps(method, ('__name__', '__doc__'))
def wrapper(self, *args, **kwds):
return method(self._fwd, *args, **kwds)
return wrapper
for methodname in '__contains__ __iter__ __len__ get keys items values'.split():
locals()[methodname] = _proxied_to_fwd(getattr(dict, methodname))
MutableMapping.register(bidict)
# thanks to Raymond Hettinger for the idea for namedbidict
_LEGALNAMEPAT = '^[a-zA-Z][a-zA-Z0-9_]*$'
_LEGALNAMERE = re.compile(_LEGALNAMEPAT)
def namedbidict(mapname, fwdname, invname):
"""
Generate a custom bidict class in the spirit of ``namedtuple`` with
custom attribute-based access to forward and inverse mappings::
>>> CoupleMap = namedbidict('CoupleMap', 'husbands', 'wives')
>>> famous = CoupleMap({'bill': 'hillary'})
>>> famous.husbands['bill']
示例4: keys
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
if sys.version_info[0] == 3: # pragma: no cover
items = _iterate_items
keys = _iterate_keys
values = _iterate_values
else:
def keys(self):
return list(self)
def items(self):
return list(self._iterate_items())
def values(self):
return list(self._iterate_values())
MutableMapping.register(DictAttribute)
class ChainMap(MutableMapping):
key_t = None
changes = None
defaults = None
maps = None
def __init__(self, *maps, **kwargs):
maps = list(maps or [{}])
self.__dict__.update(
key_t=kwargs.get('key_t'),
maps=maps,
changes=maps[0],
示例5: get
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
def get(self, key, default=None):
"""Return value for given ``key`` or ``default`` value."""
try:
return self[key]
except KeyError:
return default
def set(self, key, value, extend=False, **kwargs):
"""Extended standard set function."""
self.__setitem__(key, value, extend, **kwargs)
def update(self, E, **F):
"""Proxy `dict` update method."""
self._dict.update(E, **F)
MutableMapping.register(SmartDict)
class DotableDict(dict):
"""Make nested python dictionaries accessable using dot notation.
Example:
.. code-block:: python
>>> dotable = DotableDict({'a': [{'b': 3, 'c': 5}]})
>>> dotable.a
... [{'b': 3, 'c': 5}]
"""
示例6: clear
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
def clear(self):
"""Empty the backing store of data."""
self.__data__.clear()
def pop(self, name, default=SENTINEL):
"""Retrieve and remove a value from the backing store, optionally with a default."""
if default is SENTINEL:
return self.__data__.pop(name)
return self.__data__.pop(name, default)
def popitem(self):
"""Pop an item 2-tuple off the backing store."""
return self.__data__.popitem()
def update(self, *args, **kw):
"""Update the backing store directly."""
self.__data__.update(*args, **kw)
def setdefault(self, key, value=None):
"""Set a value in the backing store if no value is currently present."""
return self.__data__.setdefault(key, value)
MutableMapping.register(Document) # Metaclass conflict if we subclass.
示例7: keys
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
else:
def keys(self):
# type: () -> List[Any]
return list(self)
def items(self):
# type: () -> List[Tuple[Any, Any]]
return list(self._iterate_items())
def values(self):
# type: () -> List[Any]
return list(self._iterate_values())
MutableMapping.register(DictAttribute) # noqa: E305
class ChainMap(MutableMapping):
"""Key lookup on a sequence of maps."""
key_t = None
changes = None
defaults = None
maps = None
def __init__(self, *maps, **kwargs):
# type: (*Mapping, **Any) -> None
maps = list(maps or [{}])
self.__dict__.update(
key_t=kwargs.get('key_t'),
示例8: TypeWrapper
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
self.vars[key] = TypeWrapper(value)
else:
self.vars[key] = SetWrapper(value)
def copy(self, *args, **kwargs):
return type(self)(self.vars.copy(*args, **kwargs))
def display(self, **kwargs):
ret = 'Domain('
strs = ['{} = {}'.format(var, vals.display(**kwargs))
for var, vals in sorted(self.vars.items(), key=itemgetter(0))]
ret += ',\n '.join(strs) + ')'
return ret
MutableMapping.register(Domain)
#-------------------------------------------------------------------------------
# Constraint
class Constraint(Base):
_attrs = dict(args = Attr(Sequence,
init=lambda self: tuple()))
_opts = dict(init_validate = True,
args = ('args',),
make_hashable = True)
def check(self, **kwargs):
raise NotImplementedError
示例9: raw_items
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
def raw_items(self):
return [(name, self.__raw(name)) for name in self.keys()]
def raw_values(self):
return [self.__raw(name) for name in self.keys()]
def load(self, context): # allows to use collection as source
context.update(self)
return context
# end
def __str__(self):
return six.u('<Collection: %s>' % [key for key in self.keys()])
__unicode__ = __repr__ = __str__
MutableMapping.register(Collection)
class Module(ModuleType):
def __init__(self, module_name, filepath, collection):
super(Module, self).__init__(module_name)
self.__file__ = filepath
for name, value in collection.items():
setattr(self, name, value)
def __getitem__(self, name):
return getattr(self, name)
示例10: sdict
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
result = sdict()
for key, value_set in self.iteritems():
for value in value_set:
result._get_or_create(value).add(key)
return result
def delete(self, value):
"""
Delete a value in all value sets and delete resulting empty items.
Returns removed_from and deleted sets of keys.
"""
removed_from = set()
deleted = set()
for key, value_set in self.iteritems():
try:
value_set.remove(value)
except KeyError:
continue
removed_from.add(key)
if not value_set:
deleted.add(key)
for key in deleted:
self.pop(key)
return removed_from, deleted
def union(self):
return set.union(*self.values())
MutableMapping.register(sdict)
示例11:
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
from collections import MutableMapping
from ._sortedmap import sortedmap
MutableMapping.register(sortedmap)
del MutableMapping
__version__ = '0.2.0'
__all__ = [
'sortedmap',
]
示例12: _iterate_values
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
iteritems = _iterate_items
def _iterate_values(self):
return (self[key] for key in self)
itervalues = _iterate_values
def keys(self):
return list(self._iterate_keys())
def items(self):
return list(self._iterate_items())
def values(self):
return list(self._iterate_values())
if MutableMapping:
MutableMapping.register(ConfigurationView)
class LimitedSet(object):
"""Kind-of Set with limitations.
Good for when you need to test for membership (`a in set`),
but the list might become to big, so you want to limit it so it doesn't
consume too much resources.
:keyword maxlen: Maximum number of members before we start
evicting expired members.
:keyword expires: Time in seconds, before a membership expires.
"""
__slots__ = ('maxlen', 'expires', '_data', '__len__', '_heap')
示例13: isinstance
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
if isinstance(item, Undefined):
raise KeyError(key)
return item
def __repr__(self):
return '<%s %s of %r>' % (
self.__class__.__name__,
repr(self.get_all()),
self.name
)
# register the context as mutable mapping if possible
try:
from collections import MutableMapping
MutableMapping.register(Context)
except ImportError:
pass
class TemplateReference(object):
"""The `self` in templates."""
def __init__(self, context):
self.__context = context
def __getitem__(self, name):
func = self.__context.blocks[name][0]
wrap = self.__context.environment.autoescape and \
Markup or (lambda x: x)
render = lambda: wrap(concat(func(self.__context)))
示例14:
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
from _sparsedict import SparseDict
try:
from collections import MutableMapping
except ImportError:
pass
else:
MutableMapping.register(SparseDict)
del MutableMapping
示例15: TypeError
# 需要导入模块: from collections import MutableMapping [as 别名]
# 或者: from collections.MutableMapping import register [as 别名]
default = Unset if count == 0 else args[0]
if _SECTION_SEP in option:
default = None if count == 0 else args[0]
section, option = option.split(_SECTION_SEP)
return self.wrapped.misc[section].setdefault(option, default)
else:
if count == 0:
opt = self.wrapped.casts.get(option)
default = opt.my_default if opt else None
else:
default = args[0]
return self.wrapped.options.setdefault(option, default)
else:
msg = "setdefault expected at most 2 arguments, got %s"
raise TypeError(msg % count + 1)
MutableMapping.register(MetaOptions)
class options(metaclass(MetaOptions)):
"""The single instance of :class:`MetaOptions` that wraps
``openerp.tools.config``.
"""
del metaclass
del MutableMapping