本文整理汇总了Python中weakref.WeakValueDictionary.items方法的典型用法代码示例。如果您正苦于以下问题:Python WeakValueDictionary.items方法的具体用法?Python WeakValueDictionary.items怎么用?Python WeakValueDictionary.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类weakref.WeakValueDictionary
的用法示例。
在下文中一共展示了WeakValueDictionary.items方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MapImageExporter
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import items [as 别名]
class MapImageExporter(MapExporter):
def __init__(self, nodes, ways, min_lat, max_lat, min_lon, max_lon, *args,
node_color=(0, 0, 0), way_color="allrandom", bg_color="white",
enlargement=50000):
"""Export map data (nodes and ways) as a map like image.
Params:
nodes - The raw nodes as read by any OSM file reader
ways - The raw ways as read by any OSM file reader
min_lat - The southern border of the map
max_lat - The northern border of the map
min_lon - The western border of the map
max_lon - The eastern border of the map
node_color - The colour of the nodes in the image
way_color - The colour of the ways in the image
bg_color - The colour of the image background
enlargement - Multiplication factor from map coordinate to pixel
coordinate. Determines image size.
"""
super(MapImageExporter, self).__init__(min_lat, max_lat, min_lon, max_lon, bg_color, enlargement)
self.logger = logging.getLogger('.'.join((__name__, type(self).__name__)))
self.nodes = WeakValueDictionary(nodes)
self.ways = WeakValueDictionary(ways)
self.node_color = node_color
self.way_color = way_color
def export(self, filename="export.png"):
"""Export the information to an image file
Params:
filename - The filename to export to, must have a valid image
extention. Default: export.png
"""
self.logger.info('Exporting a map image to %s', filename)
# Draw all ways
self.logger.info('Drawing the ways')
for id, way in self.ways.items():
coords = [ ((self.nodes[node].lon - self.min_lon) * self.enlargement,
(self.nodes[node].lat - self.min_lat) * self.enlargement) for node in way.nodes]
self.draw.line(coords, fill=self.way_color)
# draw all nodes as points
self.logger.info('Drawing the nodes')
for id, node in self.nodes.items():
self.draw.point( ((node.lon - self.min_lon) * self.enlargement,
(node.lat - self.min_lat) * self.enlargement), fill=self.node_color)
self._save_image(filename)
示例2: __init__
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import items [as 别名]
class Signal:
"""A signal and slots implementation.
Only methods may be used as slots. Two equivalent methods with the same
function and object can't be added at the same time. The order in which the
methods will be called is undefined.
"""
def __init__(self):
self._dict = WeakValueDictionary()
def __call__(self, *args, **kwargs):
"""Call all connected methods with the given arguments."""
for key, obj in self._dict.items():
key[0](obj, *args, **kwargs)
def __len__(self):
"""Return the number of connected methods."""
return len(self._dict)
def connect(self, method):
"""Connect a method to this slot."""
key = (method.__func__, id(method.__self__))
self._dict[key] = method.__self__
def disconnect(self, method):
"""Disconnect a method from this slot."""
key = (method.__func__, id(method.__self__))
if key in self._dict:
del self._dict[key]
示例3: StorePool
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import items [as 别名]
class StorePool(object):
"""
Store pool that maintains a single store per request context.
"""
def __init__(self):
self._local = threading.local()
self._all_stores = WeakValueDictionary()
self._databases = {}
self.uris = {}
def add(self, name, uri):
if not isinstance(uri, URI):
uri = URI(uri)
self.uris.setdefault(name, uri)
self._databases.setdefault(name, create_database(uri))
def getstore(self, name, fresh=False):
try:
stores = self._local.stores
except AttributeError:
stores = self._local.stores = WeakValueDictionary()
if fresh:
return self._getstore_fresh(name)
try:
return stores[name]
except KeyError:
return stores.setdefault(name, self._getstore_fresh(name))
def _getstore_fresh(self, name):
"""
Return a fresh store object
"""
store = Store(self._databases[name])
self._all_stores[id(store)] = store
return store
def disconnect(self):
"""
Disconnect all stores.
Any pending transactions will be rolled back and the stores'
connections closed. Attempts to use objects bound to a store will raise
an exception.
Subsequent calls to ``getstore`` will return a fresh store object
"""
self._local = threading.local()
for key, store in self._all_stores.items():
del self._all_stores[key]
store.rollback()
store.close()
def __repr__(self):
return "<%s %r, active=%d>" % (self.__class__.__name__,
self.dsn,
len(self._all_stores))
示例4: ObjectPool
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import items [as 别名]
class ObjectPool(object):
"""
This class allows to fetch mvc model objects using their UUID.
This requires to model to have a property called "uuid". All
class inheriting from the base 'Model' class will have this.
If implementing a custom model, the UUID property is responsible
for the removal and addition to the pool when it changes values.
Also see the UUIDPropIntel class for an example implementation.
We can use this to store complex relations between objects where
references to each other can be replaced with the UUID.
For a multi-threaded version see ThreadedObjectPool.
"""
def __init__(self, *args, **kwargs):
object.__init__(self)
self._objects = WeakValueDictionary()
def add_or_get_object(self, obj):
try:
self.add_object(obj, force=False, silent=False)
return obj
except KeyError:
return self.get_object(obj.uuid)
def add_object(self, obj, force=False, fail_on_duplicate=False):
if not obj.uuid in self._objects or force:
self._objects[obj.uuid] = obj
elif fail_on_duplicate:
raise KeyError, "UUID %s is already taken by another object %s, cannot add object %s" % (obj.uuid, self._objects[obj.uuid], obj)
else:
# Just change the objects uuid, will break refs, but
# it prevents issues with inherited properties etc.
logger.warning("A duplicate UUID was passed to an ObjectPool for a %s object." % obj)
obj.uuid = get_new_uuid()
def change_all_uuids(self):
# first get a copy off all uuids & objects:
items = self._objects.items()
for uuid, obj in items: # @UnusedVariable
obj.uuid = get_new_uuid()
def remove_object(self, obj):
if obj.uuid in self._objects and self._objects[obj.uuid] == obj:
del self._objects[obj.uuid]
def get_object(self, uuid):
obj = self._objects.get(uuid, None)
return obj
def clear(self):
self._objects.clear()
示例5: SilkArray
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import items [as 别名]
#.........这里部分代码省略.........
def realloc(self, *shape):
assert self.storage == "numpy"
if len(shape) == 1 and isinstance(shape[0], tuple):
shape = shape[0]
parent = self._parent()
if parent is not None:
myname = parent._find_child(id(self))
if parent.storage == "numpy":
if not parent._props[myname].get("var_array", False):
raise Exception("Cannot reallocate numpy array that is\
part of a larger numpy buffer. Use numpy_shatter() on the parent to allow\
reallocation")
if len(shape) != self._arity:
msg = "Shape must have %d dimensions, not %d"
raise ValueError(msg % (self._arity, len(shape)))
min_shape = self._data.shape
for n in range(self._arity):
msg = "Dimension %d: shape must have at least length %d, not %d"
if min_shape[n] > shape[n]:
raise ValueError(msg % (n+1, min_shape[n], shape[n]))
old_data = self._data
old_len = self._Len
self._data = np.zeros(dtype=self.dtype, shape=shape)
slices = [slice(0,s) for s in min_shape]
self._data[slices] = old_data
self._Len = _get_lenarray_empty(shape)
_lenarray_copypad(self._Len, shape, old_len, old_data.shape)
self._init(parent, "numpy", self._data, self._Len)
self._restore_array_coupling()
def _find_child(self, child_id):
if self.storage == "numpy":
for childname, ch in self._children.items():
if child_id == id(ch):
return childname
else:
for childname, ch in enumerate(self._children):
if child_id == id(ch):
return childname
raise KeyError
def _add_nonjson_child(self, child):
assert self.storage != "numpy"
njc = self._storage_nonjson_children
child_id = id(child)
if child_id not in njc:
njc.add(child_id)
if self.storage == "json":
self.storage = "mixed"
parent = self._parent()
if parent is not None:
parent._add_nonjson_child(self)
def _remove_nonjson_child(self, child):
assert self.storage != "numpy"
njc = self._storage_nonjson_children
child_id = id(child)
if child_id in njc:
assert self.storage == "mixed", self.storage
njc.remove(child_id)
if len(njc) == 0:
self.storage = "json"
parent = self._parent()
if parent is not None:
parent()._remove_nonjson_child(self)
示例6: Application
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import items [as 别名]
#.........这里部分代码省略.........
except KeyError:
raise ValueError(("There is no message listener"
"registered with id {}").format(identifier))
def post_message(self, message_type, message_data, sender):
"""Post a message to the messages system.
Parameters
----------
message_type : str
A string containing a name/tag/alias for the message type. It should
be lowercase and have no leading/trailing spaces. The string will
be trimmed and changed to lower case.
message_data :
Any kind of object
sender_id : int, class instance or None
The id or reference of the sender. This will prevent the sender to
receiving this message. If the type is int, it should be the identi-
fier of the listener in the messages system. Can also be a reference
to the sender instead of it's id. If None, the sender is considered
anonymous, and will receive the message.
If the id provided is invalid, it will be ignored.
"""
self._messages.put((message_type.lower().strip(), message_data, sender))
def _dispatch_messages(self):
"""Dispatch all the messages in the queue to the registered listeners.
"""
#Create strong references to the listeners
items = self._message_listeners.items()
while not self._messages.empty():
mtype, mdata, sender = self._messages.get(False)
if _DEBUG_MESSAGES:
print "<{}, {}>: {}".format(sender, mtype, mdata)
#Assign an invalid identifier
sender_id = -1
#If the sender is an int it should be the sender identifier
if isinstance(sender, int):
sender_id = sender
#If the sender is not an int, it should be a ref to a listener, so
#try to locate it's id
elif sender is not None:
for (identifier, instance) in items:
if instance is sender:
sender_id = identifier
for (identifier, instance) in items:
#Dont dispatch the message to the sender
if identifier == sender_id:
continue
try:
#Call the receive_message method
instance.receive_message(mtype, mdata, sender_id)
except:
print ("!! A message listener raised an exception when "
"receiving a message and will be removed from the list.")
log.exception("")
del self._message_listeners[identifier]
def import_resources(self):
示例7: Silk
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import items [as 别名]
class Silk(SilkObject):
_anonymous = None # bool
_props = None # list
dtype = None # list
_positional_args = None # list
__slots__ = [
"_parent", "_storage_enum", "_storage_nonjson_children",
"_data", "_children", "_is_none", "__weakref__"
]
def __init__(self, *args, _mode="any", **kwargs):
self._storage_enum = None
self._storage_nonjson_children = set()
self._children = None
if _mode == "parent":
self._init(
kwargs["parent"],
kwargs["storage"],
kwargs["data_store"],
)
elif _mode == "from_numpy":
assert "parent" not in kwargs
self._init(
None,
"numpy",
kwargs["data_store"],
)
else:
assert "parent" not in kwargs
assert "storage" not in kwargs
assert "data_store" not in kwargs
self._init(None, "json", None)
if _mode == "any":
self.set(*args, **kwargs)
elif _mode == "empty":
pass
elif _mode == "from_json":
self.set(*args, prop_setter=_prop_setter_json, **kwargs)
else:
raise ValueError(_mode)
def _init(self, parent, storage, data_store):
from .silkarray import SilkArray
if parent is not None:
if storage == "numpy":
self._parent = lambda: parent # hard ref
self._parent = weakref.ref(parent)
else:
self._parent = lambda: None
self.storage = storage
self._is_none = False
self._storage_nonjson_children.clear()
if self._children is not None:
for child in self._children.values():
child._parent = lambda: None
if storage == "json":
self._children = {}
if data_store is None:
data_store = {}
elif storage == "numpy":
self._children = WeakValueDictionary()
assert data_store is not None
assert data_store.dtype == np.dtype(self.dtype, align=True)
assert data_store.shape == ()
self._data = data_store
return
else:
raise ValueError(storage)
assert storage == "json"
for pname, p in self._props.items():
if p["elementary"]:
continue
t = self._get_typeclass(pname)
if pname not in data_store:
if issubclass(t, SilkArray):
data_store[pname] = []
else:
data_store[pname] = {}
c_data_store = data_store[pname]
self._children[pname] = t(
_mode="parent",
storage="json",
parent=self,
data_store=c_data_store,
len_data_store=None,
)
self._data = data_store
def _get_typeclass(self, propname):
p = self._props[propname]
if "typeclass" in p:
t = p["typeclass"]
else:
typename = p["typename"]
t = typenames._silk_types[typename]
return t
#.........这里部分代码省略.........
示例8: PersistentDict
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import items [as 别名]
class PersistentDict(object):
"""
Mapping object that is persistently stored
:param store_uri: URI for storing buckets; see :py:class:`~BaseBucketStore`
:type store_uri: :py:class:`str`
:param bucket_count: number of buckets to use for storing data
:type bucket_count: :py:class:`int`
:param bucket_salt: salt for finding buckets to store data
:type bucket_salt: :py:class:`int`
:param cache_size: number of buckets to LRU-cache in memory
:type cache_size: :py:class:`int`
:param cache_keys: whether to cache all keys in memory
:type cache_keys: :py:class:`bool`
"""
persistent_defaults = {
'bucket_count': 32,
'bucket_salt': 0,
}
def __init__(self, store_uri, bucket_count=NOTSET, bucket_salt=NOTSET, cache_size=3, cache_keys=True):
self._bucket_store = BaseBucketStore.from_uri(store_uri=store_uri, default_scheme='file')
# set empty fields
self._bucket_count = None
self._bucket_salt = None
self._bucket_keys = set()
self.bucket_key_fmt = None
self._keys_cache = None
self._bucket_cache = None
self._cache_size = None
# load current settings
try:
for attr, value in self._bucket_store.fetch_head().items():
setattr(self, attr, value)
self._update_bucket_key_fmt()
except BucketNotFound:
pass
# apply new settings
self.bucket_count = bucket_count
self.bucket_salt = bucket_salt
# LRU store for objects fetched from disk
self.cache_size = cache_size
# weakref store for objects still in use
self._active_buckets = WeakValueDictionary()
self._active_items = WeakValueDictionary()
# store new settings
self._store_head()
# cache keys in memory
self.cache_keys = cache_keys
@property
def store_uri(self):
return self._bucket_store.store_uri
# Settings
def _store_head(self):
"""
Store the meta-information of the dict
"""
self._bucket_store.store_head({
attr: getattr(self, attr) for attr in
# work directly on internal values, setters are called as part of init for finalization
('_bucket_count', '_bucket_salt', '_bucket_keys')
})
def _bucket_fmt_digits(self, bucket_count=None):
"""Return the number of hex digits required for the bucket name"""
bucket_count = bucket_count or self._bucket_count
return max(int(math.ceil(math.log(bucket_count, 16))), 1)
# exposed settings
@property
def cache_size(self):
return self._cache_size
@cache_size.setter
def cache_size(self, value):
self._cache_size = int(value or 1)
self._bucket_cache = deque(maxlen=self.cache_size)
@property
def bucket_salt(self):
"""
Get/Set the ``bucket_salt`` of the persistent mapping
:note: Setting ``bucket_salt`` causes **all** buckets storing data to be
recreated. Until the new buckets have been created, changes to the
mapping content may be silently dropped.
"""
return self._bucket_salt
@bucket_salt.setter
def bucket_salt(self, value):
# default if unset
if value == NOTSET:
if self._bucket_salt is not None:
return
self._bucket_salt = self.persistent_defaults['bucket_salt']
#.........这里部分代码省略.........