lazr.delegates-2.0.3/0000775000175000017500000000000012547235462014714 5ustar barrybarry00000000000000lazr.delegates-2.0.3/MANIFEST.in0000664000175000017500000000014112547230200016427 0ustar barrybarry00000000000000include *.py *.txt *.rst MANIFEST.in *.ini recursive-include lazr *.txt *.rst exclude .bzrignore lazr.delegates-2.0.3/lazr.delegates.egg-info/0000775000175000017500000000000012547235462021312 5ustar barrybarry00000000000000lazr.delegates-2.0.3/lazr.delegates.egg-info/SOURCES.txt0000664000175000017500000000151212547235462023175 0ustar barrybarry00000000000000COPYING.txt HACKING.rst MANIFEST.in README.rst conf.py setup.cfg setup.py tox.ini lazr/__init__.py lazr.delegates.egg-info/PKG-INFO lazr.delegates.egg-info/SOURCES.txt lazr.delegates.egg-info/dependency_links.txt lazr.delegates.egg-info/namespace_packages.txt lazr.delegates.egg-info/not-zip-safe lazr.delegates.egg-info/requires.txt lazr.delegates.egg-info/top_level.txt lazr/delegates/__init__.py lazr/delegates/_delegates.py lazr/delegates/_passthrough.py lazr/delegates/_python2.py lazr/delegates/_python3.py lazr/delegates/version.txt lazr/delegates/docs/NEWS.rst lazr/delegates/docs/__init__.py lazr/delegates/docs/fixture.py lazr/delegates/docs/usage.rst lazr/delegates/docs/usage_fixture.py lazr/delegates/tests/__init__.py lazr/delegates/tests/test_api.py lazr/delegates/tests/test_passthrough.py lazr/delegates/tests/test_python2.pylazr.delegates-2.0.3/lazr.delegates.egg-info/requires.txt0000664000175000017500000000003712547235462023712 0ustar barrybarry00000000000000nose setuptools zope.interface lazr.delegates-2.0.3/lazr.delegates.egg-info/top_level.txt0000664000175000017500000000000512547235462024037 0ustar barrybarry00000000000000lazr lazr.delegates-2.0.3/lazr.delegates.egg-info/dependency_links.txt0000664000175000017500000000000112547235462025360 0ustar barrybarry00000000000000 lazr.delegates-2.0.3/lazr.delegates.egg-info/namespace_packages.txt0000664000175000017500000000000512547235462025640 0ustar barrybarry00000000000000lazr lazr.delegates-2.0.3/lazr.delegates.egg-info/not-zip-safe0000664000175000017500000000000112547235462023540 0ustar barrybarry00000000000000 lazr.delegates-2.0.3/lazr.delegates.egg-info/PKG-INFO0000664000175000017500000000204412547235462022407 0ustar barrybarry00000000000000Metadata-Version: 1.1 Name: lazr.delegates Version: 2.0.3 Summary: Easily write objects that delegate behavior Home-page: https://launchpad.net/lazr.delegates Author: LAZR Developers Author-email: lazr-developers@lists.launchpad.net License: LGPL v3 Download-URL: https://launchpad.net/lazr.delegates/+download Description: The ``lazr.delegates`` package makes it easy to write objects that delegate behavior to another object. The new object adds some property or behavior on to the other object, while still providing the underlying interface, and delegating behavior. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 lazr.delegates-2.0.3/setup.py0000775000175000017500000000446612547230200016424 0ustar barrybarry00000000000000# Copyright 2008-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . from setuptools import setup, find_packages __version__ = open("lazr/delegates/version.txt").read().strip() setup( name='lazr.delegates', version=__version__, namespace_packages=['lazr'], packages=find_packages(), include_package_data=True, zip_safe=False, maintainer='LAZR Developers', maintainer_email='lazr-developers@lists.launchpad.net', description='Easily write objects that delegate behavior', long_description=""" The ``lazr.delegates`` package makes it easy to write objects that delegate behavior to another object. The new object adds some property or behavior on to the other object, while still providing the underlying interface, and delegating behavior. """, license='LGPL v3', install_requires=[ 'nose', 'setuptools', 'zope.interface', ], url='https://launchpad.net/lazr.delegates', download_url= 'https://launchpad.net/lazr.delegates/+download', classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], # nose plugins don't really work with `python setup.py test` so use # `python setup.py nosetests` instead, or just `tox`. Gosh, we really # should switch to nose2. :/ - BAW 2014-08-20 #test_suite='nose.collector', ) lazr.delegates-2.0.3/setup.cfg0000664000175000017500000000042512547235462016536 0ustar barrybarry00000000000000[nosetests] verbosity = 3 with-coverage = 1 with-doctest = 1 doctest-extension = .rst doctest-options = +ELLIPSIS,+NORMALIZE_WHITESPACE,+REPORT_NDIFF doctest-fixtures = _fixture cover-package = lazr.delegates pdb = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 lazr.delegates-2.0.3/lazr/0000775000175000017500000000000012547235462015664 5ustar barrybarry00000000000000lazr.delegates-2.0.3/lazr/__init__.py0000664000175000017500000000162512547232123017770 0ustar barrybarry00000000000000# Copyright 2008-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . # This is a namespace package. try: import pkg_resources pkg_resources.declare_namespace(__name__) except ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__) lazr.delegates-2.0.3/lazr/delegates/0000775000175000017500000000000012547235462017621 5ustar barrybarry00000000000000lazr.delegates-2.0.3/lazr/delegates/docs/0000775000175000017500000000000012547235462020551 5ustar barrybarry00000000000000lazr.delegates-2.0.3/lazr/delegates/docs/fixture.py0000664000175000017500000000234412547230200022575 0ustar barrybarry00000000000000# Copyright 2009-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Doctest fixtures for running under nose.""" from __future__ import absolute_import, print_function, unicode_literals __metaclass__ = type __all__ = [ 'globs', ] def globs(globs): """Set up globals for doctests.""" # Enable future statements to make Python 2 act more like Python 3. globs['absolute_import'] = absolute_import globs['print_function'] = print_function globs['unicode_literals'] = unicode_literals # Provide a convenient way to clean things up at the end of the test. return globs lazr.delegates-2.0.3/lazr/delegates/docs/NEWS.rst0000664000175000017500000000253312547232000022043 0ustar barrybarry00000000000000======================= NEWS for lazr.delegates ======================= 2.0.3 (2015-07-08) ================== - Restore the public import of ``lazr.delegates.Passthrough`` which was inadvertently lost during the port to Python 3. - Officially add support for Python 3.5. - Drop official Python 2.6 support. 2.0.2 (2015-01-05) ================== - Always use old-style namespace package registration in ``lazr/__init__.py`` since the mere presence of this file subverts PEP 420 style namespace packages. (LP: #1407816) 2.0.1 (2014-08-21) ================== - Drop the use of `distribute` in favor of `setuptools`. (LP: #1359927) - Run the test suite with `tox`. 2.0 (2013-01-10) ================ - Port to Python 3, which requires the use of the ``@delegate_to`` class decorator instead of the ``delegates()`` function call. Officially support Python 2.6, 2.7, 3.2, and 3.3. 1.2.0 (2010-07-16) ================== - Extend Passthrough so that it takes an extra (optional) callable argument, used to adapt the context before accessing the delegated attribute. 1.1.0 (2009-08-31) ================== - Remove build dependencies on bzr and egg_info - remove sys.path hack in setup.py for __version__ 1.0.1 (2009-03-24) ================== - specify only v3 of LGPL - build/developer improvements 1.0 (2008-12-19) ================ - Initial release lazr.delegates-2.0.3/lazr/delegates/docs/usage.rst0000664000175000017500000000737112547230200022400 0ustar barrybarry00000000000000============== lazr.delegates ============== The ``lazr.delegates`` package makes it easy to write objects that delegate behavior to another object. The new object adds some property or behavior on to the other object, while still providing the underlying interface, and delegating behavior. Usage ===== The ``@delegate_to`` class decorator makes a class implement zero or more interfaces by delegating the implementation to another object. In the case of a class providing an adapter, that object will be the *context*, but it can really be any object stored in an attribute. So while the interfaces use an inheritance mechanism, the classes use a composition mechanism. For example, we can define two interfaces ``IFoo0`` and ``IFoo1`` where the latter inherits from the former. The first interface defines an attribute. >>> from zope.interface import Interface, Attribute >>> class IFoo0(Interface): ... one = Attribute('attribute in IFoo0') The second (i.e. derived) interface defines a method and an attribute. >>> class IFoo1(IFoo0): ... def bar(): ... """A method in IFoo1""" ... baz = Attribute('attribute in IFoo1') We also define two classes that mirror the interfaces, and do something interesting. :: >>> class Foo0: ... one = 'one' >>> class Foo1(Foo0): ... def bar(self): ... return 'bar' ... baz = 'I am baz' Finally, to tie everything together, we can define a class that delegates the implementation of ``IFoo1`` to an attribute on the instance. By default, ``self.context`` is used as the delegate attribute. >>> from lazr.delegates import delegate_to >>> @delegate_to(IFoo1) ... class SomeClass: ... def __init__(self, context): ... self.context = context When the class doing the delegation is instantiated, an instance of the class implementing the interface is passed in. >>> delegate = Foo1() >>> s = SomeClass(delegate) Now, the ``bar()`` method comes from ``Foo1``. >>> print(s.bar()) bar The ``baz`` attribute also comes from ``Foo1``. >>> print(s.baz) I am baz The ``one`` attribute comes from ``Foo0``. >>> print(s.one) one Even though the interface of ``SomeClass`` is defined through the delegate, the interface is still provided by the instance. >>> IFoo1.providedBy(s) True Custom context -------------- The ``@delegate_to`` decorator takes an optional keyword argument to customize the attribute containing the object to delegate to. >>> @delegate_to(IFoo1, context='myfoo') ... class SomeOtherClass: ... def __init__(self, foo): ... self.myfoo = foo The attributes and methods are still delegated correctly. >>> s = SomeOtherClass(delegate) >>> print(s.bar()) bar >>> print(s.baz) I am baz Multiple interfaces =================== The ``@delegate_to`` decorator accepts more than one interface. Note however, that the context attribute must implement all of the named interfaces. >>> class IFoo2(Interface): ... another = Attribute('another attribute') Here is a class that implements the interface. It inherits from the implementation class that provides the ``IFoo0`` interface. Thus does this class implement both interfaces. >>> class Foo2(Foo0): ... another = 'I am another foo' Again, we tie it all together. >>> @delegate_to(IFoo0, IFoo2) ... class SomeOtherClass: ... def __init__(self, context): ... self.context = context Now, the instance of this class has all the expected attributes, and provides the expected interfaces. >>> s = SomeOtherClass(Foo2()) >>> print(s.another) I am another foo >>> IFoo0.providedBy(s) True >>> IFoo2.providedBy(s) True lazr.delegates-2.0.3/lazr/delegates/docs/__init__.py0000664000175000017500000000000012547230200022631 0ustar barrybarry00000000000000lazr.delegates-2.0.3/lazr/delegates/docs/usage_fixture.py0000664000175000017500000000165112547230200023761 0ustar barrybarry00000000000000# Copyright 2009-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Doctest fixtures for running under nose.""" from __future__ import absolute_import, print_function, unicode_literals __metaclass__ = type __all__ = [ 'globs', ] from lazr.delegates.docs.fixture import globs lazr.delegates-2.0.3/lazr/delegates/_python3.py0000664000175000017500000000254112547230200021721 0ustar barrybarry00000000000000# Copyright 2014-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Class decorator definition for Python 3. This syntax is not legal in Python 2. """ from zope.interface import classImplements from lazr.delegates._passthrough import Passthrough def delegate_to(*interfaces, context='context'): if len(interfaces) == 0: raise TypeError('At least one interface is required') def _decorator(cls): missing = object() for interface in interfaces: classImplements(cls, interface) for name in interface: if getattr(cls, name, missing) is missing: setattr(cls, name, Passthrough(name, context)) return cls return _decorator lazr.delegates-2.0.3/lazr/delegates/_delegates.py0000664000175000017500000000662212547230200022256 0ustar barrybarry00000000000000# Copyright 2008-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Decorator helpers that simplify class composition.""" from __future__ import absolute_import, print_function, unicode_literals __metaclass__ = type __all__ = [ 'delegates', ] import sys from types import ClassType from zope.interface.advice import addClassAdvisor from zope.interface import classImplements from zope.interface.interfaces import IInterface from lazr.delegates._passthrough import Passthrough def delegates(interface_spec, context='context'): """Make an adapter into a decorator. Use like: class RosettaProject: implements(IRosettaProject) delegates(IProject) def __init__(self, context): self.context = context def methodFromRosettaProject(self): return self.context.methodFromIProject() If you want to use a different name than "context" then you can explicitly say so: class RosettaProject: implements(IRosettaProject) delegates(IProject, context='project') def __init__(self, project): self.project = project def methodFromRosettaProject(self): return self.project.methodFromIProject() The adapter class will implement the interface it is decorating. The minimal decorator looks like this: class RosettaProject: delegates(IProject) def __init__(self, context): self.context = context """ # pylint: disable-msg=W0212 frame = sys._getframe(1) locals = frame.f_locals # Try to make sure we were called from a class def if (locals is frame.f_globals) or ('__module__' not in locals): raise TypeError( "delegates() can be used only from a class definition.") locals['__delegates_advice_data__'] = interface_spec, context addClassAdvisor(_delegates_advice, depth=2) def _delegates_advice(cls): """Add a Passthrough class for each missing interface attribute. This function connects the decorator class to the delegate class. Only new-style classes are supported. """ interface_spec, contextvar = cls.__dict__['__delegates_advice_data__'] del cls.__delegates_advice_data__ if isinstance(cls, ClassType): raise TypeError( 'Cannot use delegates() on a classic class: %s.' % cls) if IInterface.providedBy(interface_spec): interfaces = [interface_spec] else: interfaces = interface_spec not_found = object() for interface in interfaces: classImplements(cls, interface) for name in interface: if getattr(cls, name, not_found) is not_found: setattr(cls, name, Passthrough(name, contextvar)) return cls lazr.delegates-2.0.3/lazr/delegates/_passthrough.py0000664000175000017500000000364412547230200022671 0ustar barrybarry00000000000000# Copyright 2008-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . from __future__ import absolute_import, print_function, unicode_literals __metaclass__ = type __all__ = [ 'Passthrough', ] class Passthrough: """Call the delegated class for the decorator class. If the ``adaptation`` argument is not None, it should be a callable. It will be called with the context, and should return an object that will have the delegated attribute. The ``adaptation`` argument is expected to be used with an interface, to adapt the context. """ def __init__(self, name, contextvar, adaptation=None): self.name = name self.contextvar = contextvar self.adaptation = adaptation def __get__(self, inst, cls=None): if inst is None: return self else: context = getattr(inst, self.contextvar) if self.adaptation is not None: context = self.adaptation(context) return getattr(context, self.name) def __set__(self, inst, value): context = getattr(inst, self.contextvar) if self.adaptation is not None: context = self.adaptation(context) setattr(context, self.name, value) def __delete__(self, inst): raise NotImplementedError lazr.delegates-2.0.3/lazr/delegates/version.txt0000664000175000017500000000000612547232566022045 0ustar barrybarry000000000000002.0.3 lazr.delegates-2.0.3/lazr/delegates/__init__.py0000664000175000017500000000246712547230200021724 0ustar barrybarry00000000000000# Copyright 2008-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Decorator helpers that simplify class composition.""" __all__ = [ 'delegate_to', ] import pkg_resources __version__ = pkg_resources.resource_string( "lazr.delegates", "version.txt").strip() from lazr.delegates._passthrough import Passthrough # The class decorator syntax is different in Python 2 vs. Python 3. import sys if sys.version_info[0] == 2: from lazr.delegates._python2 import delegate_to # The legacy API is only compatible with Python 2. from lazr.delegates._delegates import delegates __all__.append('delegates') else: from lazr.delegates._python3 import delegate_to lazr.delegates-2.0.3/lazr/delegates/_python2.py0000664000175000017500000000263412547230200021723 0ustar barrybarry00000000000000# Copyright 2014-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Class decorator definition for Python 2.""" from zope.interface import classImplements from lazr.delegates._passthrough import Passthrough def delegate_to(*interfaces, **kws): context = kws.pop('context', 'context') if len(kws) > 0: raise TypeError('Too many arguments') if len(interfaces) == 0: raise TypeError('At least one interface is required') def _decorator(cls): missing = object() for interface in interfaces: classImplements(cls, interface) for name in interface: if getattr(cls, name, missing) is missing: setattr(cls, name, Passthrough(name, context)) return cls return _decorator lazr.delegates-2.0.3/lazr/delegates/tests/0000775000175000017500000000000012547235462020763 5ustar barrybarry00000000000000lazr.delegates-2.0.3/lazr/delegates/tests/test_api.py0000664000175000017500000000213312547230200023125 0ustar barrybarry00000000000000# Copyright 2013-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Test the new API.""" import unittest from lazr.delegates import delegate_to class TestAPI(unittest.TestCase): """Test various corner cases in the API.""" def test_no_interfaces(self): try: @delegate_to() class SomeClass(object): pass except TypeError: pass else: self.fail('TypeError expected') lazr.delegates-2.0.3/lazr/delegates/tests/test_python2.py0000664000175000017500000001127512547230200023766 0ustar barrybarry00000000000000# Copyright 2013-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Test the legacy API, which only works in Python 2. All of these tests are copied almost verbatim from the old README.rst. """ from __future__ import absolute_import, print_function, unicode_literals # Don't enable the following or we can't test classic class failures. #__metaclass__ = type __all__ = [ 'TestLegacyAPI', ] import sys import unittest from zope.interface import Attribute, Interface, implements, providedBy from lazr.delegates import delegate_to if sys.version_info[0] == 2: from lazr.delegates import delegates class IFoo0(Interface): spoo = Attribute('attribute in IFoo0') class IFoo(IFoo0): def bar(): 'some method' baz = Attribute('some attribute') class BaseFoo0: spoo = 'some spoo' class BaseFoo(BaseFoo0): def bar(self): return 'bar' baz = 'hi baz!' class IOther(Interface): another = Attribute('another attribute') class BaseOtherFoo(BaseFoo): another = 'yes, another' # Python 2.6 doesn't have skips. def skip_python3(cls): if sys.version_info[0] > 2: return None return cls @skip_python3 class TestLegacyAPI(unittest.TestCase): def test_basic_usage(self): class SomeClass(object): delegates(IFoo) def __init__(self, context): self.context = context f = BaseFoo() s = SomeClass(f) self.assertEqual(s.bar(), 'bar') self.assertEqual(s.baz, 'hi baz!') self.assertEqual(s.spoo, 'some spoo') self.assertTrue(IFoo.providedBy(s)) def test_keyword_context(self): class SomeOtherClass(object): delegates(IFoo, context='myfoo') def __init__(self, foo): self.myfoo = foo spoo = 'spoo from SomeOtherClass' f = BaseFoo() s = SomeOtherClass(f) self.assertEqual(s.bar(), 'bar') self.assertEqual(s.baz, 'hi baz!') self.assertEqual(s.spoo, 'spoo from SomeOtherClass') s.baz = 'fish' self.assertEqual(s.baz, 'fish') self.assertEqual(f.baz, 'fish') def test_classic_is_error(self): try: class SomeClassicClass: delegates(IFoo) except TypeError: pass else: self.fail('TypeError expected') def test_use_outside_class_is_error(self): self.assertRaises(TypeError, delegates, IFoo) def test_multiple_interfaces(self): class SomeOtherClass(object): delegates([IFoo, IOther]) s = SomeOtherClass() s.context = BaseOtherFoo() self.assertEqual(s.another, 'yes, another') self.assertEqual(s.baz, 'hi baz!') self.assertEqual(s.spoo, 'some spoo') self.assertTrue(IFoo.providedBy(s)) self.assertTrue(IOther.providedBy(s)) def test_decorate_existing_object(self): class MoreFoo(BaseFoo, BaseOtherFoo): implements([IFoo, IOther]) foo = MoreFoo() class WithExtraTeapot(object): delegates(providedBy(foo)) teapot = 'i am a teapot' foo_with_teapot = WithExtraTeapot() foo_with_teapot.context = foo self.assertEqual(foo_with_teapot.baz, 'hi baz!') self.assertEqual(foo_with_teapot.another, 'yes, another') self.assertEqual(foo_with_teapot.teapot, 'i am a teapot') self.assertTrue(IFoo.providedBy(foo_with_teapot)) self.assertTrue(IOther.providedBy(foo_with_teapot)) @skip_python3 class TestNewAPI(unittest.TestCase): """Test corner cases in Python 2. Most of the new API is tested in the doctest. The implementation of the new API is different between Python 2 and Python 3, so test these corner cases. """ def test_type_error(self): # Too many arguments to @delegate_to() raises a TypeError. try: @delegate_to(IFoo0, context='myfoo', other='bogus') class SomeClass(object): pass except TypeError: pass else: self.fail('TypeError expected') lazr.delegates-2.0.3/lazr/delegates/tests/__init__.py0000664000175000017500000000000012547230200023043 0ustar barrybarry00000000000000lazr.delegates-2.0.3/lazr/delegates/tests/test_passthrough.py0000664000175000017500000000550712547230200024733 0ustar barrybarry00000000000000# Copyright 2013-2015 Canonical Ltd. All rights reserved. # # This file is part of lazr.delegates. # # lazr.delegates is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License. # # lazr.delegates is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with lazr.delegates. If not, see . """Test the Passthrough implementation.""" import unittest from lazr.delegates import Passthrough class Base: foo = 'foo from Base' @classmethod def clsmethod(cls): return cls.__name__ class TestPassthrough(unittest.TestCase): def setUp(self): self.p = Passthrough('foo', 'mycontext') self.p2 = Passthrough('clsmethod', 'mycontext') self.base = Base() class Adapter: mycontext = self.base self.Adapter = Adapter self.adapter = Adapter() def test_get(self): self.assertEqual(self.p.__get__(self.adapter), 'foo from Base') self.assertTrue(self.p.__get__(None, self.Adapter) is self.p) self.assertEqual(self.p2.__get__(self.adapter)(), 'Base') def test_set(self): self.p.__set__(self.adapter, 'new value') self.assertEqual(self.base.foo, 'new value') def test_no_delete(self): self.assertRaises(NotImplementedError, self.p.__delete__, self.adapter) def test_adaptation(self): # Passthrough's third argument (adaptation) is optional and, when # provided, should be a zope.interface.Interface subclass (although in # practice any callable will do) to which the instance is adapted # before getting/setting the delegated attribute. class HasNoFoo(object): _foo = 1 no_foo = HasNoFoo() # ... but IHasFooAdapter uses HasNoFoo._foo to provide its own .foo, # so it works like an adapter for HasNoFoo into some interface that # provides a 'foo' attribute. class IHasFooAdapter(object): def __init__(self, inst): self.inst = inst @property def foo(self): return self.inst._foo @foo.setter def foo(self, value): self.inst._foo = value class Example(object): context = no_foo p = Passthrough('foo', 'context', adaptation=IHasFooAdapter) e = Example() self.assertEqual(p.__get__(e), 1) p.__set__(e, 2) self.assertEqual(p.__get__(e), 2) lazr.delegates-2.0.3/conf.py0000664000175000017500000002045412547231675016222 0ustar barrybarry00000000000000# -*- coding: utf-8 -*- # # lazr.delegates documentation build configuration file, created by # sphinx-quickstart on Mon Jan 7 10:37:37 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. from __future__ import print_function import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'README' # General information about the project. project = u'lazr.delegates' copyright = u'2013-2015, LAZR developers' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = open('lazr/delegates/version.txt').read().strip() # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', 'eggs'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'lazrdelegatesdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'lazrdelegates.tex', u'lazr.delegates Documentation', u'LAZR developers', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'lazrdelegates', u'lazr.delegates Documentation', [u'LAZR developers'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'lazrdelegates', u'lazr.delegates Documentation', u'LAZR developers', 'lazrdelegates', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # Make upload to packages.python.org happy. def index_html(): import errno cwd = os.getcwd() try: try: os.makedirs('build/sphinx/html') except OSError as error: if error.errno != errno.EEXIST: raise os.chdir('build/sphinx/html') try: os.symlink('README.html', 'index.html') print('index.html -> README.html') except OSError as error: if error.errno != errno.EEXIST: raise finally: os.chdir(cwd) import atexit atexit.register(index_html) lazr.delegates-2.0.3/tox.ini0000664000175000017500000000013112547230200016203 0ustar barrybarry00000000000000[tox] envlist = py27,py32,py33,py34,py35 [testenv] commands = python setup.py nosetests lazr.delegates-2.0.3/HACKING.rst0000664000175000017500000000272112547230200016475 0ustar barrybarry00000000000000.. This file is part of lazr.delegates. lazr.delegates is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. lazr.delegates is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with lazr.delegates. If not, see . ========================= Hacking on lazr.delegates ========================= These are guidelines for hacking on the lazr.delegates project. But first, please see the common hacking guidelines at: http://dev.launchpad.net/Hacking Getting help ------------ If you find bugs in this package, you can report them here: https://launchpad.net/lazr.delegates If you want to discuss this package, join the team and mailing list here: https://launchpad.net/~lazr-developers or send a message to: lazr-developers@lists.launchpad.net Running the tests ================= The tests suite requires tox_ and nose_ and is compatible with both Python 2 and Python 3. To run the full test suite:: $ tox .. _nose: https://nose.readthedocs.org/en/latest/ .. _tox: https://testrun.org/tox/latest/ lazr.delegates-2.0.3/PKG-INFO0000664000175000017500000000204412547235462016011 0ustar barrybarry00000000000000Metadata-Version: 1.1 Name: lazr.delegates Version: 2.0.3 Summary: Easily write objects that delegate behavior Home-page: https://launchpad.net/lazr.delegates Author: LAZR Developers Author-email: lazr-developers@lists.launchpad.net License: LGPL v3 Download-URL: https://launchpad.net/lazr.delegates/+download Description: The ``lazr.delegates`` package makes it easy to write objects that delegate behavior to another object. The new object adds some property or behavior on to the other object, while still providing the underlying interface, and delegating behavior. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 lazr.delegates-2.0.3/COPYING.txt0000664000175000017500000001672512547230200016561 0ustar barrybarry00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. lazr.delegates-2.0.3/README.rst0000664000175000017500000000043212547230200016363 0ustar barrybarry00000000000000========================= Welcome to lazr.delegates ========================= Contents: .. toctree:: :maxdepth: 2 lazr/delegates/docs/usage lazr/delegates/docs/NEWS HACKING Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`