zope.cachedescriptors-3.5.1/bootstrap.py0000644000000000000000000000733611366606164020370 0ustar rootroot00000000000000############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs) zope.cachedescriptors-3.5.1/buildout.cfg0000644000000000000000000000014711155310242020263 0ustar rootroot00000000000000[buildout] develop = . parts = test [test] recipe = zc.recipe.testrunner eggs = zope.cachedescriptors zope.cachedescriptors-3.5.1/CHANGES.txt0000644000000000000000000000132011366606442017574 0ustar rootroot00000000000000======= CHANGES ======= 3.5.1 (2010-04-30) ------------------ - Removed undeclared testing dependency on zope.testing. 3.5.0 (2009-02-10) ------------------ - Remove dependency on ZODB by allowing to specify storage factory for ``zope.cachedescriptors.method.cachedIn`` which is now `dict` by default. If you need to use BTree instead, you must pass it as `factory` argument to the ``zope.cachedescriptors.method.cachedIn`` decorator. - Remove zpkg-related file. - Clean up package description and documentation a bit. - Change package mailing list address to zope-dev at zope.org, as zope3-dev at zope.org is now retired. 3.4.0 (2007-08-30) ------------------ Initial release as an independent package zope.cachedescriptors-3.5.1/PKG-INFO0000644000000000000000000002776211366606502017077 0ustar rootroot00000000000000Metadata-Version: 1.0 Name: zope.cachedescriptors Version: 3.5.1 Summary: Method and property caching decorators Home-page: http://pypi.python.org/pypi/zope.cachedescriptors Author: Zope Corporation and Contributors Author-email: zope-dev@zope.org License: ZPL 2.1 Description: .. contents:: ================== Cached descriptors ================== Cached descriptors cache their output. They take into account instance attributes that they depend on, so when the instance attributes change, the descriptors will change the values they return. Cached descriptors cache their data in _v_ attributes, so they are also useful for managing the computation of volatile attributes for persistent objects. Persistent descriptors: property A simple computed property. See property.txt. method Idempotent method. The return values are cached based on method arguments and on any instance attributes that the methods are defined to depend on. **Note**, only a cache based on arguments has been implemented so far. See method.txt. Cached Properties ----------------- Cached properties are computed properties that cache their computed values. They take into account instance attributes that they depend on, so when the instance attributes change, the properties will change the values they return. CachedProperty ~~~~~~~~~~~~~~ Cached properties cache their data in _v_ attributes, so they are also useful for managing the computation of volatile attributes for persistent objects. Let's look at an example: >>> from zope.cachedescriptors import property >>> import math >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) ... radius = property.CachedProperty(radius, 'x', 'y') >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it will be recomputed: >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' But changing other attributes doesn't cause recomputation: >>> point.q = 1 >>> '%.2f' % point.radius '2.83' Note that we don't have any non-volitile attributes added: >>> names = [name for name in point.__dict__ if not name.startswith('_v_')] >>> names.sort() >>> names ['q', 'x', 'y'] Lazy Computed Attributes ~~~~~~~~~~~~~~~~~~~~~~~~ The `property` module provides another descriptor that supports a slightly different caching model: lazy attributes. Like cached proprties, they are computed the first time they are used. however, they aren't stored in volatile attributes and they aren't automatically updated when other attributes change. Furthermore, the store their data using their attribute name, thus overriding themselves. This provides much faster attribute access after the attribute has been computed. Let's look at the previous example using lazy attributes: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.Lazy ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it still isn't called: >>> point.x = 2.0 >>> '%.2f' % point.radius '2.24' If we want the radius to be recomputed, we have to manually delete it: >>> del point.radius >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' Note that the radius is stored in the instance dictionary: >>> '%.2f' % point.__dict__['radius'] '2.83' The lazy attribute needs to know the attribute name. It normally deduces the attribute name from the name of the function passed. If we want to use a different name, we need to pass it: >>> def d(point): ... print 'computing diameter' ... return 2*point.radius >>> Point.diameter = property.Lazy(d, 'diameter') >>> '%.2f' % point.diameter computing diameter '5.66' readproperty ~~~~~~~~~~~~ readproperties are like lazy computed attributes except that the attribute isn't set by the property: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.readproperty ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius computing radius '2.24' But you *can* replace the property by setting a value. This is the major difference to the builtin `property`: >>> point.radius = 5 >>> point.radius 5 cachedIn ~~~~~~~~ The `cachedIn` property allows to specify the attribute where to store the computed value: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.cachedIn('_radius_attribute') ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius '2.24' The radius is cached in the attribute with the given name, `_radius_attribute` in this case: >>> '%.2f' % point._radius_attribute '2.24' When the attribute is removed the radius is re-calculated once. This allows invalidation: >>> del point._radius_attribute >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius '2.24' Method Cache ------------ cachedIn ~~~~~~~~ The `cachedIn` property allows to specify the attribute where to store the computed value: >>> import math >>> from zope.cachedescriptors import method >>> class Point(object): ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @method.cachedIn('_cache') ... def distance(self, x, y): ... print 'computing distance' ... return math.sqrt((self.x - x)**2 + (self.y - y)**2) ... >>> point = Point(1.0, 2.0) The value is computed once: >>> point.distance(2, 2) computing distance 1.0 >>> point.distance(2, 2) 1.0 Using different arguments calculates a new distance: >>> point.distance(5, 2) computing distance 4.0 >>> point.distance(5, 2) 4.0 The data is stored at the given `_cache` attribute: >>> isinstance(point._cache, dict) True >>> sorted(point._cache.items()) [(((2, 2), ()), 1.0), (((5, 2), ()), 4.0)] It is possible to exlicitly invalidate the data: >>> point.distance.invalidate(point, 5, 2) >>> point.distance(5, 2) computing distance 4.0 Invalidating keys which are not in the cache, does not result in an error: >>> point.distance.invalidate(point, 47, 11) It is possible to pass in a factory for the cache attribute. Create another Point class: >>> class MyDict(dict): ... pass >>> class Point(object): ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @method.cachedIn('_cache', MyDict) ... def distance(self, x, y): ... print 'computing distance' ... return math.sqrt((self.x - x)**2 + (self.y - y)**2) ... >>> point = Point(1.0, 2.0) >>> point.distance(2, 2) computing distance 1.0 Now the cache is a MyDict instance: >>> isinstance(point._cache, MyDict) True ======= CHANGES ======= 3.5.1 (2010-04-30) ------------------ - Removed undeclared testing dependency on zope.testing. 3.5.0 (2009-02-10) ------------------ - Remove dependency on ZODB by allowing to specify storage factory for ``zope.cachedescriptors.method.cachedIn`` which is now `dict` by default. If you need to use BTree instead, you must pass it as `factory` argument to the ``zope.cachedescriptors.method.cachedIn`` decorator. - Remove zpkg-related file. - Clean up package description and documentation a bit. - Change package mailing list address to zope-dev at zope.org, as zope3-dev at zope.org is now retired. 3.4.0 (2007-08-30) ------------------ Initial release as an independent package Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Zope Public License Classifier: Programming Language :: Python Classifier: Operating System :: OS Independent Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Software Development zope.cachedescriptors-3.5.1/README.txt0000644000000000000000000000005211155310242017444 0ustar rootroot00000000000000See src/zope/cachedescriptors/README.txt. zope.cachedescriptors-3.5.1/setup.cfg0000644000000000000000000000007311366606502017605 0ustar rootroot00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 zope.cachedescriptors-3.5.1/setup.py0000644000000000000000000000450011366606464017504 0ustar rootroot00000000000000############################################################################## # # Copyright (c) 2006 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## # This package is developed by the Zope Toolkit project, documented here: # http://docs.zope.org/zopetoolkit # When developing and releasing this package, please follow the documented # Zope Toolkit policies as described by this documentation. ############################################################################## """Setup for zope.cachedescriptors package $Id: setup.py 111680 2010-04-30 18:02:44Z hannosch $ """ import os from setuptools import setup, find_packages def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup( name='zope.cachedescriptors', version='3.5.1', url='http://pypi.python.org/pypi/zope.cachedescriptors', author='Zope Corporation and Contributors', author_email='zope-dev@zope.org', license='ZPL 2.1', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Zope Public License', 'Programming Language :: Python', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development', ], description='Method and property caching decorators', long_description=\ '.. contents::\n\n' + read('src', 'zope', 'cachedescriptors', 'README.txt') + '\n' + read('src', 'zope', 'cachedescriptors', 'property.txt') + '\n' + read('src', 'zope', 'cachedescriptors', 'method.txt') + '\n' + read('CHANGES.txt'), packages=find_packages('src'), package_dir={'': 'src'}, namespace_packages=['zope',], include_package_data=True, install_requires=['setuptools'], zip_safe=False, ) zope.cachedescriptors-3.5.1/src/zope/__init__.py0000644000000000000000000000007011155753750021642 0ustar rootroot00000000000000__import__('pkg_resources').declare_namespace(__name__) zope.cachedescriptors-3.5.1/src/zope/cachedescriptors/__init__.py0000644000000000000000000000000210160372266025154 0ustar rootroot00000000000000# zope.cachedescriptors-3.5.1/src/zope/cachedescriptors/method.py0000644000000000000000000000364610673706760024727 0ustar rootroot00000000000000############################################################################## # Copyright (c) 2007 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. ############################################################################## """Cached Methods $Id: method.py 79733 2007-09-18 09:36:00Z zagy $ """ class cachedIn(object): """Cached method with given cache attribute.""" def __init__(self, attribute_name, factory=dict): self.attribute_name = attribute_name self.factory = factory def __call__(self, func): def decorated(instance, *args, **kwargs): cache = self.cache(instance) key = self._get_cache_key(*args, **kwargs) try: v = cache[key] except KeyError: v = cache[key] = func(instance, *args, **kwargs) return v decorated.invalidate = self.invalidate return decorated def invalidate(self, instance, *args, **kwargs): cache = self.cache(instance) key = self._get_cache_key(*args, **kwargs) try: del cache[key] except KeyError: pass def cache(self, instance): try: cache = getattr(instance, self.attribute_name) except AttributeError: cache = self.factory() setattr(instance, self.attribute_name, cache) return cache @staticmethod def _get_cache_key(*args, **kwargs): kw = kwargs.items() kw.sort() key = (args, tuple(kw)) return key zope.cachedescriptors-3.5.1/src/zope/cachedescriptors/method.txt0000644000000000000000000000365111155310242025070 0ustar rootroot00000000000000Method Cache ------------ cachedIn ~~~~~~~~ The `cachedIn` property allows to specify the attribute where to store the computed value: >>> import math >>> from zope.cachedescriptors import method >>> class Point(object): ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @method.cachedIn('_cache') ... def distance(self, x, y): ... print 'computing distance' ... return math.sqrt((self.x - x)**2 + (self.y - y)**2) ... >>> point = Point(1.0, 2.0) The value is computed once: >>> point.distance(2, 2) computing distance 1.0 >>> point.distance(2, 2) 1.0 Using different arguments calculates a new distance: >>> point.distance(5, 2) computing distance 4.0 >>> point.distance(5, 2) 4.0 The data is stored at the given `_cache` attribute: >>> isinstance(point._cache, dict) True >>> sorted(point._cache.items()) [(((2, 2), ()), 1.0), (((5, 2), ()), 4.0)] It is possible to exlicitly invalidate the data: >>> point.distance.invalidate(point, 5, 2) >>> point.distance(5, 2) computing distance 4.0 Invalidating keys which are not in the cache, does not result in an error: >>> point.distance.invalidate(point, 47, 11) It is possible to pass in a factory for the cache attribute. Create another Point class: >>> class MyDict(dict): ... pass >>> class Point(object): ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @method.cachedIn('_cache', MyDict) ... def distance(self, x, y): ... print 'computing distance' ... return math.sqrt((self.x - x)**2 + (self.y - y)**2) ... >>> point = Point(1.0, 2.0) >>> point.distance(2, 2) computing distance 1.0 Now the cache is a MyDict instance: >>> isinstance(point._cache, MyDict) True zope.cachedescriptors-3.5.1/src/zope/cachedescriptors/property.py0000644000000000000000000000535310620335162025312 0ustar rootroot00000000000000############################################################################## # Copyright (c) 2003 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. ############################################################################## """Cached properties See the CachedProperty class. $Id: property.py 75652 2007-05-09 13:11:30Z zagy $ """ ncaches = 0l class CachedProperty(object): """Cached Properties. """ def __init__(self, func, *names): global ncaches ncaches += 1 self.data = (func, names, "_v_cached_property_key_%s" % ncaches, "_v_cached_property_value_%s" % ncaches) def __get__(self, inst, class_): if inst is None: return self func, names, key_name, value_name = self.data key = names and [getattr(inst, name) for name in names] value = getattr(inst, value_name, self) if value is not self: # We have a cached value if key == getattr(inst, key_name, self): # Cache is still good! return value # We need to compute and cache the value value = func(inst) setattr(inst, key_name, key) setattr(inst, value_name, value) return value class Lazy(object): """Lazy Attributes. """ def __init__(self, func, name=None): if name is None: name = func.__name__ self.data = (func, name) def __get__(self, inst, class_): if inst is None: return self func, name = self.data value = func(inst) inst.__dict__[name] = value return value class readproperty(object): def __init__(self, func): self.func = func def __get__(self, inst, class_): if inst is None: return self func = self.func return func(inst) class cachedIn(object): """Cached property with given cache attribute.""" def __init__(self, attribute_name): self.attribute_name = attribute_name def __call__(self, func): def get(instance): try: value = getattr(instance, self.attribute_name) except AttributeError: value = func(instance) setattr(instance, self.attribute_name, value) return value return property(get) zope.cachedescriptors-3.5.1/src/zope/cachedescriptors/property.txt0000644000000000000000000001224711325530004025474 0ustar rootroot00000000000000Cached Properties ----------------- Cached properties are computed properties that cache their computed values. They take into account instance attributes that they depend on, so when the instance attributes change, the properties will change the values they return. CachedProperty ~~~~~~~~~~~~~~ Cached properties cache their data in _v_ attributes, so they are also useful for managing the computation of volatile attributes for persistent objects. Let's look at an example: >>> from zope.cachedescriptors import property >>> import math >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) ... radius = property.CachedProperty(radius, 'x', 'y') >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it will be recomputed: >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' But changing other attributes doesn't cause recomputation: >>> point.q = 1 >>> '%.2f' % point.radius '2.83' Note that we don't have any non-volitile attributes added: >>> names = [name for name in point.__dict__ if not name.startswith('_v_')] >>> names.sort() >>> names ['q', 'x', 'y'] Lazy Computed Attributes ~~~~~~~~~~~~~~~~~~~~~~~~ The `property` module provides another descriptor that supports a slightly different caching model: lazy attributes. Like cached proprties, they are computed the first time they are used. however, they aren't stored in volatile attributes and they aren't automatically updated when other attributes change. Furthermore, the store their data using their attribute name, thus overriding themselves. This provides much faster attribute access after the attribute has been computed. Let's look at the previous example using lazy attributes: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.Lazy ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it still isn't called: >>> point.x = 2.0 >>> '%.2f' % point.radius '2.24' If we want the radius to be recomputed, we have to manually delete it: >>> del point.radius >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' Note that the radius is stored in the instance dictionary: >>> '%.2f' % point.__dict__['radius'] '2.83' The lazy attribute needs to know the attribute name. It normally deduces the attribute name from the name of the function passed. If we want to use a different name, we need to pass it: >>> def d(point): ... print 'computing diameter' ... return 2*point.radius >>> Point.diameter = property.Lazy(d, 'diameter') >>> '%.2f' % point.diameter computing diameter '5.66' readproperty ~~~~~~~~~~~~ readproperties are like lazy computed attributes except that the attribute isn't set by the property: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.readproperty ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius computing radius '2.24' But you *can* replace the property by setting a value. This is the major difference to the builtin `property`: >>> point.radius = 5 >>> point.radius 5 cachedIn ~~~~~~~~ The `cachedIn` property allows to specify the attribute where to store the computed value: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.cachedIn('_radius_attribute') ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius '2.24' The radius is cached in the attribute with the given name, `_radius_attribute` in this case: >>> '%.2f' % point._radius_attribute '2.24' When the attribute is removed the radius is re-calculated once. This allows invalidation: >>> del point._radius_attribute >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius '2.24' zope.cachedescriptors-3.5.1/src/zope/cachedescriptors/README.txt0000644000000000000000000000141211155310242024536 0ustar rootroot00000000000000================== Cached descriptors ================== Cached descriptors cache their output. They take into account instance attributes that they depend on, so when the instance attributes change, the descriptors will change the values they return. Cached descriptors cache their data in _v_ attributes, so they are also useful for managing the computation of volatile attributes for persistent objects. Persistent descriptors: property A simple computed property. See property.txt. method Idempotent method. The return values are cached based on method arguments and on any instance attributes that the methods are defined to depend on. **Note**, only a cache based on arguments has been implemented so far. See method.txt. zope.cachedescriptors-3.5.1/src/zope/cachedescriptors/tests.py0000644000000000000000000000152711366606202024573 0ustar rootroot00000000000000############################################################################## # # Copyright (c) 2004 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Test hookup $Id: tests.py 111678 2010-04-30 17:59:46Z hannosch $ """ import doctest def test_suite(): return doctest.DocFileSuite( 'property.txt', 'method.txt', optionflags=doctest.ELLIPSIS) zope.cachedescriptors-3.5.1/src/zope.cachedescriptors.egg-info/dependency_links.txt0000644000000000000000000000000111366606502030614 0ustar rootroot00000000000000 zope.cachedescriptors-3.5.1/src/zope.cachedescriptors.egg-info/namespace_packages.txt0000644000000000000000000000000511366606502031074 0ustar rootroot00000000000000zope zope.cachedescriptors-3.5.1/src/zope.cachedescriptors.egg-info/not-zip-safe0000644000000000000000000000000111366606222026773 0ustar rootroot00000000000000 zope.cachedescriptors-3.5.1/src/zope.cachedescriptors.egg-info/PKG-INFO0000644000000000000000000002776211366606502025661 0ustar rootroot00000000000000Metadata-Version: 1.0 Name: zope.cachedescriptors Version: 3.5.1 Summary: Method and property caching decorators Home-page: http://pypi.python.org/pypi/zope.cachedescriptors Author: Zope Corporation and Contributors Author-email: zope-dev@zope.org License: ZPL 2.1 Description: .. contents:: ================== Cached descriptors ================== Cached descriptors cache their output. They take into account instance attributes that they depend on, so when the instance attributes change, the descriptors will change the values they return. Cached descriptors cache their data in _v_ attributes, so they are also useful for managing the computation of volatile attributes for persistent objects. Persistent descriptors: property A simple computed property. See property.txt. method Idempotent method. The return values are cached based on method arguments and on any instance attributes that the methods are defined to depend on. **Note**, only a cache based on arguments has been implemented so far. See method.txt. Cached Properties ----------------- Cached properties are computed properties that cache their computed values. They take into account instance attributes that they depend on, so when the instance attributes change, the properties will change the values they return. CachedProperty ~~~~~~~~~~~~~~ Cached properties cache their data in _v_ attributes, so they are also useful for managing the computation of volatile attributes for persistent objects. Let's look at an example: >>> from zope.cachedescriptors import property >>> import math >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) ... radius = property.CachedProperty(radius, 'x', 'y') >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it will be recomputed: >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' But changing other attributes doesn't cause recomputation: >>> point.q = 1 >>> '%.2f' % point.radius '2.83' Note that we don't have any non-volitile attributes added: >>> names = [name for name in point.__dict__ if not name.startswith('_v_')] >>> names.sort() >>> names ['q', 'x', 'y'] Lazy Computed Attributes ~~~~~~~~~~~~~~~~~~~~~~~~ The `property` module provides another descriptor that supports a slightly different caching model: lazy attributes. Like cached proprties, they are computed the first time they are used. however, they aren't stored in volatile attributes and they aren't automatically updated when other attributes change. Furthermore, the store their data using their attribute name, thus overriding themselves. This provides much faster attribute access after the attribute has been computed. Let's look at the previous example using lazy attributes: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.Lazy ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it still isn't called: >>> point.x = 2.0 >>> '%.2f' % point.radius '2.24' If we want the radius to be recomputed, we have to manually delete it: >>> del point.radius >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' Note that the radius is stored in the instance dictionary: >>> '%.2f' % point.__dict__['radius'] '2.83' The lazy attribute needs to know the attribute name. It normally deduces the attribute name from the name of the function passed. If we want to use a different name, we need to pass it: >>> def d(point): ... print 'computing diameter' ... return 2*point.radius >>> Point.diameter = property.Lazy(d, 'diameter') >>> '%.2f' % point.diameter computing diameter '5.66' readproperty ~~~~~~~~~~~~ readproperties are like lazy computed attributes except that the attribute isn't set by the property: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.readproperty ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius computing radius '2.24' But you *can* replace the property by setting a value. This is the major difference to the builtin `property`: >>> point.radius = 5 >>> point.radius 5 cachedIn ~~~~~~~~ The `cachedIn` property allows to specify the attribute where to store the computed value: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.cachedIn('_radius_attribute') ... def radius(self): ... print 'computing radius' ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius '2.24' The radius is cached in the attribute with the given name, `_radius_attribute` in this case: >>> '%.2f' % point._radius_attribute '2.24' When the attribute is removed the radius is re-calculated once. This allows invalidation: >>> del point._radius_attribute >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius '2.24' Method Cache ------------ cachedIn ~~~~~~~~ The `cachedIn` property allows to specify the attribute where to store the computed value: >>> import math >>> from zope.cachedescriptors import method >>> class Point(object): ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @method.cachedIn('_cache') ... def distance(self, x, y): ... print 'computing distance' ... return math.sqrt((self.x - x)**2 + (self.y - y)**2) ... >>> point = Point(1.0, 2.0) The value is computed once: >>> point.distance(2, 2) computing distance 1.0 >>> point.distance(2, 2) 1.0 Using different arguments calculates a new distance: >>> point.distance(5, 2) computing distance 4.0 >>> point.distance(5, 2) 4.0 The data is stored at the given `_cache` attribute: >>> isinstance(point._cache, dict) True >>> sorted(point._cache.items()) [(((2, 2), ()), 1.0), (((5, 2), ()), 4.0)] It is possible to exlicitly invalidate the data: >>> point.distance.invalidate(point, 5, 2) >>> point.distance(5, 2) computing distance 4.0 Invalidating keys which are not in the cache, does not result in an error: >>> point.distance.invalidate(point, 47, 11) It is possible to pass in a factory for the cache attribute. Create another Point class: >>> class MyDict(dict): ... pass >>> class Point(object): ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @method.cachedIn('_cache', MyDict) ... def distance(self, x, y): ... print 'computing distance' ... return math.sqrt((self.x - x)**2 + (self.y - y)**2) ... >>> point = Point(1.0, 2.0) >>> point.distance(2, 2) computing distance 1.0 Now the cache is a MyDict instance: >>> isinstance(point._cache, MyDict) True ======= CHANGES ======= 3.5.1 (2010-04-30) ------------------ - Removed undeclared testing dependency on zope.testing. 3.5.0 (2009-02-10) ------------------ - Remove dependency on ZODB by allowing to specify storage factory for ``zope.cachedescriptors.method.cachedIn`` which is now `dict` by default. If you need to use BTree instead, you must pass it as `factory` argument to the ``zope.cachedescriptors.method.cachedIn`` decorator. - Remove zpkg-related file. - Clean up package description and documentation a bit. - Change package mailing list address to zope-dev at zope.org, as zope3-dev at zope.org is now retired. 3.4.0 (2007-08-30) ------------------ Initial release as an independent package Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Zope Public License Classifier: Programming Language :: Python Classifier: Operating System :: OS Independent Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Software Development zope.cachedescriptors-3.5.1/src/zope.cachedescriptors.egg-info/requires.txt0000644000000000000000000000001211366606502027137 0ustar rootroot00000000000000setuptoolszope.cachedescriptors-3.5.1/src/zope.cachedescriptors.egg-info/SOURCES.txt0000644000000000000000000000126011366606502026431 0ustar rootroot00000000000000CHANGES.txt README.txt bootstrap.py buildout.cfg setup.py src/zope/__init__.py src/zope.cachedescriptors.egg-info/PKG-INFO src/zope.cachedescriptors.egg-info/SOURCES.txt src/zope.cachedescriptors.egg-info/dependency_links.txt src/zope.cachedescriptors.egg-info/namespace_packages.txt src/zope.cachedescriptors.egg-info/not-zip-safe src/zope.cachedescriptors.egg-info/requires.txt src/zope.cachedescriptors.egg-info/top_level.txt src/zope/cachedescriptors/README.txt src/zope/cachedescriptors/__init__.py src/zope/cachedescriptors/method.py src/zope/cachedescriptors/method.txt src/zope/cachedescriptors/property.py src/zope/cachedescriptors/property.txt src/zope/cachedescriptors/tests.pyzope.cachedescriptors-3.5.1/src/zope.cachedescriptors.egg-info/top_level.txt0000644000000000000000000000000511366606502027273 0ustar rootroot00000000000000zope