本文整理汇总了Python中collections.ChainMap.new_child方法的典型用法代码示例。如果您正苦于以下问题:Python ChainMap.new_child方法的具体用法?Python ChainMap.new_child怎么用?Python ChainMap.new_child使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.ChainMap
的用法示例。
在下文中一共展示了ChainMap.new_child方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: combine_map
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
def combine_map():
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
c = ChainMap(a,b)
print(c['x']) # Outputs 1 (from a)
print(c['y']) # Outputs 2 (from b)
print(c['z']) # Outputs 3 (from a)
print(len(c))
print(list(c.keys()))
print(list(c.values()))
c['z'] = 10
c['w'] = 40
del c['x']
print(a)
# del c['y']
values = ChainMap()
values['x'] = 1
# Add a new mapping
values = values.new_child()
values['x'] = 2
# Add a new mapping
values = values.new_child()
values['x'] = 3
print(values)
print(values['x'])
# Discard last mapping
values = values.parents
print(values['x'])
# Discard last mapping
values = values.parents
print(values['x'])
print(values)
示例2: more
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
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'])
示例3: raw_lines
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
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)
示例4: simple_cm
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
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
示例5: test_chain_map
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
def test_chain_map():
from collections import ChainMap
ChainMap()
cm = ChainMap({"a": 1, "b": 2})
assert cm.maps is not None
assert cm.new_child().maps is not None
assert cm.new_child({"c": 3}).maps is not None
assert cm.parents.maps is not None
cm["d"] = 4
del cm["a"]
assert cm["a"] is None
assert cm["b"] == 2
assert cm["d"] == 4
assert list(iter(cm)) == ["b", "d", "c"]
assert len(cm) == 3
示例6: __new__
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
def __new__(self, name, bases, attrs):
meta = ChainMap({})
used = set()
for b in bases:
if hasattr(b, "meta"):
meta = meta.new_child(b.meta)
for cls in b.mro():
used.add(cls)
else:
for cls in reversed(b.mro()):
if cls in used:
continue
used.add(cls)
if not hasattr(cls, "Meta"):
continue
meta = meta.new_child(cls.Meta.__dict__)
if "Meta" in attrs:
meta = meta.new_child(attrs["Meta"].__dict__)
attrs.update({"meta": meta})
return super().__new__(self, name, bases, attrs)
示例7: test_bool
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
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
示例8: Module
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
class Module(object):
def __init__(self, name, fullname, parent=None, reader=None):
self.name = name
self.fullname = fullname
self.parent = parent
self.reader = reader
self.files = OrderedDict()
self.reset()
@property
def package_name(self):
return self.name
def fulladdress(self, name):
return "{}.{}".format(self.fullname, name)
def read_file(self, name, file):
self.files[name] = self.reader.read_file(file, parent=self)
def normalize(self):
self.reset()
for file in self.files.values():
file.normalize()
self.new_child(file.members)
def reset(self):
self.members = ChainMap()
def new_child(self, item):
self.members = self.members.new_child(item)
def __getitem__(self, name):
return self.members[name]
def get(self, name, default=None):
return self.members.get(name, default)
def __contains__(self, name):
return name in self.members
@property
def world(self):
return self.parent
示例9: ScopeStack
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
class ScopeStack(object):
def __init__(self):
self.data = ChainMap({})
self.special_forms = {}
def __contains__(self, key):
return key in self.data
def set(self, key, value, special_form=False):
if not special_form:
self.data[key] = value
else:
self.special_forms[key] = value
if not self.validate():
raise RuntimeError("Special form overwriten")
def unset(self, key):
del self.data[key]
def is_empty(self):
return len(self.data) == 0
def new_scope(self):
self.data = self.data.new_child()
def drop_scope(self):
self.data = self.data.parents
def get_scope_identifiers(self, root=False):
first_level = self.data.maps[0] if len(self.data.maps) > 0 else {}
merged_stmts = list(first_level.values())
if root:
merged_stmts = list(self.special_forms.values()) + merged_stmts
return sorted(merged_stmts, key=lambda x: x.value)
def validate(self):
normal_scope = set(self.data.keys())
special_form_scope = set(self.special_forms.keys())
return len(normal_scope.intersection(special_form_scope)) == 0
示例10: SymbolTable
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
class SymbolTable(object):
'''
Class representing a symbol table. It should provide functionality
for adding and looking up nodes associated with identifiers.
'''
def __init__(self):
self.table = ChainMap()
self.current_scope = self.table
self.root_scope = self.table
self.type_objects = {
int: gonetype.int_type,
float: gonetype.float_type,
str: gonetype.string_type,
bool: gonetype.bool_type,
'int': gonetype.int_type,
'float': gonetype.float_type,
'string': gonetype.string_type,
'bool': gonetype.bool_type
}
def add(self, symbol, data):
self.current_scope[symbol] = data
def get(self, symbol):
if symbol in self.current_scope:
return self.current_scope[symbol]
return None
def push_scope(self):
self.current_scope = self.table.new_child()
return self.current_scope
def pop_scope(self):
self.current_scope = self.current_scope.parents
return self.current_scope
def pprint(self):
print("{}top".format("-" * 10))
for symbol in self.table:
print("{}: {}".format(symbol, self.table.get(symbol)))
print("-" * 10)
示例11: print
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
print(d)
# ==============================================
from collections import deque
d = deque([1, 2, 3])
print(d.pop(), d)
# ==============================================
from collections import ChainMap
a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
m = ChainMap(a, b)
print(m['c'])
print(m.maps)
m2 = m.new_child()
print(m2)
print(m2.parents)
# ==============================================
from collections import Counter
a = [1, 4, 2, 3, 2, 3, 4, 2]
c = Counter(a)
print(c)
print(c.most_common(1))
# ==============================================
from collections import namedtuple
Point = namedtuple('PointExtension', ['x', 'y'])
示例12: ChainMap
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#collections模块中的ChainMap类可以实现关联两个字典的操作
from collections import ChainMap
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
c = ChainMap(a,b)
print(c['x'])
print(c['y'])
print(c['z'])
#增加
c = c.new_child()
c['x'] = 2
print(c)
示例13: VarStore
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
#.........这里部分代码省略.........
if key is not None:
assert '.' not in key
if prefix is None:
prefix = 'V'
try:
typ, var = self.lookup[key]
return var
except KeyError:
self.count += 1
count_str = str(self.count)
if len(count_str) == 1:
count_str = '0' + count_str
if key is None:
key = 'ANON' + count_str
v = Variable(prefix + count_str)
self.lookup[key] = (typ, v)
self.type_of_var[v] = typ
return v
def define(self, key=None, typ=None, prefix=None):
"""Define a new variable.
Args:
key: a name to associate the variable with
typ: the type of the variable, if it is not defined the type will be inferred from the key.
prefix: a prefix to use when generating the variable's name
"""
if key is not None:
assert '.' in key
if prefix is None:
prefix = 'V'
try:
typ, var = self.lookup[key]
return var
except KeyError:
self.count += 1
count_str = str(self.count)
if len(count_str) == 1:
count_str = '0' + count_str
if key is None:
key = 'ANON' + count_str
v = Variable(prefix + count_str)
if typ is None:
typ = self.find_type(key)
self.type_of_var[v] = typ
# insert into the level that contains the root
if '.' in key:
root = key.split('.')[0]
for d in self.lookup.maps:
if root in d:
d[key] = (typ, v)
break
else:
self.lookup[key] = (typ, v)
return v
def find_var(self, key):
return self.lookup[key][1]
def find_type(self, key):
key_split = key.split('.')
top_var = key_split[0]
descendants = '.'.join(key_split[1:])
typ, _ = self.lookup[top_var]
return type_lookup(self.schema, typ, descendants)
def find_raw_type(self, key):
key_split = key.split('.')
top_var = key_split[0]
typ, _ = self.lookup[top_var]
for part in key_split[1:]:
typ = self.schema[type_deref(typ)][part]
return typ
def find_type_of_var(self, var):
return self.type_of_var[var]
def descend_scope(self):
self.lookup = self.lookup.new_child()
def ascend_scope(self):
self.lookup = self.lookup.parents
def define_constant(self, constant):
self.constants.add(constant)
def type_has_backrefs(self, typ):
for rtyp, field in self.backrefs.keys():
if rtyp == typ:
return True
return False
示例14: ChainMap
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
'B': 10}
b={
'B': 20,
'D': 50
}
c = ChainMap(a,b) # Check first map first Do c['B']=10
print(list(c.keys())) # ABD
print(list(c.values())) #100 10 50
#del c['D'] #can not delete key in first map
#others. new_child merge, update
val = ChainMap()
val['x']=1
val = val.new_child()
val['x']=2
val = val.new_child()
val['x']=3
print(val)
print(val['x'])
val=val.parents
print(val['x'])
val=val.parents
print(val['x'])
print(val)
#=========
c = {
示例15: ChainMap
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import new_child [as 别名]
# Combining Multiple Mappings into a Single Mapping
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
from collections import ChainMap
c = ChainMap(a,b)
print(c['x'])
print(c['y'])
print(c['z'])
>>> values = ChainMap()
>>> values['x'] = 1
>>> values = values.new_child()
>>> values['x'] = 2
>>> values = values.new_child()
>>> values['x'] = 3
>>> values
ChainMap({'x': 3}, {'x': 2}, {'x': 1})
>>> values['x']
3
>>> values = values.parents
>>> values['x']
2
>>> values = values.parents
>>> values['x']
1
>>> values
ChainMap({'x': 1})