本文整理汇总了Python中weakref.WeakValueDictionary.get方法的典型用法代码示例。如果您正苦于以下问题:Python WeakValueDictionary.get方法的具体用法?Python WeakValueDictionary.get怎么用?Python WeakValueDictionary.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类weakref.WeakValueDictionary
的用法示例。
在下文中一共展示了WeakValueDictionary.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Showcase
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class Showcase(SessionSingleton):
'''
This class enables other classes to translate names previously registered
to actual objects
'''
def __init__(self):
self._objects = WeakValueDictionary()
self._cases = WeakValueDictionary()
def get(self, oid):
'''
:param str oid: the oid registered in the NameAuthority
'''
return self._objects.get(oid)
def put(self, instance):
'''
:param INamed oid: the exposed object.
'''
self._objects[instance.oid] = instance
def get_case(self, tag, default=None):
'''
:param str tag: The tag that the returned case should have
'''
return self._cases.get(tag, default)
示例2: Monitor
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class Monitor(QObject):
"""File monitor
This monitor can be used to track single files
"""
def __init__(self, **kwargs):
super(Monitor, self).__init__(**kwargs)
self.watched = WeakValueDictionary()
self.delMapper = QSignalMapper(self)
self.delMapper.mapped[str].connect(self.unmonitorFile)
self.watcher = MonitorWithRename(parent=self)
self.watcher.fileChanged.connect(self._onFileChanged)
def monitorFile(self, path):
"""Monitor a file and return an object that tracks only `path`
:rtype: SingleFileWatcher
:return: an object tracking `path`, the same object is returned if the method is called
with the same path.
"""
path = os.path.abspath(path)
self.watcher.addPath(path)
proxy = self.watched.get(path)
if not proxy:
proxy = SingleFileWatcher(path)
proxy.destroyed.connect(self.delMapper.map)
self.delMapper.setMapping(proxy, path)
self.watched[path] = proxy
return proxy
@Slot(str)
def unmonitorFile(self, path):
"""Stop monitoring a file
Since there is only one :any:`SingleFileWatcher` object per path, all objects monitoring
`path` will not receive notifications anymore.
To let only one object stop monitoring the file, simply disconnect its `modified` signal.
When the :any:`SingleFileWatcher` object returned by method :any:`monitorFile` is
destroyed, the file is automatically un-monitored.
"""
path = os.path.abspath(path)
self.watcher.removePath(path)
self.watched.pop(path, None)
@Slot(str)
def _onFileChanged(self, path):
proxy = self.watched.get(path)
if proxy:
proxy.modified.emit()
示例3: _TransformExecutorServices
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class _TransformExecutorServices(object):
"""Schedules and completes TransformExecutors.
Controls the concurrency as appropriate for the applied transform the executor
exists for.
"""
def __init__(self, executor_service):
self._executor_service = executor_service
self._scheduled = set()
self._parallel = _ParallelEvaluationState(
self._executor_service, self._scheduled)
self._serial_cache = WeakValueDictionary()
def parallel(self):
return self._parallel
def serial(self, step):
cached = self._serial_cache.get(step)
if not cached:
cached = _SerialEvaluationState(self._executor_service, self._scheduled)
self._serial_cache[step] = cached
return cached
@property
def executors(self):
return frozenset(self._scheduled)
示例4: HasWeaks
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class HasWeaks(metaclass=HasWeaksMeta):
"""A mix-in to allow objects to store weak references to other objects.
Each individual class or instance of a class that subclasses this will
have a separate weak reference dict, there is no inheritance.
"""
def __init__(self):
super().__init__()
self._get_weak_wr = WeakMethod(self._inst_get_weak)
self._get_weak = lambda k: self._get_weak_wr()(k)
self._set_weak_wr = WeakMethod(self._inst_set_weak)
self._set_weak = lambda k, o: self._set_weak_wr()(k, o)
self._del_weak_wr = WeakMethod(self._inst_del_weak)
self._del_weak = lambda k: self._del_weak_wr()(k)
self._weak_refs = WeakValueDictionary()
def _inst_get_weak(self, name):
return self._weak_refs.get(name)
def _inst_set_weak(self, name, obj):
if obj is None:
self._del_weak(name)
else:
self._weak_refs[name] = obj
def _inst_del_weak(self, name):
if name in self._weak_refs:
del self._weak_refs[name]
示例5: TimerWnd
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class TimerWnd(object):
def __init__(self):
win = ui.CreateFrame()
win.CreateWindow(None, "", 0, (0, 0, 0, 0))
win.AttachObject(self)
self._win = win
self.tasks = WeakValueDictionary()
def schedule(self, task):
self.cancel(task)
event_id = id(task)
timer_id = self._win.SetTimer(event_id, task._milliseconds)
if not timer_id:
raise ValueError("Out of timers")
task._win_timer_id = timer_id
self.tasks[event_id] = task
def cancel(self, task):
timer_id = task._win_timer_id
if timer_id:
self._win.KillTimer(timer_id)
task._win_timer_id = None
def OnTimer(self, event_id):
#print "TimerWnd.OnTimer:", event_id
task = self.tasks.get(event_id)
if task:
if not task._repeat:
self.cancel(task)
task._proc()
# We do this so that the application can't get starved of idle time
# by a repeatedly-firing Task:
application()._win_idle()
示例6: Root
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class Root(Directory):
cls_dir_class = Directory
def __init__(self, dbname=':memory:', dirname='', threaded=True):
super(Root,self).__init__(None,dirname)
if threaded:
self.con = hscommon.sqlite.ThreadedConn(dbname, False)
else:
self.con = sqlite.connect(dbname)
self.id = 0
self._attrs_to_read = None
self._id_cache = WeakValueDictionary()
self._id_cache[0] = self
try:
cur = self.con.execute("select * from nodes where 1=2")
except sqlite.OperationalError:
self.__create_tables()
self._load_from_db()
def __create_tables(self):
sqls = [
'create table nodes(parent INT,type INT,name TEXT);',
'create table attrs(parent INT,name TEXT,type INT,value TEXT);',
'create index idx_node_parent on nodes(parent);',
'create index idx_node_name on nodes(name);',
'create index idx_attr_parent on attrs(parent);',
'create index idx_attr_name on attrs(name);',
'create unique index idx_node_unique on nodes(parent,name);',
'create unique index idx_attr_unique on attrs(parent,name);'
]
for sql in sqls:
self.con.execute(sql)
def find_node_of_id(self,id):
return self._id_cache.get(id)
示例7: __init__
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class LRUCache:
def __init__(self, max_size):
self.LRU = [Node(time(), "none%s"%i) for i in range(max_size)]
self.search = WeakValueDictionary()
for i in self.LRU:
self.search[i.name] = i
def __setitem__(self, name, value):
q = self.search.get(name, None)
if q:
q.data = value
q.time = time()
else:
lru = self.LRU[0]
self.search.pop(lru.name)
lru.data = value
lru.time = time()
lru.name = name
self.search[lru.name] = lru
self.LRU.sort()
def get(self, name, default=None):
pos = None
try:
pos = self.search.__getitem__(name)
pos.time = time()
return pos.data
except KeyError:
if default is not None:
return default
else:
raise
示例8: RecentFiles
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class RecentFiles(object):
numberOfFiles = 8
separator = u";"
def __init__(self, fileManager):
self.fileManager = fileManager
fileManager.onRead.connect(self.onReadOrWrite)
fileManager.onWrite.connect(self.onReadOrWrite)
self.files = self.retrieveList()
self.menu = JMenu("Open Recent Program")
self.menuActions = WeakValueDictionary()
self.disabledItem = JMenuItem("(No recent programs)")
self.disabledItem.enabled = False
self.fillMenu()
### Maintaining the menu
def onReadOrWrite(self, fileManager, filename, **_):
try:
self.files.remove(filename)
except ValueError:
if len(self.files) >= self.numberOfFiles:
# Remove enough files that there's a spare slot.
self.files = self.files[:self.numberOfFiles - 1]
self.files.insert(0, filename)
self.storeList(self.files)
self.fillMenu()
def fillMenu(self):
self.menu.removeAll()
if self.files:
for filename in self.files:
action = self.menuActions.get(filename)
if action is None:
action = PythonAction(self.fileManager.readAction, filename,
name=filename)
self.menuActions[filename] = action
self.menu.add(action)
else:
self.menu.add(self.disabledItem)
### Writing filenames
def retrieveList(self):
joined = JESConfig.getInstance().getStringProperty(JESConfig.CONFIG_RECENT_FILES)
if not joined:
return []
else:
return [fn for fn in joined.split(self.separator) if os.path.isfile(fn)]
def storeList(self, files):
joined = self.separator.join(files)
JESConfig.getInstance().setStringProperty(JESConfig.CONFIG_RECENT_FILES, joined)
示例9: ObjectRedis
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class ObjectRedis(object):
"""
Extended Redis client, which additionally provides object-oriented
operations and object caching.
Objects are represented as hashes in the Redis database. The translation
from a hash to an object is carried out by a given `decode` function.
When `caching` is enabled, objects loaded from the Redis database are cached
and subsequently retrieved from the cache. An object stays in the cache as
long as there is a reference to it and it is automatically removed when the
Python interpreter destroys it. Thus, it is guaranteed that getting the same
key multiple times will yield the identical object.
Attributes:
* `r`: Underlying Redis client. Read-Only.
* `decode`: function, which decodes an object from a Redis hash. It is
called with the hash (a `dict`) as single argument. Read-Only.
* `caching`: switch to enable / disable object caching.
"""
# TODO: add oset and omset
def __init__(self, r, decode, caching=True):
self.r = r
self.decode = decode
self.caching = caching
self._cache = WeakValueDictionary()
def oget(self, key):
"""
Get the object for `key`.
"""
object = self._cache.get(key) if self.caching else None
if not object:
hash = self.hgetall(key)
if hash:
object = self.decode(hash)
if self.caching:
self._cache[key] = object
return object
def omget(self, keys):
"""
Get the objects for all specified `keys`.
"""
# TODO: make atomic
return [self.oget(k) for k in keys]
def __getattr__(self, name):
return getattr(self.r, name)
示例10: ObjectPool
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [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()
示例11: BaseContextualizable
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class BaseContextualizable(object):
def __init__(self, *args, **kwargs):
super(BaseContextualizable, self).__init__(*args, **kwargs)
if not hasattr(self, '_contexts'):
self._contexts = WeakValueDictionary()
@property
def context(self):
return None
def contextualize(self, context):
"""
Return an object with the given context. If the provided ``context`` is
`None`, then `self` MUST be returned unmodified.
It is generally not correct to set a field on the object and return the
same object as this would change the context for other users of the
object. Also, returning a copy of the object is usually inappropriate
for mutable objects. Immutable objects may maintain a 'context'
property and return a copy of themselves with that property set to the
provided ``context`` argument.
"""
ctxd = self._contexts.get(context)
if ctxd is not None:
return ctxd
ctxd = self.contextualize_augment(context)
self._contexts[context] = ctxd
return ctxd
def decontextualize(self):
"""
Return the object with all contexts removed
"""
return self
def add_contextualization(self, context, contextualization):
try:
self._contexts[context] = contextualization
except AttributeError:
self._contexts = WeakValueDictionary()
self._contexts[context] = contextualization
def contextualize_augment(self, context):
return self
示例12: Cache
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class Cache(object):
def __init__(self, config):
self._entries = dict()
# indexed by (domain, user) tuple
self._entry_by_domain = WeakValueDictionary()
self._config = config
def set(self, service, username, password, timeout=None):
expire = None
if timeout:
expire = int(time.time()) + timeout
entry = CacheEntry(username, password, expire)
self._entries[service] = entry
domain = self._config.get_domain_for_service(service)
if domain is not None:
logging.debug("updating password for domain,user = %s,%s", domain, username)
self._entry_by_domain[(domain, username)] = entry
def get(self, service):
entry = self._entries.get(service)
if entry is None:
domain = self._config.get_domain_for_service(service)
username = self._config.get_user_for_service(service)
if domain and username:
logging.debug("searching in domain %s", domain)
entry = self._entry_by_domain.get((domain, username))
if entry is None:
return None
now = int(time.time())
if entry.expire and entry.expire <= now:
del self._entries[service]
# no need to delete from domain dict since is a weakref values
return None
return entry
示例13: WeakLocks
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class WeakLocks(object):
"""
A cache of DeferredLocks that gets garbage collected after the lock has
been utilized
"""
def __init__(self):
self._locks = WeakValueDictionary()
def get_lock(self, key):
"""
Get lock based on key. If no lock exists, create one.
:param key: Some arbitrary key
:return: :class:`DeferredLock`
"""
lock = self._locks.get(key)
if not lock:
lock = DeferredLock()
self._locks[key] = lock
return lock
示例14: SharedSinkProvider
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class SharedSinkProvider(SinkProviderBase):
def __init__(self, key_selector):
self._key_selector = key_selector
self._cache = WeakValueDictionary()
super(SharedSinkProvider, self).__init__()
def CreateSink(self, properties):
key = self._key_selector(properties)
if key:
sink = self._cache.get(key)
if not sink:
new_sink = self.next_provider.CreateSink(properties)
sink = RefCountedSink(new_sink)
self._cache[key] = sink
return sink
else:
return self.next_provider.CreateSink(properties)
@property
def sink_class(self):
return self.next_provider.sink_class
示例15: Layout
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import get [as 别名]
class Layout(object):
def __init__(self):
self.solver = Solver()
self.introns = WeakValueDictionary()
def update(self, element):
self.solver.autosolve = False
for constraint in element.constraints[1]:
self.solver.remove_constraint(constraint)
for constraint in element.constraints[0]:
self.solver.add_constraint(constraint)
element.constraints = [], element.constraints[0]
self.solver.autosolve = True
def add_intron(self, source, intron):
self.introns[source] = intron
def pop_intron(self, source):
return self.introns.pop(source)
def get_intron(self, source, otherwise=None):
return self.introns.get(source, otherwise)