lazy-object-proxy-1.3.1/0000775000175000017500000000000013103065765015364 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/AUTHORS.rst0000664000175000017500000000030513102433674017236 0ustar ionelionel00000000000000 Authors ======= * Ionel Cristian Mărieș - https://blog.ionelmc.ro * Alvin Chow - https://github.com/alvinchow86 * Astrum Kuo - https://github.com/xowenx * Erik M. Bray - https://iguananaut.net lazy-object-proxy-1.3.1/LICENSE0000664000175000017500000000243313102352620016357 0ustar ionelionel00000000000000Copyright (c) 2014-2017, Ionel Cristian Mărieș All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. lazy-object-proxy-1.3.1/tests/0000775000175000017500000000000013103065765016526 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/tests/test_lazy_object_proxy.py0000664000175000017500000013425613102352646023714 0ustar ionelionel00000000000000from __future__ import print_function import gc import imp import pickle import platform import sys import weakref from datetime import date from datetime import datetime from decimal import Decimal from functools import partial import pytest from compat import PY2 from compat import PY3 from compat import exec_ PYPY = '__pypy__' in sys.builtin_module_names OBJECTS_CODE = """ class TargetBaseClass(object): "documentation" class Target(TargetBaseClass): "documentation" def target(): "documentation" pass """ objects = imp.new_module('objects') exec_(OBJECTS_CODE, objects.__dict__, objects.__dict__) def load_implementation(name): class FakeModule: subclass = False kind = name if name == "slots": from lazy_object_proxy.slots import Proxy elif name == "simple": from lazy_object_proxy.simple import Proxy elif name == "cext": try: from lazy_object_proxy.cext import Proxy except ImportError: if PYPY: pytest.skip(msg="C Extension not available.") else: raise elif name == "objproxies": Proxy = pytest.importorskip("objproxies").LazyProxy elif name == "django": Proxy = pytest.importorskip("django.utils.functional").SimpleLazyObject else: raise RuntimeError("Unsupported param: %r." % name) Proxy return FakeModule @pytest.fixture(scope="module", params=[ "slots", "cext", "simple", # "external-django", "external-objproxies" ]) def lop_implementation(request): return load_implementation(request.param) @pytest.fixture(scope="module", params=[True, False], ids=['subclassed', 'normal']) def lop_subclass(request, lop_implementation): if request.param: class submod(lop_implementation): subclass = True Proxy = type("SubclassOf_" + lop_implementation.Proxy.__name__, (lop_implementation.Proxy,), {}) return submod else: return lop_implementation @pytest.fixture(scope="function") def lazy_object_proxy(request, lop_subclass): if request.node.get_marker('xfail_subclass'): request.applymarker(pytest.mark.xfail( reason="This test can't work because subclassing disables certain " "features like __doc__ and __module__ proxying." )) if request.node.get_marker('xfail_simple'): request.applymarker(pytest.mark.xfail( reason="The lazy_object_proxy.simple.Proxy has some limitations." )) return lop_subclass def test_round(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(lambda: 1.2) assert round(proxy) == 1 def test_attributes(lazy_object_proxy): def function1(*args, **kwargs): return args, kwargs function2 = lazy_object_proxy.Proxy(lambda: function1) assert function2.__wrapped__ == function1 def test_get_wrapped(lazy_object_proxy): def function1(*args, **kwargs): return args, kwargs function2 = lazy_object_proxy.Proxy(lambda: function1) assert function2.__wrapped__ == function1 function3 = lazy_object_proxy.Proxy(lambda: function2) assert function3.__wrapped__ == function1 def test_set_wrapped(lazy_object_proxy): def function1(*args, **kwargs): return args, kwargs function2 = lazy_object_proxy.Proxy(lambda: function1) assert function2 == function1 assert function2.__wrapped__ is function1 assert function2.__name__ == function1.__name__ if PY3: assert function2.__qualname__ == function1.__qualname__ function2.__wrapped__ = None assert not hasattr(function1, '__wrapped__') assert function2 == None assert function2.__wrapped__ is None assert not hasattr(function2, '__name__') if PY3: assert not hasattr(function2, '__qualname__') def function3(*args, **kwargs): return args, kwargs function2.__wrapped__ = function3 assert function2 == function3 assert function2.__wrapped__ == function3 assert function2.__name__ == function3.__name__ if PY3: assert function2.__qualname__ == function3.__qualname__ def test_wrapped_attribute(lazy_object_proxy): def function1(*args, **kwargs): return args, kwargs function2 = lazy_object_proxy.Proxy(lambda: function1) function2.variable = True assert hasattr(function1, 'variable') assert hasattr(function2, 'variable') assert function2.variable == True del function2.variable assert not hasattr(function1, 'variable') assert not hasattr(function2, 'variable') assert getattr(function2, 'variable', None) == None def test_class_object_name(lazy_object_proxy): # Test preservation of class __name__ attribute. target = objects.Target wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__name__ == target.__name__ def test_class_object_qualname(lazy_object_proxy): # Test preservation of class __qualname__ attribute. target = objects.Target wrapper = lazy_object_proxy.Proxy(lambda: target) try: __qualname__ = target.__qualname__ except AttributeError: pass else: assert wrapper.__qualname__ == __qualname__ @pytest.mark.xfail_subclass def test_class_module_name(lazy_object_proxy): # Test preservation of class __module__ attribute. target = objects.Target wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__module__ == target.__module__ @pytest.mark.xfail_subclass def test_class_doc_string(lazy_object_proxy): # Test preservation of class __doc__ attribute. target = objects.Target wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__doc__ == target.__doc__ @pytest.mark.xfail_subclass def test_instance_module_name(lazy_object_proxy): # Test preservation of instance __module__ attribute. target = objects.Target() wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__module__ == target.__module__ @pytest.mark.xfail_subclass def test_instance_doc_string(lazy_object_proxy): # Test preservation of instance __doc__ attribute. target = objects.Target() wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__doc__ == target.__doc__ def test_function_object_name(lazy_object_proxy): # Test preservation of function __name__ attribute. target = objects.target wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__name__ == target.__name__ def test_function_object_qualname(lazy_object_proxy): # Test preservation of function __qualname__ attribute. target = objects.target wrapper = lazy_object_proxy.Proxy(lambda: target) try: __qualname__ = target.__qualname__ except AttributeError: pass else: assert wrapper.__qualname__ == __qualname__ @pytest.mark.xfail_subclass def test_function_module_name(lazy_object_proxy): # Test preservation of function __module__ attribute. target = objects.target wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__module__ == target.__module__ @pytest.mark.xfail_subclass def test_function_doc_string(lazy_object_proxy): # Test preservation of function __doc__ attribute. target = objects.target wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__doc__ == target.__doc__ def test_class_of_class(lazy_object_proxy): # Test preservation of class __class__ attribute. target = objects.Target wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__class__ is target.__class__ assert isinstance(wrapper, type(target)) def test_revert_class_proxying(lazy_object_proxy): class ProxyWithOldStyleIsInstance(lazy_object_proxy.Proxy): __class__ = object.__dict__['__class__'] target = objects.Target() wrapper = ProxyWithOldStyleIsInstance(lambda: target) assert wrapper.__class__ is ProxyWithOldStyleIsInstance assert isinstance(wrapper, ProxyWithOldStyleIsInstance) assert not isinstance(wrapper, objects.Target) assert not isinstance(wrapper, objects.TargetBaseClass) class ProxyWithOldStyleIsInstance2(ProxyWithOldStyleIsInstance): pass wrapper = ProxyWithOldStyleIsInstance2(lambda: target) assert wrapper.__class__ is ProxyWithOldStyleIsInstance2 assert isinstance(wrapper, ProxyWithOldStyleIsInstance2) assert not isinstance(wrapper, objects.Target) assert not isinstance(wrapper, objects.TargetBaseClass) def test_class_of_instance(lazy_object_proxy): # Test preservation of instance __class__ attribute. target = objects.Target() wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__class__ is target.__class__ assert isinstance(wrapper, objects.Target) assert isinstance(wrapper, objects.TargetBaseClass) def test_class_of_function(lazy_object_proxy): # Test preservation of function __class__ attribute. target = objects.target wrapper = lazy_object_proxy.Proxy(lambda: target) assert wrapper.__class__ is target.__class__ assert isinstance(wrapper, type(target)) def test_dir_of_class(lazy_object_proxy): # Test preservation of class __dir__ attribute. target = objects.Target wrapper = lazy_object_proxy.Proxy(lambda: target) assert dir(wrapper) == dir(target) @pytest.mark.xfail_simple def test_vars_of_class(lazy_object_proxy): # Test preservation of class __dir__ attribute. target = objects.Target wrapper = lazy_object_proxy.Proxy(lambda: target) assert vars(wrapper) == vars(target) def test_dir_of_instance(lazy_object_proxy): # Test preservation of instance __dir__ attribute. target = objects.Target() wrapper = lazy_object_proxy.Proxy(lambda: target) assert dir(wrapper) == dir(target) @pytest.mark.xfail_simple def test_vars_of_instance(lazy_object_proxy): # Test preservation of instance __dir__ attribute. target = objects.Target() wrapper = lazy_object_proxy.Proxy(lambda: target) assert vars(wrapper) == vars(target) def test_dir_of_function(lazy_object_proxy): # Test preservation of function __dir__ attribute. target = objects.target wrapper = lazy_object_proxy.Proxy(lambda: target) assert dir(wrapper) == dir(target) @pytest.mark.xfail_simple def test_vars_of_function(lazy_object_proxy): # Test preservation of function __dir__ attribute. target = objects.target wrapper = lazy_object_proxy.Proxy(lambda: target) assert vars(wrapper) == vars(target) def test_function_no_args(lazy_object_proxy): _args = () _kwargs = {} def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: function) result = wrapper() assert result == (_args, _kwargs) def test_function_args(lazy_object_proxy): _args = (1, 2) _kwargs = {} def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: function) result = wrapper(*_args) assert result == (_args, _kwargs) def test_function_kwargs(lazy_object_proxy): _args = () _kwargs = {"one": 1, "two": 2} def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: function) result = wrapper(**_kwargs) assert result == (_args, _kwargs) def test_function_args_plus_kwargs(lazy_object_proxy): _args = (1, 2) _kwargs = {"one": 1, "two": 2} def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: function) result = wrapper(*_args, **_kwargs) assert result == (_args, _kwargs) def test_instancemethod_no_args(lazy_object_proxy): _args = () _kwargs = {} class Class(object): def function(self, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper() assert result == (_args, _kwargs) def test_instancemethod_args(lazy_object_proxy): _args = (1, 2) _kwargs = {} class Class(object): def function(self, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(*_args) assert result == (_args, _kwargs) def test_instancemethod_kwargs(lazy_object_proxy): _args = () _kwargs = {"one": 1, "two": 2} class Class(object): def function(self, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(**_kwargs) assert result == (_args, _kwargs) def test_instancemethod_args_plus_kwargs(lazy_object_proxy): _args = (1, 2) _kwargs = {"one": 1, "two": 2} class Class(object): def function(self, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(*_args, **_kwargs) assert result == (_args, _kwargs) def test_instancemethod_via_class_no_args(lazy_object_proxy): _args = () _kwargs = {} class Class(object): def function(self, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(Class()) assert result == (_args, _kwargs) def test_instancemethod_via_class_args(lazy_object_proxy): _args = (1, 2) _kwargs = {} class Class(object): def function(self, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(Class(), *_args) assert result == (_args, _kwargs) def test_instancemethod_via_class_kwargs(lazy_object_proxy): _args = () _kwargs = {"one": 1, "two": 2} class Class(object): def function(self, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(Class(), **_kwargs) assert result == (_args, _kwargs) def test_instancemethod_via_class_args_plus_kwargs(lazy_object_proxy): _args = (1, 2) _kwargs = {"one": 1, "two": 2} class Class(object): def function(self, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(Class(), *_args, **_kwargs) assert result == (_args, _kwargs) def test_classmethod_no_args(lazy_object_proxy): _args = () _kwargs = {} class Class(object): @classmethod def function(cls, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper() assert result == (_args, _kwargs) def test_classmethod_args(lazy_object_proxy): _args = (1, 2) _kwargs = {} class Class(object): @classmethod def function(cls, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(*_args) assert result == (_args, _kwargs) def test_classmethod_kwargs(lazy_object_proxy): _args = () _kwargs = {"one": 1, "two": 2} class Class(object): @classmethod def function(cls, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(**_kwargs) assert result == (_args, _kwargs) def test_classmethod_args_plus_kwargs(lazy_object_proxy): _args = (1, 2) _kwargs = {"one": 1, "two": 2} class Class(object): @classmethod def function(cls, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(*_args, **_kwargs) assert result == (_args, _kwargs) def test_classmethod_via_class_no_args(lazy_object_proxy): _args = () _kwargs = {} class Class(object): @classmethod def function(cls, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper() assert result == (_args, _kwargs) def test_classmethod_via_class_args(lazy_object_proxy): _args = (1, 2) _kwargs = {} class Class(object): @classmethod def function(cls, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(*_args) assert result == (_args, _kwargs) def test_classmethod_via_class_kwargs(lazy_object_proxy): _args = () _kwargs = {"one": 1, "two": 2} class Class(object): @classmethod def function(cls, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(**_kwargs) assert result == (_args, _kwargs) def test_classmethod_via_class_args_plus_kwargs(lazy_object_proxy): _args = (1, 2) _kwargs = {"one": 1, "two": 2} class Class(object): @classmethod def function(cls, *args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(*_args, **_kwargs) assert result == (_args, _kwargs) def test_staticmethod_no_args(lazy_object_proxy): _args = () _kwargs = {} class Class(object): @staticmethod def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper() assert result == (_args, _kwargs) def test_staticmethod_args(lazy_object_proxy): _args = (1, 2) _kwargs = {} class Class(object): @staticmethod def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(*_args) assert result == (_args, _kwargs) def test_staticmethod_kwargs(lazy_object_proxy): _args = () _kwargs = {"one": 1, "two": 2} class Class(object): @staticmethod def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(**_kwargs) assert result == (_args, _kwargs) def test_staticmethod_args_plus_kwargs(lazy_object_proxy): _args = (1, 2) _kwargs = {"one": 1, "two": 2} class Class(object): @staticmethod def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class().function) result = wrapper(*_args, **_kwargs) assert result == (_args, _kwargs) def test_staticmethod_via_class_no_args(lazy_object_proxy): _args = () _kwargs = {} class Class(object): @staticmethod def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper() assert result == (_args, _kwargs) def test_staticmethod_via_class_args(lazy_object_proxy): _args = (1, 2) _kwargs = {} class Class(object): @staticmethod def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(*_args) assert result == (_args, _kwargs) def test_staticmethod_via_class_kwargs(lazy_object_proxy): _args = () _kwargs = {"one": 1, "two": 2} class Class(object): @staticmethod def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(**_kwargs) assert result == (_args, _kwargs) def test_staticmethod_via_class_args_plus_kwargs(lazy_object_proxy): _args = (1, 2) _kwargs = {"one": 1, "two": 2} class Class(object): @staticmethod def function(*args, **kwargs): return args, kwargs wrapper = lazy_object_proxy.Proxy(lambda: Class.function) result = wrapper(*_args, **_kwargs) assert result == (_args, _kwargs) def test_iteration(lazy_object_proxy): items = [1, 2] wrapper = lazy_object_proxy.Proxy(lambda: items) result = [x for x in wrapper] assert result == items with pytest.raises(TypeError): for _ in lazy_object_proxy.Proxy(lambda: 1): pass def test_iter_builtin(lazy_object_proxy): iter(lazy_object_proxy.Proxy(lambda: [1, 2])) pytest.raises(TypeError, iter, lazy_object_proxy.Proxy(lambda: 1)) def test_context_manager(lazy_object_proxy): class Class(object): def __enter__(self): return self def __exit__(*args, **kwargs): return instance = Class() wrapper = lazy_object_proxy.Proxy(lambda: instance) with wrapper: pass def test_object_hash(lazy_object_proxy): def function1(*args, **kwargs): return args, kwargs function2 = lazy_object_proxy.Proxy(lambda: function1) assert hash(function2) == hash(function1) def test_mapping_key(lazy_object_proxy): def function1(*args, **kwargs): return args, kwargs function2 = lazy_object_proxy.Proxy(lambda: function1) table = dict() table[function1] = True assert table.get(function2) table = dict() table[function2] = True assert table.get(function1) def test_comparison(lazy_object_proxy): one = lazy_object_proxy.Proxy(lambda: 1) two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert two > 1 assert two >= 1 assert two < 3 assert two <= 3 assert two != 1 assert two == 2 assert two != 3 assert 2 > one assert 2 >= one assert 2 < three assert 2 <= three assert 2 != one assert 2 == two assert 2 != three assert two > one assert two >= one assert two < three assert two <= three assert two != one assert two == two assert two != three def test_nonzero(lazy_object_proxy): true = lazy_object_proxy.Proxy(lambda: True) false = lazy_object_proxy.Proxy(lambda: False) assert true assert not false assert bool(true) assert not bool(false) assert not false assert not not true def test_int(lazy_object_proxy): one = lazy_object_proxy.Proxy(lambda: 1) assert int(one) == 1 if not PY3: assert long(one) == 1 def test_float(lazy_object_proxy): one = lazy_object_proxy.Proxy(lambda: 1) assert float(one) == 1.0 def test_add(lazy_object_proxy): one = lazy_object_proxy.Proxy(lambda: 1) two = lazy_object_proxy.Proxy(lambda: 2) assert one + two == 1 + 2 assert 1 + two == 1 + 2 assert one + 2 == 1 + 2 def test_sub(lazy_object_proxy): one = lazy_object_proxy.Proxy(lambda: 1) two = lazy_object_proxy.Proxy(lambda: 2) assert one - two == 1 - 2 assert 1 - two == 1 - 2 assert one - 2 == 1 - 2 def test_mul(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert two * three == 2 * 3 assert 2 * three == 2 * 3 assert two * 3 == 2 * 3 def test_div(lazy_object_proxy): # On Python 2 this will pick up div and on Python # 3 it will pick up truediv. two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert two / three == 2 / 3 assert 2 / three == 2 / 3 assert two / 3 == 2 / 3 def test_mod(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert three // two == 3 // 2 assert 3 // two == 3 // 2 assert three // 2 == 3 // 2 def test_mod(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert three % two == 3 % 2 assert 3 % two == 3 % 2 assert three % 2 == 3 % 2 def test_divmod(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert divmod(three, two), divmod(3 == 2) assert divmod(3, two), divmod(3 == 2) assert divmod(three, 2), divmod(3 == 2) def test_pow(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert three ** two == pow(3, 2) assert 3 ** two == pow(3, 2) assert three ** 2 == pow(3, 2) assert pow(three, two) == pow(3, 2) assert pow(3, two) == pow(3, 2) assert pow(three, 2) == pow(3, 2) # Only PyPy implements __rpow__ for ternary pow(). if PYPY: assert pow(three, two, 2) == pow(3, 2, 2) assert pow(3, two, 2) == pow(3, 2, 2) assert pow(three, 2, 2) == pow(3, 2, 2) def test_lshift(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert three << two == 3 << 2 assert 3 << two == 3 << 2 assert three << 2 == 3 << 2 def test_rshift(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert three >> two == 3 >> 2 assert 3 >> two == 3 >> 2 assert three >> 2 == 3 >> 2 def test_and(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert three & two == 3 & 2 assert 3 & two == 3 & 2 assert three & 2 == 3 & 2 def test_xor(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert three ^ two == 3 ^ 2 assert 3 ^ two == 3 ^ 2 assert three ^ 2 == 3 ^ 2 def test_or(lazy_object_proxy): two = lazy_object_proxy.Proxy(lambda: 2) three = lazy_object_proxy.Proxy(lambda: 3) assert three | two == 3 | 2 assert 3 | two == 3 | 2 assert three | 2 == 3 | 2 def test_iadd(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 1) one = lazy_object_proxy.Proxy(lambda: 1) value += 1 assert value == 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value += one assert value == 3 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_isub(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 1) one = lazy_object_proxy.Proxy(lambda: 1) value -= 1 assert value == 0 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value -= one assert value == -1 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_imul(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 2) two = lazy_object_proxy.Proxy(lambda: 2) value *= 2 assert value == 4 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value *= two assert value == 8 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_idiv(lazy_object_proxy): # On Python 2 this will pick up div and on Python # 3 it will pick up truediv. value = lazy_object_proxy.Proxy(lambda: 2) two = lazy_object_proxy.Proxy(lambda: 2) value /= 2 assert value == 2 / 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value /= two assert value == 2 / 2 / 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_ifloordiv(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 2) two = lazy_object_proxy.Proxy(lambda: 2) value //= 2 assert value == 2 // 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value //= two assert value == 2 // 2 // 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_imod(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 10) two = lazy_object_proxy.Proxy(lambda: 2) value %= 2 assert value == 10 % 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value %= two assert value == 10 % 2 % 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_ipow(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 10) two = lazy_object_proxy.Proxy(lambda: 2) value **= 2 assert value == 10 ** 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value **= two assert value == 10 ** 2 ** 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_ilshift(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 256) two = lazy_object_proxy.Proxy(lambda: 2) value <<= 2 assert value == 256 << 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value <<= two assert value == 256 << 2 << 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_irshift(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 2) two = lazy_object_proxy.Proxy(lambda: 2) value >>= 2 assert value == 2 >> 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value >>= two assert value == 2 >> 2 >> 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_iand(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 1) two = lazy_object_proxy.Proxy(lambda: 2) value &= 2 assert value == 1 & 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value &= two assert value == 1 & 2 & 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_ixor(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 1) two = lazy_object_proxy.Proxy(lambda: 2) value ^= 2 assert value == 1 ^ 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value ^= two assert value == 1 ^ 2 ^ 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_ior(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 1) two = lazy_object_proxy.Proxy(lambda: 2) value |= 2 assert value == 1 | 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy value |= two assert value == 1 | 2 | 2 if lazy_object_proxy.kind != 'simple': assert type(value) == lazy_object_proxy.Proxy def test_neg(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 1) assert -value == -1 def test_pos(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 1) assert +value == 1 def test_abs(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: -1) assert abs(value) == 1 def test_invert(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 1) assert ~value == ~1 def test_oct(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 20) assert oct(value) == oct(20) def test_hex(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 20) assert hex(value) == hex(20) def test_index(lazy_object_proxy): class Class(object): def __index__(self): return 1 value = lazy_object_proxy.Proxy(lambda: Class()) items = [0, 1, 2] assert items[value] == items[1] def test_length(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: list(range(3))) assert len(value) == 3 def test_contains(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: list(range(3))) assert 2 in value assert not -2 in value def test_getitem(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: list(range(3))) assert value[1] == 1 def test_setitem(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: list(range(3))) value[1] = -1 assert value[1] == -1 def test_delitem(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: list(range(3))) assert len(value) == 3 del value[1] assert len(value) == 2 assert value[1] == 2 def test_getslice(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: list(range(5))) assert value[1:4] == [1, 2, 3] def test_setslice(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: list(range(5))) value[1:4] = reversed(value[1:4]) assert value[1:4] == [3, 2, 1] def test_delslice(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: list(range(5))) del value[1:4] assert len(value) == 2 assert value == [0, 4] def test_length(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: dict.fromkeys(range(3), False)) assert len(value) == 3 def test_contains(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: dict.fromkeys(range(3), False)) assert 2 in value assert -2 not in value def test_getitem(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: dict.fromkeys(range(3), False)) assert value[1] == False def test_setitem(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: dict.fromkeys(range(3), False)) value[1] = True assert value[1] == True def test_delitem(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: dict.fromkeys(range(3), False)) assert len(value) == 3 del value[1] assert len(value) == 2 def test_str(lazy_object_proxy): value = lazy_object_proxy.Proxy(lambda: 10) assert str(value) == str(10) value = lazy_object_proxy.Proxy(lambda: (10,)) assert str(value) == str((10,)) value = lazy_object_proxy.Proxy(lambda: [10]) assert str(value) == str([10]) value = lazy_object_proxy.Proxy(lambda: {10: 10}) assert str(value) == str({10: 10}) def test_repr(lazy_object_proxy): class Foobar: pass value = lazy_object_proxy.Proxy(lambda: Foobar()) str(value) representation = repr(value) print(representation) assert 'Proxy at' in representation assert 'lambda' in representation assert 'Foobar' in representation def test_repr_doesnt_consume(lazy_object_proxy): consumed = [] value = lazy_object_proxy.Proxy(lambda: consumed.append(1)) print(repr(value)) assert not consumed def test_derived_new(lazy_object_proxy): class DerivedObjectProxy(lazy_object_proxy.Proxy): def __new__(cls, wrapped): instance = super(DerivedObjectProxy, cls).__new__(cls) instance.__init__(wrapped) def __init__(self, wrapped): super(DerivedObjectProxy, self).__init__(wrapped) def function(): pass obj = DerivedObjectProxy(lambda: function) def test_setup_class_attributes(lazy_object_proxy): def function(): pass class DerivedObjectProxy(lazy_object_proxy.Proxy): pass obj = DerivedObjectProxy(lambda: function) DerivedObjectProxy.ATTRIBUTE = 1 assert obj.ATTRIBUTE == 1 assert not hasattr(function, 'ATTRIBUTE') del DerivedObjectProxy.ATTRIBUTE assert not hasattr(DerivedObjectProxy, 'ATTRIBUTE') assert not hasattr(obj, 'ATTRIBUTE') assert not hasattr(function, 'ATTRIBUTE') def test_override_class_attributes(lazy_object_proxy): def function(): pass class DerivedObjectProxy(lazy_object_proxy.Proxy): ATTRIBUTE = 1 obj = DerivedObjectProxy(lambda: function) assert DerivedObjectProxy.ATTRIBUTE == 1 assert obj.ATTRIBUTE == 1 obj.ATTRIBUTE = 2 assert DerivedObjectProxy.ATTRIBUTE == 1 assert obj.ATTRIBUTE == 2 assert not hasattr(function, 'ATTRIBUTE') del DerivedObjectProxy.ATTRIBUTE assert not hasattr(DerivedObjectProxy, 'ATTRIBUTE') assert obj.ATTRIBUTE == 2 assert not hasattr(function, 'ATTRIBUTE') def test_attr_functions(lazy_object_proxy): def function(): pass proxy = lazy_object_proxy.Proxy(lambda: function) assert hasattr(proxy, '__getattr__') assert hasattr(proxy, '__setattr__') assert hasattr(proxy, '__delattr__') def test_override_getattr(lazy_object_proxy): def function(): pass accessed = [] class DerivedObjectProxy(lazy_object_proxy.Proxy): def __getattr__(self, name): accessed.append(name) try: __getattr__ = super(DerivedObjectProxy, self).__getattr__ except AttributeError as e: raise RuntimeError(str(e)) return __getattr__(name) function.attribute = 1 proxy = DerivedObjectProxy(lambda: function) assert proxy.attribute == 1 assert 'attribute' in accessed skipcallable = pytest.mark.xfail( reason="Don't know how to make this work. This tests the existance of the __call__ method.") @skipcallable def test_proxy_hasattr_call(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(lambda: None) assert not hasattr(proxy, '__call__') @skipcallable def test_proxy_getattr_call(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(lambda: None) assert getattr(proxy, '__call__', None) == None @skipcallable def test_proxy_is_callable(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(lambda: None) assert not callable(proxy) def test_callable_proxy_hasattr_call(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(lambda: None) assert hasattr(proxy, '__call__') @skipcallable def test_callable_proxy_getattr_call(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(lambda: None) assert getattr(proxy, '__call__', None) is None def test_callable_proxy_is_callable(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(lambda: None) assert callable(proxy) def test_class_bytes(lazy_object_proxy): if PY3: class Class(object): def __bytes__(self): return b'BYTES' instance = Class() proxy = lazy_object_proxy.Proxy(lambda: instance) assert bytes(instance) == bytes(proxy) def test_str_format(lazy_object_proxy): instance = 'abcd' proxy = lazy_object_proxy.Proxy(lambda: instance) assert format(instance, ''), format(proxy == '') def test_list_reversed(lazy_object_proxy): instance = [1, 2] proxy = lazy_object_proxy.Proxy(lambda: instance) assert list(reversed(instance)) == list(reversed(proxy)) def test_decimal_complex(lazy_object_proxy): import decimal instance = decimal.Decimal(123) proxy = lazy_object_proxy.Proxy(lambda: instance) assert complex(instance) == complex(proxy) def test_fractions_round(lazy_object_proxy): import fractions instance = fractions.Fraction('1/2') proxy = lazy_object_proxy.Proxy(lambda: instance) assert round(instance) == round(proxy) def test_readonly(lazy_object_proxy): class Foo(object): if PY2: @property def __qualname__(self): return 'object' proxy = lazy_object_proxy.Proxy(lambda: Foo() if PY2 else object) assert proxy.__qualname__ == 'object' def test_del_wrapped(lazy_object_proxy): foo = object() called = [] def make_foo(): called.append(1) return foo proxy = lazy_object_proxy.Proxy(make_foo) str(proxy) assert called == [1] assert proxy.__wrapped__ is foo # print(type(proxy), hasattr(type(proxy), '__wrapped__')) del proxy.__wrapped__ str(proxy) assert called == [1, 1] def test_raise_attribute_error(lazy_object_proxy): def foo(): raise AttributeError("boom!") proxy = lazy_object_proxy.Proxy(foo) pytest.raises(AttributeError, str, proxy) pytest.raises(AttributeError, lambda: proxy.__wrapped__) assert proxy.__factory__ is foo def test_patching_the_factory(lazy_object_proxy): def foo(): raise AttributeError("boom!") proxy = lazy_object_proxy.Proxy(foo) pytest.raises(AttributeError, lambda: proxy.__wrapped__) assert proxy.__factory__ is foo proxy.__factory__ = lambda: foo pytest.raises(AttributeError, proxy) assert proxy.__wrapped__ is foo def test_deleting_the_factory(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(None) assert proxy.__factory__ is None proxy.__factory__ = None assert proxy.__factory__ is None pytest.raises(TypeError, str, proxy) del proxy.__factory__ pytest.raises(ValueError, str, proxy) def test_patching_the_factory_with_none(lazy_object_proxy): proxy = lazy_object_proxy.Proxy(None) assert proxy.__factory__ is None proxy.__factory__ = None assert proxy.__factory__ is None proxy.__factory__ = None assert proxy.__factory__ is None def foo(): return 1 proxy.__factory__ = foo assert proxy.__factory__ is foo assert proxy.__wrapped__ == 1 assert str(proxy) == '1' def test_new(lazy_object_proxy): a = lazy_object_proxy.Proxy.__new__(lazy_object_proxy.Proxy) b = lazy_object_proxy.Proxy.__new__(lazy_object_proxy.Proxy) # NOW KISS pytest.raises(ValueError, lambda: a + b) # no segfault, yay pytest.raises(ValueError, lambda: a.__wrapped__) def test_set_wrapped_via_new(lazy_object_proxy): obj = lazy_object_proxy.Proxy.__new__(lazy_object_proxy.Proxy) obj.__wrapped__ = 1 assert str(obj) == '1' assert obj + 1 == 2 def test_set_wrapped(lazy_object_proxy): obj = lazy_object_proxy.Proxy(None) obj.__wrapped__ = 1 assert str(obj) == '1' assert obj + 1 == 2 @pytest.fixture(params=["pickle", "cPickle"]) def pickler(request): return pytest.importorskip(request.param) @pytest.mark.parametrize("obj", [ 1, 1.2, "a", ["b", "c"], {"d": "e"}, date(2015, 5, 1), datetime(2015, 5, 1), Decimal("1.2") ]) @pytest.mark.parametrize("level", range(pickle.HIGHEST_PROTOCOL + 1)) def test_pickling(lazy_object_proxy, obj, pickler, level): proxy = lazy_object_proxy.Proxy(lambda: obj) dump = pickler.dumps(proxy, protocol=level) result = pickler.loads(dump) assert obj == result @pytest.mark.parametrize("level", range(pickle.HIGHEST_PROTOCOL + 1)) def test_pickling_exception(lazy_object_proxy, pickler, level): class BadStuff(Exception): pass def trouble_maker(): raise BadStuff("foo") proxy = lazy_object_proxy.Proxy(trouble_maker) pytest.raises(BadStuff, pickler.dumps, proxy, protocol=level) @pytest.mark.skipif(platform.python_implementation() != 'CPython', reason="Interpreter doesn't have reference counting") def test_garbage_collection(lazy_object_proxy): leaky = lambda: "foobar" proxy = lazy_object_proxy.Proxy(leaky) leaky.leak = proxy ref = weakref.ref(leaky) assert proxy == "foobar" del leaky del proxy gc.collect() assert ref() is None @pytest.mark.skipif(platform.python_implementation() != 'CPython', reason="Interpreter doesn't have reference counting") def test_garbage_collection_count(lazy_object_proxy): obj = object() count = sys.getrefcount(obj) for _ in range(100): str(lazy_object_proxy.Proxy(lambda: obj)) assert count == sys.getrefcount(obj) @pytest.mark.parametrize("name", ["slots", "cext", "simple", "django", "objproxies"]) def test_perf(benchmark, name): implementation = load_implementation(name) obj = "foobar" proxied = implementation.Proxy(lambda: obj) assert benchmark(partial(str, proxied)) == obj empty = object() @pytest.fixture(scope="module", params=["SimpleProxy", "LocalsSimpleProxy", "CachedPropertyProxy", "LocalsCachedPropertyProxy"]) def prototype(request): from lazy_object_proxy.simple import cached_property name = request.param if name == "SimpleProxy": class SimpleProxy(object): def __init__(self, factory): self.factory = factory self.object = empty def __str__(self): if self.object is empty: self.object = self.factory() return str(self.object) return SimpleProxy elif name == "CachedPropertyProxy": class CachedPropertyProxy(object): def __init__(self, factory): self.factory = factory @cached_property def object(self): return self.factory() def __str__(self): return str(self.object) return CachedPropertyProxy elif name == "LocalsSimpleProxy": class LocalsSimpleProxy(object): def __init__(self, factory): self.factory = factory self.object = empty def __str__(self, func=str): if self.object is empty: self.object = self.factory() return func(self.object) return LocalsSimpleProxy elif name == "LocalsCachedPropertyProxy": class LocalsCachedPropertyProxy(object): def __init__(self, factory): self.factory = factory @cached_property def object(self): return self.factory() def __str__(self, func=str): return func(self.object) return LocalsCachedPropertyProxy @pytest.mark.benchmark(group="prototypes") def test_proto(benchmark, prototype): obj = "foobar" proxied = prototype(lambda: obj) assert benchmark(partial(str, proxied)) == obj def test_subclassing_with_local_attr(lazy_object_proxy): class Foo: pass called = [] class LazyProxy(lazy_object_proxy.Proxy): name = None def __init__(self, func, **lazy_attr): super(LazyProxy, self).__init__(func) for attr, val in lazy_attr.items(): setattr(self, attr, val) proxy = LazyProxy(lambda: called.append(1) or Foo(), name='bar') assert proxy.name == 'bar' assert not called def test_subclassing_dynamic_with_local_attr(lazy_object_proxy): if lazy_object_proxy.kind == 'cext': pytest.skip("Not possible.") class Foo: pass called = [] class LazyProxy(lazy_object_proxy.Proxy): def __init__(self, func, **lazy_attr): super(LazyProxy, self).__init__(func) for attr, val in lazy_attr.items(): object.__setattr__(self, attr, val) proxy = LazyProxy(lambda: called.append(1) or Foo(), name='bar') assert proxy.name == 'bar' assert not called lazy-object-proxy-1.3.1/tests/compat.py0000664000175000017500000000117613102345227020361 0ustar ionelionel00000000000000import sys PY2 = sys.version_info[0] < 3 PY3 = sys.version_info[0] >= 3 if PY3: import builtins exec_ = getattr(builtins, "exec") del builtins else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """)lazy-object-proxy-1.3.1/setup.cfg0000664000175000017500000000177313103065765017215 0ustar ionelionel00000000000000[flake8] max-line-length = 140 exclude = tests/*,*/migrations/*,*/south_migrations/* [tool:pytest] norecursedirs = .git .tox .env dist build south_migrations migrations python_files = test_*.py *_test.py tests.py markers = xfail_subclass: Expected test to fail with a subclass of Proxy. xfail_simple: Expected test to fail on the `simple` implementation. addopts = -rxEfsw --strict --ignore=docs/conf.py --ignore=setup.py --ignore=ci --ignore=.eggs --doctest-modules --doctest-glob=\*.rst --tb=short [isort] force_single_line = True line_length = 120 known_first_party = lazy_object_proxy default_section = THIRDPARTY forced_separate = test_lazy_object_proxy not_skip = __init__.py skip = migrations, south_migrations [matrix] python_versions = 2.6 2.7 3.3 3.4 3.5 3.6 pypy pypy3 dependencies = :Django objproxies==0.9.4 !python_versions[2.6] : &python_versions[2.6] coverage_flags = cover: true nocov: false environment_variables = - [egg_info] tag_build = tag_date = 0 lazy-object-proxy-1.3.1/.editorconfig0000664000175000017500000000032713102352620020027 0ustar ionelionel00000000000000# see http://editorconfig.org root = true [*] end_of_line = lf trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 4 charset = utf-8 [*.{bat,cmd,ps1}] end_of_line = crlf lazy-object-proxy-1.3.1/MANIFEST.in0000664000175000017500000000053513102547350017117 0ustar ionelionel00000000000000graft docs graft src graft ci graft tests include .bumpversion.cfg include .coveragerc include .cookiecutterrc include .editorconfig include .isort.cfg include AUTHORS.rst include CHANGELOG.rst include CONTRIBUTING.rst include LICENSE include README.rst include tox.ini .travis.yml appveyor.yml global-exclude *.py[cod] __pycache__ *.so *.dylib lazy-object-proxy-1.3.1/setup.py0000664000175000017500000000741613103065740017077 0ustar ionelionel00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function import io import os import re from glob import glob from os.path import basename from os.path import dirname from os.path import join from os.path import relpath from os.path import splitext from setuptools import Extension from setuptools import find_packages from setuptools import setup from setuptools.command.build_ext import build_ext def read(*names, **kwargs): return io.open( join(dirname(__file__), *names), encoding=kwargs.get('encoding', 'utf8') ).read() # Enable code coverage for C code: we can't use CFLAGS=-coverage in tox.ini, since that may mess with compiling # dependencies (e.g. numpy). Therefore we set SETUPPY_CFLAGS=-coverage in tox.ini and copy it to CFLAGS here (after # deps have been safely installed). if 'TOXENV' in os.environ and 'SETUPPY_CFLAGS' in os.environ: os.environ['CFLAGS'] = os.environ['SETUPPY_CFLAGS'] class optional_build_ext(build_ext): """Allow the building of C extensions to fail.""" def run(self): try: build_ext.run(self) except Exception as e: self._unavailable(e) self.extensions = [] # avoid copying missing files (it would fail). def _unavailable(self, e): print('*' * 80) print('''WARNING: An optional code optimization (C extension) could not be compiled. Optimizations for this package will not be available! ''') print('CAUSE:') print('') print(' ' + repr(e)) print('*' * 80) setup( name='lazy-object-proxy', version='1.3.1', license='BSD', description='A fast and thorough lazy object proxy.', long_description='%s\n%s' % ( re.compile('^.. start-badges.*^.. end-badges', re.M | re.S).sub('', read('README.rst')), re.sub(':[a-z]+:`~?(.*?)`', r'``\1``', read('CHANGELOG.rst')) ), author='Ionel Cristian Mărieș', author_email='contact@ionelmc.ro', url='https://github.com/ionelmc/python-lazy-object-proxy', packages=find_packages('src'), package_dir={'': 'src'}, py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')], include_package_data=True, zip_safe=False, classifiers=[ # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Utilities', ], keywords=[ # eg: 'keyword1', 'keyword2', 'keyword3', ], install_requires=[ # eg: 'aspectlib==1.1.1', 'six>=1.7', ], extras_require={ # eg: # 'rst': ['docutils>=0.11'], # ':python_version=="2.6"': ['argparse'], }, cmdclass={'build_ext': optional_build_ext}, ext_modules=[ Extension( splitext(relpath(path, 'src').replace(os.sep, '.'))[0], sources=[path], include_dirs=[dirname(path)] ) for root, _, _ in os.walk('src') for path in glob(join(root, '*.c')) ], ) lazy-object-proxy-1.3.1/docs/0000775000175000017500000000000013103065765016314 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/docs/contributing.rst0000664000175000017500000000004113102352620021534 0ustar ionelionel00000000000000.. include:: ../CONTRIBUTING.rst lazy-object-proxy-1.3.1/docs/readme.rst0000664000175000017500000000003313102352620020263 0ustar ionelionel00000000000000.. include:: ../README.rst lazy-object-proxy-1.3.1/docs/changelog.rst0000664000175000017500000000003613102352620020760 0ustar ionelionel00000000000000.. include:: ../CHANGELOG.rst lazy-object-proxy-1.3.1/docs/conf.py0000664000175000017500000000265713103065740017616 0ustar ionelionel00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import os extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'sphinx.ext.extlinks', 'sphinx.ext.ifconfig', 'sphinx.ext.napoleon', 'sphinx.ext.todo', 'sphinx.ext.viewcode', ] if os.getenv('SPELLCHECK'): extensions += 'sphinxcontrib.spelling', spelling_show_suggestions = True spelling_lang = 'en_US' source_suffix = '.rst' master_doc = 'index' project = 'lazy-object-proxy' year = '2014-2017' author = 'Ionel Cristian Mărieș' copyright = '{0}, {1}'.format(year, author) version = release = '1.3.1' pygments_style = 'trac' templates_path = ['.'] extlinks = { 'issue': ('https://github.com/ionelmc/python-lazy-object-proxy/issues/%s', '#'), 'pr': ('https://github.com/ionelmc/python-lazy-object-proxy/pull/%s', 'PR #'), } import sphinx_py3doc_enhanced_theme html_theme = "sphinx_py3doc_enhanced_theme" html_theme_path = [sphinx_py3doc_enhanced_theme.get_html_theme_path()] html_theme_options = { 'githuburl': 'https://github.com/ionelmc/python-lazy-object-proxy/' } html_use_smartypants = True html_last_updated_fmt = '%b %d, %Y' html_split_index = False html_sidebars = { '**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'], } html_short_title = '%s-%s' % (project, version) napoleon_use_ivar = True napoleon_use_rtype = False napoleon_use_param = False lazy-object-proxy-1.3.1/docs/installation.rst0000664000175000017500000000014113102352620021527 0ustar ionelionel00000000000000============ Installation ============ At the command line:: pip install lazy-object-proxy lazy-object-proxy-1.3.1/docs/index.rst0000664000175000017500000000036513102352620020145 0ustar ionelionel00000000000000======== Contents ======== .. toctree:: :maxdepth: 2 readme installation usage reference/index contributing authors changelog Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` lazy-object-proxy-1.3.1/docs/usage.rst0000664000175000017500000000012613102352620020135 0ustar ionelionel00000000000000===== Usage ===== To use lazy-object-proxy in a project:: import lazy_object_proxy lazy-object-proxy-1.3.1/docs/reference/0000775000175000017500000000000013103065765020252 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/docs/reference/lazy_object_proxy.rst0000664000175000017500000000021213102352620024531 0ustar ionelionel00000000000000lazy_object_proxy ================= .. testsetup:: from lazy_object_proxy import * .. automodule:: lazy_object_proxy :members: lazy-object-proxy-1.3.1/docs/reference/index.rst0000664000175000017500000000010513102352620022073 0ustar ionelionel00000000000000Reference ========= .. toctree:: :glob: lazy_object_proxy* lazy-object-proxy-1.3.1/docs/spelling_wordlist.txt0000664000175000017500000000015513102352620022606 0ustar ionelionel00000000000000builtin builtins classmethod staticmethod classmethods staticmethods args kwargs callstack Changelog Indices lazy-object-proxy-1.3.1/docs/authors.rst0000664000175000017500000000003413102352620020514 0ustar ionelionel00000000000000.. include:: ../AUTHORS.rst lazy-object-proxy-1.3.1/docs/requirements.txt0000664000175000017500000000005613102352620021565 0ustar ionelionel00000000000000sphinx>=1.3 sphinx-py3doc-enhanced-theme -e . lazy-object-proxy-1.3.1/tox.ini0000664000175000017500000001375513102433674016707 0ustar ionelionel00000000000000[tox] envlist = clean, check, 2.6-cover, 2.6-nocov, 2.7-cover, 2.7-nocov, 3.3-cover, 3.3-nocov, 3.4-cover, 3.4-nocov, 3.5-cover, 3.5-nocov, 3.6-cover, 3.6-nocov, pypy-cover, pypy-nocov, pypy3-cover, pypy3-nocov, report, docs [testenv] basepython = {docs,spell}: {env:TOXPYTHON:python2.7} {bootstrap,clean,check,report,extension-coveralls,coveralls,codecov}: {env:TOXPYTHON:python3} setenv = PYTHONPATH={toxinidir}/tests PYTHONUNBUFFERED=yes passenv = * deps = setuptools>=6.0 pytest pytest-capturelog pytest-benchmark commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test -vv --ignore=src} [testenv:spell] setenv = SPELLCHECK=1 commands = sphinx-build -b spelling docs dist/docs skip_install = true usedevelop = false deps = -r{toxinidir}/docs/requirements.txt sphinxcontrib-spelling pyenchant [testenv:docs] deps = -r{toxinidir}/docs/requirements.txt commands = sphinx-build {posargs:-E} -b html docs dist/docs sphinx-build -b linkcheck docs dist/docs [testenv:bootstrap] deps = jinja2 matrix skip_install = true usedevelop = false commands = python ci/bootstrap.py passenv = * [testenv:check] deps = docutils check-manifest flake8 readme-renderer pygments isort skip_install = true usedevelop = false commands = python setup.py check --strict --metadata --restructuredtext check-manifest {toxinidir} flake8 src tests setup.py isort --verbose --check-only --diff --recursive src tests setup.py [testenv:coveralls] deps = coveralls skip_install = true usedevelop = false commands = coveralls --merge=extension-coveralls.json [] [testenv:codecov] deps = codecov skip_install = true usedevelop = false commands = coverage xml --ignore-errors codecov [] [testenv:extension-coveralls] deps = cpp-coveralls skip_install = true usedevelop = false commands = coveralls --build-root=. --include=src --dump=extension-coveralls.json [] [testenv:report] deps = coverage skip_install = true usedevelop = false commands = coverage combine --append coverage report coverage html [testenv:clean] commands = coverage erase skip_install = true usedevelop = false deps = coverage [testenv:2.6-cover] basepython = {env:TOXPYTHON:python2.6} setenv = {[testenv]setenv} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} deps = {[testenv]deps} pytest-cov [testenv:2.6-nocov] basepython = {env:TOXPYTHON:python2.6} [testenv:2.7-cover] basepython = {env:TOXPYTHON:python2.7} setenv = {[testenv]setenv} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} deps = {[testenv]deps} pytest-cov Django objproxies==0.9.4 [testenv:2.7-nocov] basepython = {env:TOXPYTHON:python2.7} deps = {[testenv]deps} Django objproxies==0.9.4 [testenv:3.3-cover] basepython = {env:TOXPYTHON:python3.3} setenv = {[testenv]setenv} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} deps = {[testenv]deps} pytest-cov Django objproxies==0.9.4 [testenv:3.3-nocov] basepython = {env:TOXPYTHON:python3.3} deps = {[testenv]deps} Django objproxies==0.9.4 [testenv:3.4-cover] basepython = {env:TOXPYTHON:python3.4} setenv = {[testenv]setenv} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} deps = {[testenv]deps} pytest-cov Django objproxies==0.9.4 [testenv:3.4-nocov] basepython = {env:TOXPYTHON:python3.4} deps = {[testenv]deps} Django objproxies==0.9.4 [testenv:3.5-cover] basepython = {env:TOXPYTHON:python3.5} setenv = {[testenv]setenv} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} deps = {[testenv]deps} pytest-cov Django objproxies==0.9.4 [testenv:3.5-nocov] basepython = {env:TOXPYTHON:python3.5} deps = {[testenv]deps} Django objproxies==0.9.4 [testenv:3.6-cover] basepython = {env:TOXPYTHON:python3.6} setenv = {[testenv]setenv} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} deps = {[testenv]deps} pytest-cov Django objproxies==0.9.4 [testenv:3.6-nocov] basepython = {env:TOXPYTHON:python3.6} deps = {[testenv]deps} Django objproxies==0.9.4 [testenv:pypy-cover] basepython = {env:TOXPYTHON:pypy} setenv = {[testenv]setenv} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} deps = {[testenv]deps} pytest-cov Django objproxies==0.9.4 [testenv:pypy-nocov] basepython = {env:TOXPYTHON:pypy} deps = {[testenv]deps} Django objproxies==0.9.4 [testenv:pypy3-cover] basepython = {env:TOXPYTHON:pypy3} setenv = {[testenv]setenv} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} deps = {[testenv]deps} pytest-cov Django objproxies==0.9.4 [testenv:pypy3-nocov] basepython = {env:TOXPYTHON:pypy3} deps = {[testenv]deps} Django objproxies==0.9.4 lazy-object-proxy-1.3.1/README.rst0000664000175000017500000001103513103065740017044 0ustar ionelionel00000000000000======== Overview ======== .. start-badges .. list-table:: :stub-columns: 1 * - docs - |docs| * - tests - | |travis| |appveyor| |requires| | |coveralls| |codecov| | |landscape| |scrutinizer| |codacy| |codeclimate| * - package - | |version| |wheel| |supported-versions| |supported-implementations| | |commits-since| .. |docs| image:: https://readthedocs.org/projects/python-lazy-object-proxy/badge/?style=flat :target: https://readthedocs.org/projects/python-lazy-object-proxy :alt: Documentation Status .. |travis| image:: https://travis-ci.org/ionelmc/python-lazy-object-proxy.svg?branch=master :alt: Travis-CI Build Status :target: https://travis-ci.org/ionelmc/python-lazy-object-proxy .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/github/ionelmc/python-lazy-object-proxy?branch=master&svg=true :alt: AppVeyor Build Status :target: https://ci.appveyor.com/project/ionelmc/python-lazy-object-proxy .. |requires| image:: https://requires.io/github/ionelmc/python-lazy-object-proxy/requirements.svg?branch=master :alt: Requirements Status :target: https://requires.io/github/ionelmc/python-lazy-object-proxy/requirements/?branch=master .. |coveralls| image:: https://coveralls.io/repos/ionelmc/python-lazy-object-proxy/badge.svg?branch=master&service=github :alt: Coverage Status :target: https://coveralls.io/r/ionelmc/python-lazy-object-proxy .. |codecov| image:: https://codecov.io/github/ionelmc/python-lazy-object-proxy/coverage.svg?branch=master :alt: Coverage Status :target: https://codecov.io/github/ionelmc/python-lazy-object-proxy .. |landscape| image:: https://landscape.io/github/ionelmc/python-lazy-object-proxy/master/landscape.svg?style=flat :target: https://landscape.io/github/ionelmc/python-lazy-object-proxy/master :alt: Code Quality Status .. |codacy| image:: https://img.shields.io/codacy/REPLACE_WITH_PROJECT_ID.svg :target: https://www.codacy.com/app/ionelmc/python-lazy-object-proxy :alt: Codacy Code Quality Status .. |codeclimate| image:: https://codeclimate.com/github/ionelmc/python-lazy-object-proxy/badges/gpa.svg :target: https://codeclimate.com/github/ionelmc/python-lazy-object-proxy :alt: CodeClimate Quality Status .. |version| image:: https://img.shields.io/pypi/v/lazy-object-proxy.svg :alt: PyPI Package latest release :target: https://pypi.python.org/pypi/lazy-object-proxy .. |commits-since| image:: https://img.shields.io/github/commits-since/ionelmc/python-lazy-object-proxy/v1.3.1.svg :alt: Commits since latest release :target: https://github.com/ionelmc/python-lazy-object-proxy/compare/v1.3.1...master .. |wheel| image:: https://img.shields.io/pypi/wheel/lazy-object-proxy.svg :alt: PyPI Wheel :target: https://pypi.python.org/pypi/lazy-object-proxy .. |supported-versions| image:: https://img.shields.io/pypi/pyversions/lazy-object-proxy.svg :alt: Supported versions :target: https://pypi.python.org/pypi/lazy-object-proxy .. |supported-implementations| image:: https://img.shields.io/pypi/implementation/lazy-object-proxy.svg :alt: Supported implementations :target: https://pypi.python.org/pypi/lazy-object-proxy .. |scrutinizer| image:: https://img.shields.io/scrutinizer/g/ionelmc/python-lazy-object-proxy/master.svg :alt: Scrutinizer Status :target: https://scrutinizer-ci.com/g/ionelmc/python-lazy-object-proxy/ .. end-badges A fast and thorough lazy object proxy. * Free software: BSD license Note that this is based on `wrapt`_'s ObjectProxy with one big change: it calls a function the first time the proxy object is used, while `wrapt.ObjectProxy` just forwards the method calls to the target object. In other words, you use `lazy-object-proxy` when you only have the object way later and you use `wrapt.ObjectProxy` when you want to override few methods (by subclassing) and forward everything else to the target object. Example:: def expensive_func(): # create expensive object return stuff obj = lazy_object_proxy.Proxy(expensive_func) # function is called only when object is actually used print(obj.foobar) # now expensive_func is called Installation ============ :: pip install lazy-object-proxy Documentation ============= https://python-lazy-object-proxy.readthedocs.io/ Development =========== To run the all tests run:: tox Acknowledgements ================ This project is based on some code from `wrapt`_ as you can see in the git history. .. _wrapt: https://github.com/GrahamDumpleton/wrapt lazy-object-proxy-1.3.1/CHANGELOG.rst0000664000175000017500000000234013103065713017375 0ustar ionelionel00000000000000 Changelog ========= 1.3.1 (2017-05-05) ------------------ * Fix broken release (``sdist`` had a broken ``MANIFEST.in``). 1.3.0 (2017-05-02) ------------------ * Speed up arithmetic operations involving ``cext.Proxy`` subclasses. 1.2.2 (2016-04-14) ------------------ * Added `manylinux `_ wheels. * Minor cleanup in readme. 1.2.1 (2015-08-18) ------------------ * Fix a memory leak (the wrapped object would get bogus references). Contributed by Astrum Kuo in `#10 `_. 1.2.0 (2015-07-06) ------------------ * Don't instantiate the object when __repr__ is called. This aids with debugging (allows one to see exactly in what state the proxy is). 1.1.0 (2015-07-05) ------------------ * Added support for pickling. The pickled value is going to be the wrapped object *without* any Proxy container. * Fixed a memory management issue in the C extension (reference cycles weren't garbage collected due to improper handling in the C extension). Contributed by Alvin Chow in `#8 `_. 1.0.2 (2015-04-11) ----------------------------------------- * First release on PyPI. lazy-object-proxy-1.3.1/PKG-INFO0000664000175000017500000001032713103065765016464 0ustar ionelionel00000000000000Metadata-Version: 1.1 Name: lazy-object-proxy Version: 1.3.1 Summary: A fast and thorough lazy object proxy. Home-page: https://github.com/ionelmc/python-lazy-object-proxy Author: Ionel Cristian Mărieș Author-email: contact@ionelmc.ro License: BSD Description: ======== Overview ======== A fast and thorough lazy object proxy. * Free software: BSD license Note that this is based on `wrapt`_'s ObjectProxy with one big change: it calls a function the first time the proxy object is used, while `wrapt.ObjectProxy` just forwards the method calls to the target object. In other words, you use `lazy-object-proxy` when you only have the object way later and you use `wrapt.ObjectProxy` when you want to override few methods (by subclassing) and forward everything else to the target object. Example:: def expensive_func(): # create expensive object return stuff obj = lazy_object_proxy.Proxy(expensive_func) # function is called only when object is actually used print(obj.foobar) # now expensive_func is called Installation ============ :: pip install lazy-object-proxy Documentation ============= https://python-lazy-object-proxy.readthedocs.io/ Development =========== To run the all tests run:: tox Acknowledgements ================ This project is based on some code from `wrapt`_ as you can see in the git history. .. _wrapt: https://github.com/GrahamDumpleton/wrapt Changelog ========= 1.3.1 (2017-05-05) ------------------ * Fix broken release (``sdist`` had a broken ``MANIFEST.in``). 1.3.0 (2017-05-02) ------------------ * Speed up arithmetic operations involving ``cext.Proxy`` subclasses. 1.2.2 (2016-04-14) ------------------ * Added `manylinux `_ wheels. * Minor cleanup in readme. 1.2.1 (2015-08-18) ------------------ * Fix a memory leak (the wrapped object would get bogus references). Contributed by Astrum Kuo in `#10 `_. 1.2.0 (2015-07-06) ------------------ * Don't instantiate the object when __repr__ is called. This aids with debugging (allows one to see exactly in what state the proxy is). 1.1.0 (2015-07-05) ------------------ * Added support for pickling. The pickled value is going to be the wrapped object *without* any Proxy container. * Fixed a memory management issue in the C extension (reference cycles weren't garbage collected due to improper handling in the C extension). Contributed by Alvin Chow in `#8 `_. 1.0.2 (2015-04-11) ----------------------------------------- * First release on PyPI. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: Unix Classifier: Operating System :: POSIX Classifier: Operating System :: Microsoft :: Windows Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Utilities lazy-object-proxy-1.3.1/CONTRIBUTING.rst0000664000175000017500000000541213102352620020013 0ustar ionelionel00000000000000============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. Bug reports =========== When `reporting a bug `_ please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Documentation improvements ========================== lazy-object-proxy could always use more documentation, whether as part of the official lazy-object-proxy docs, in docstrings, or even on the web in blog posts, articles, and such. Feature requests and feedback ============================= The best way to send feedback is to file an issue at https://github.com/ionelmc/python-lazy-object-proxy/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that code contributions are welcome :) Development =========== To set up `python-lazy-object-proxy` for local development: 1. Fork `python-lazy-object-proxy `_ (look for the "Fork" button). 2. Clone your fork locally:: git clone git@github.com:your_name_here/python-lazy-object-proxy.git 3. Create a branch for local development:: git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 4. When you're done making changes, run all the checks, doc builder and spell checker with `tox `_ one command:: tox 5. Commit your changes and push your branch to GitHub:: git add . git commit -m "Your detailed description of your changes." git push origin name-of-your-bugfix-or-feature 6. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- If you need some code review or feedback while you're developing the code just make the pull request. For merging, you should: 1. Include passing tests (run ``tox``) [1]_. 2. Update documentation when there's new API, functionality etc. 3. Add a note to ``CHANGELOG.rst`` about the changes. 4. Add yourself to ``AUTHORS.rst``. .. [1] If you don't have all the necessary python versions available locally you can rely on Travis - it will `run the tests `_ for each change you add in the pull request. It will be slower though ... Tips ---- To run a subset of tests:: tox -e envname -- py.test -k test_myfeature To run all the test environments in *parallel* (you need to ``pip install detox``):: detox lazy-object-proxy-1.3.1/.coveragerc0000664000175000017500000000022513102352620017470 0ustar ionelionel00000000000000[paths] source = src [run] branch = true source = src tests parallel = true [report] show_missing = true precision = 2 omit = *migrations* lazy-object-proxy-1.3.1/.travis.yml0000664000175000017500000000567213102352652017500 0ustar ionelionel00000000000000language: python sudo: false cache: pip env: global: - LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so - SEGFAULT_SIGNALS=all matrix: - TOXENV=check - TOXENV=docs matrix: include: - python: '2.6' env: - TOXENV=2.6-cover,report,extension-coveralls,coveralls,codecov - python: '2.6' env: - TOXENV=2.6-nocov - python: '2.7' env: - TOXENV=2.7-cover,report,extension-coveralls,coveralls,codecov - python: '2.7' env: - TOXENV=2.7-nocov - python: '3.3' env: - TOXENV=3.3-cover,report,extension-coveralls,coveralls,codecov - python: '3.3' env: - TOXENV=3.3-nocov - python: '3.4' env: - TOXENV=3.4-cover,report,extension-coveralls,coveralls,codecov - python: '3.4' env: - TOXENV=3.4-nocov - python: '3.5' env: - TOXENV=3.5-cover,report,extension-coveralls,coveralls,codecov - python: '3.5' env: - TOXENV=3.5-nocov - python: '3.6' env: - TOXENV=3.6-cover,report,extension-coveralls,coveralls,codecov - python: '3.6' env: - TOXENV=3.6-nocov - python: 'pypy' env: - TOXENV=pypy-cover,report,extension-coveralls,coveralls,codecov - python: 'pypy' env: - TOXENV=pypy-nocov - python: 'pypy3' env: - TOXENV=pypy3-cover,report,extension-coveralls,coveralls,codecov - python: 'pypy3' env: - TOXENV=pypy3-nocov before_install: - python --version - uname -a - lsb_release -a install: - pip install -U tox virtualenv - virtualenv --version - easy_install --version - pip --version - tox --version - | set -ex if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then (cd $HOME wget https://bitbucket.org/squeaky/portable-pypy/downloads/pypy-5.7.1-linux_x86_64-portable.tar.bz2 tar xf pypy-5.7.1-linux_x86_64-portable.tar.bz2 pypy-5.7.1-linux_x86_64-portable/bin/pypy -m ensurepip pypy-5.7.1-linux_x86_64-portable/bin/pypy -m pip install -U virtualenv) export PATH=$HOME/pypy-5.7.1-linux_x86_64-portable/bin/:$PATH export TOXPYTHON=$HOME/pypy-5.7.1-linux_x86_64-portable/bin/pypy fi if [[ $TRAVIS_PYTHON_VERSION == 'pypy3' ]]; then (cd $HOME wget https://bitbucket.org/squeaky/portable-pypy/downloads/pypy3.5-5.7.1-beta-linux_x86_64-portable.tar.bz2 tar xf pypy3.5-5.7.1-beta-linux_x86_64-portable.tar.bz2 pypy3.5-5.7.1-beta-linux_x86_64-portable/bin/pypy3 -m ensurepip pypy3.5-5.7.1-beta-linux_x86_64-portable/bin/pypy3 -m pip install -U virtualenv) export PATH=$HOME/pypy3.5-5.7.1-beta-linux_x86_64-portable/bin/:$PATH export TOXPYTHON=$HOME/pypy3.5-5.7.1-beta-linux_x86_64-portable/bin/pypy3 fi set +x script: - tox -v after_failure: - more .tox/log/* | cat - more .tox/*/log/* | cat notifications: email: on_success: never on_failure: always lazy-object-proxy-1.3.1/src/0000775000175000017500000000000013103065765016153 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/src/lazy_object_proxy.egg-info/0000775000175000017500000000000013103065765023413 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/src/lazy_object_proxy.egg-info/SOURCES.txt0000664000175000017500000000204613103065765025301 0ustar ionelionel00000000000000.bumpversion.cfg .cookiecutterrc .coveragerc .editorconfig .travis.yml AUTHORS.rst CHANGELOG.rst CONTRIBUTING.rst LICENSE MANIFEST.in README.rst appveyor.yml setup.cfg setup.py tox.ini ci/appveyor-bootstrap.py ci/appveyor-download.py ci/appveyor-with-compiler.cmd ci/bootstrap.py ci/templates/.travis.yml ci/templates/appveyor.yml ci/templates/tox.ini docs/authors.rst docs/changelog.rst docs/conf.py docs/contributing.rst docs/index.rst docs/installation.rst docs/readme.rst docs/requirements.txt docs/spelling_wordlist.txt docs/usage.rst docs/reference/index.rst docs/reference/lazy_object_proxy.rst src/lazy_object_proxy/__init__.py src/lazy_object_proxy/cext.c src/lazy_object_proxy/compat.py src/lazy_object_proxy/simple.py src/lazy_object_proxy/slots.py src/lazy_object_proxy/utils.py src/lazy_object_proxy.egg-info/PKG-INFO src/lazy_object_proxy.egg-info/SOURCES.txt src/lazy_object_proxy.egg-info/dependency_links.txt src/lazy_object_proxy.egg-info/not-zip-safe src/lazy_object_proxy.egg-info/top_level.txt tests/compat.py tests/test_lazy_object_proxy.pylazy-object-proxy-1.3.1/src/lazy_object_proxy.egg-info/not-zip-safe0000664000175000017500000000000113103065765025641 0ustar ionelionel00000000000000 lazy-object-proxy-1.3.1/src/lazy_object_proxy.egg-info/top_level.txt0000664000175000017500000000002213103065765026137 0ustar ionelionel00000000000000lazy_object_proxy lazy-object-proxy-1.3.1/src/lazy_object_proxy.egg-info/PKG-INFO0000664000175000017500000001032713103065765024513 0ustar ionelionel00000000000000Metadata-Version: 1.1 Name: lazy-object-proxy Version: 1.3.1 Summary: A fast and thorough lazy object proxy. Home-page: https://github.com/ionelmc/python-lazy-object-proxy Author: Ionel Cristian Mărieș Author-email: contact@ionelmc.ro License: BSD Description: ======== Overview ======== A fast and thorough lazy object proxy. * Free software: BSD license Note that this is based on `wrapt`_'s ObjectProxy with one big change: it calls a function the first time the proxy object is used, while `wrapt.ObjectProxy` just forwards the method calls to the target object. In other words, you use `lazy-object-proxy` when you only have the object way later and you use `wrapt.ObjectProxy` when you want to override few methods (by subclassing) and forward everything else to the target object. Example:: def expensive_func(): # create expensive object return stuff obj = lazy_object_proxy.Proxy(expensive_func) # function is called only when object is actually used print(obj.foobar) # now expensive_func is called Installation ============ :: pip install lazy-object-proxy Documentation ============= https://python-lazy-object-proxy.readthedocs.io/ Development =========== To run the all tests run:: tox Acknowledgements ================ This project is based on some code from `wrapt`_ as you can see in the git history. .. _wrapt: https://github.com/GrahamDumpleton/wrapt Changelog ========= 1.3.1 (2017-05-05) ------------------ * Fix broken release (``sdist`` had a broken ``MANIFEST.in``). 1.3.0 (2017-05-02) ------------------ * Speed up arithmetic operations involving ``cext.Proxy`` subclasses. 1.2.2 (2016-04-14) ------------------ * Added `manylinux `_ wheels. * Minor cleanup in readme. 1.2.1 (2015-08-18) ------------------ * Fix a memory leak (the wrapped object would get bogus references). Contributed by Astrum Kuo in `#10 `_. 1.2.0 (2015-07-06) ------------------ * Don't instantiate the object when __repr__ is called. This aids with debugging (allows one to see exactly in what state the proxy is). 1.1.0 (2015-07-05) ------------------ * Added support for pickling. The pickled value is going to be the wrapped object *without* any Proxy container. * Fixed a memory management issue in the C extension (reference cycles weren't garbage collected due to improper handling in the C extension). Contributed by Alvin Chow in `#8 `_. 1.0.2 (2015-04-11) ----------------------------------------- * First release on PyPI. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: Unix Classifier: Operating System :: POSIX Classifier: Operating System :: Microsoft :: Windows Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Utilities lazy-object-proxy-1.3.1/src/lazy_object_proxy.egg-info/dependency_links.txt0000664000175000017500000000000113103065765027461 0ustar ionelionel00000000000000 lazy-object-proxy-1.3.1/src/lazy_object_proxy/0000775000175000017500000000000013103065765021721 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/src/lazy_object_proxy/__init__.py0000664000175000017500000000051413103065740024023 0ustar ionelionel00000000000000try: import copy_reg as copyreg except ImportError: import copyreg from .utils import identity copyreg.constructor(identity) try: from .cext import Proxy from .cext import identity except ImportError: from .slots import Proxy else: copyreg.constructor(identity) __version__ = "1.3.1" __all__ = "Proxy", lazy-object-proxy-1.3.1/src/lazy_object_proxy/slots.py0000664000175000017500000002611313102345227023433 0ustar ionelionel00000000000000import operator from .compat import PY2 from .compat import PY3 from .compat import with_metaclass from .utils import identity class _ProxyMethods(object): # We use properties to override the values of __module__ and # __doc__. If we add these in ObjectProxy, the derived class # __dict__ will still be setup to have string variants of these # attributes and the rules of descriptors means that they appear to # take precedence over the properties in the base class. To avoid # that, we copy the properties into the derived class type itself # via a meta class. In that way the properties will always take # precedence. @property def __module__(self): return self.__wrapped__.__module__ @__module__.setter def __module__(self, value): self.__wrapped__.__module__ = value @property def __doc__(self): return self.__wrapped__.__doc__ @__doc__.setter def __doc__(self, value): self.__wrapped__.__doc__ = value # We similar use a property for __dict__. We need __dict__ to be # explicit to ensure that vars() works as expected. @property def __dict__(self): return self.__wrapped__.__dict__ # Need to also propagate the special __weakref__ attribute for case # where decorating classes which will define this. If do not define # it and use a function like inspect.getmembers() on a decorator # class it will fail. This can't be in the derived classes. @property def __weakref__(self): return self.__wrapped__.__weakref__ class _ProxyMetaType(type): def __new__(cls, name, bases, dictionary): # Copy our special properties into the class so that they # always take precedence over attributes of the same name added # during construction of a derived class. This is to save # duplicating the implementation for them in all derived classes. dictionary.update(vars(_ProxyMethods)) return type.__new__(cls, name, bases, dictionary) class Proxy(with_metaclass(_ProxyMetaType)): """ A proxy implementation in pure Python, using slots. You can subclass this to add local methods or attributes, or enable __dict__. The most important internals: * ``__factory__`` is the callback that "materializes" the object we proxy to. * ``__target__`` will contain the object we proxy to, once it's "materialized". * ``__wrapped__`` is a property that does either: * return ``__target__`` if it's set. * calls ``__factory__``, saves result to ``__target__`` and returns said result. """ __slots__ = '__target__', '__factory__' def __init__(self, factory): object.__setattr__(self, '__factory__', factory) @property def __wrapped__(self, __getattr__=object.__getattribute__, __setattr__=object.__setattr__, __delattr__=object.__delattr__): try: return __getattr__(self, '__target__') except AttributeError: try: factory = __getattr__(self, '__factory__') except AttributeError: raise ValueError("Proxy hasn't been initiated: __factory__ is missing.") target = factory() __setattr__(self, '__target__', target) return target @__wrapped__.deleter def __wrapped__(self, __delattr__=object.__delattr__): __delattr__(self, '__target__') @__wrapped__.setter def __wrapped__(self, target, __setattr__=object.__setattr__): __setattr__(self, '__target__', target) @property def __name__(self): return self.__wrapped__.__name__ @__name__.setter def __name__(self, value): self.__wrapped__.__name__ = value @property def __class__(self): return self.__wrapped__.__class__ @__class__.setter def __class__(self, value): self.__wrapped__.__class__ = value @property def __annotations__(self): return self.__wrapped__.__anotations__ @__annotations__.setter def __annotations__(self, value): self.__wrapped__.__annotations__ = value def __dir__(self): return dir(self.__wrapped__) def __str__(self): return str(self.__wrapped__) if PY3: def __bytes__(self): return bytes(self.__wrapped__) def __repr__(self, __getattr__=object.__getattribute__): try: target = __getattr__(self, '__target__') except AttributeError: return '<%s at 0x%x with factory %r>' % ( type(self).__name__, id(self), self.__factory__ ) else: return '<%s at 0x%x wrapping %r at 0x%x with factory %r>' % ( type(self).__name__, id(self), target, id(target), self.__factory__ ) def __reversed__(self): return reversed(self.__wrapped__) if PY3: def __round__(self): return round(self.__wrapped__) def __lt__(self, other): return self.__wrapped__ < other def __le__(self, other): return self.__wrapped__ <= other def __eq__(self, other): return self.__wrapped__ == other def __ne__(self, other): return self.__wrapped__ != other def __gt__(self, other): return self.__wrapped__ > other def __ge__(self, other): return self.__wrapped__ >= other def __hash__(self): return hash(self.__wrapped__) def __nonzero__(self): return bool(self.__wrapped__) def __bool__(self): return bool(self.__wrapped__) def __setattr__(self, name, value, __setattr__=object.__setattr__): if hasattr(type(self), name): __setattr__(self, name, value) else: setattr(self.__wrapped__, name, value) def __getattr__(self, name): if name in ('__wrapped__', '__factory__'): raise AttributeError(name) else: return getattr(self.__wrapped__, name) def __delattr__(self, name, __delattr__=object.__delattr__): if hasattr(type(self), name): __delattr__(self, name) else: delattr(self.__wrapped__, name) def __add__(self, other): return self.__wrapped__ + other def __sub__(self, other): return self.__wrapped__ - other def __mul__(self, other): return self.__wrapped__ * other def __div__(self, other): return operator.div(self.__wrapped__, other) def __truediv__(self, other): return operator.truediv(self.__wrapped__, other) def __floordiv__(self, other): return self.__wrapped__ // other def __mod__(self, other): return self.__wrapped__ ^ other def __divmod__(self, other): return divmod(self.__wrapped__, other) def __pow__(self, other, *args): return pow(self.__wrapped__, other, *args) def __lshift__(self, other): return self.__wrapped__ << other def __rshift__(self, other): return self.__wrapped__ >> other def __and__(self, other): return self.__wrapped__ & other def __xor__(self, other): return self.__wrapped__ ^ other def __or__(self, other): return self.__wrapped__ | other def __radd__(self, other): return other + self.__wrapped__ def __rsub__(self, other): return other - self.__wrapped__ def __rmul__(self, other): return other * self.__wrapped__ def __rdiv__(self, other): return operator.div(other, self.__wrapped__) def __rtruediv__(self, other): return operator.truediv(other, self.__wrapped__) def __rfloordiv__(self, other): return other // self.__wrapped__ def __rmod__(self, other): return other % self.__wrapped__ def __rdivmod__(self, other): return divmod(other, self.__wrapped__) def __rpow__(self, other, *args): return pow(other, self.__wrapped__, *args) def __rlshift__(self, other): return other << self.__wrapped__ def __rrshift__(self, other): return other >> self.__wrapped__ def __rand__(self, other): return other & self.__wrapped__ def __rxor__(self, other): return other ^ self.__wrapped__ def __ror__(self, other): return other | self.__wrapped__ def __iadd__(self, other): self.__wrapped__ += other return self def __isub__(self, other): self.__wrapped__ -= other return self def __imul__(self, other): self.__wrapped__ *= other return self def __idiv__(self, other): self.__wrapped__ = operator.idiv(self.__wrapped__, other) return self def __itruediv__(self, other): self.__wrapped__ = operator.itruediv(self.__wrapped__, other) return self def __ifloordiv__(self, other): self.__wrapped__ //= other return self def __imod__(self, other): self.__wrapped__ %= other return self def __ipow__(self, other): self.__wrapped__ **= other return self def __ilshift__(self, other): self.__wrapped__ <<= other return self def __irshift__(self, other): self.__wrapped__ >>= other return self def __iand__(self, other): self.__wrapped__ &= other return self def __ixor__(self, other): self.__wrapped__ ^= other return self def __ior__(self, other): self.__wrapped__ |= other return self def __neg__(self): return -self.__wrapped__ def __pos__(self): return +self.__wrapped__ def __abs__(self): return abs(self.__wrapped__) def __invert__(self): return ~self.__wrapped__ def __int__(self): return int(self.__wrapped__) if PY2: def __long__(self): return long(self.__wrapped__) # flake8: noqa def __float__(self): return float(self.__wrapped__) def __oct__(self): return oct(self.__wrapped__) def __hex__(self): return hex(self.__wrapped__) def __index__(self): return operator.index(self.__wrapped__) def __len__(self): return len(self.__wrapped__) def __contains__(self, value): return value in self.__wrapped__ def __getitem__(self, key): return self.__wrapped__[key] def __setitem__(self, key, value): self.__wrapped__[key] = value def __delitem__(self, key): del self.__wrapped__[key] def __getslice__(self, i, j): return self.__wrapped__[i:j] def __setslice__(self, i, j, value): self.__wrapped__[i:j] = value def __delslice__(self, i, j): del self.__wrapped__[i:j] def __enter__(self): return self.__wrapped__.__enter__() def __exit__(self, *args, **kwargs): return self.__wrapped__.__exit__(*args, **kwargs) def __iter__(self): return iter(self.__wrapped__) def __call__(self, *args, **kwargs): return self.__wrapped__(*args, **kwargs) def __reduce__(self): return identity, (self.__wrapped__,) def __reduce_ex__(self, protocol): return identity, (self.__wrapped__,) lazy-object-proxy-1.3.1/src/lazy_object_proxy/simple.py0000664000175000017500000002001413102345227023552 0ustar ionelionel00000000000000import operator from .compat import PY2 from .compat import PY3 from .compat import with_metaclass from .utils import cached_property from .utils import identity def make_proxy_method(code): def proxy_wrapper(self, *args): return code(self.__wrapped__, *args) return proxy_wrapper class _ProxyMethods(object): # We use properties to override the values of __module__ and # __doc__. If we add these in ObjectProxy, the derived class # __dict__ will still be setup to have string variants of these # attributes and the rules of descriptors means that they appear to # take precedence over the properties in the base class. To avoid # that, we copy the properties into the derived class type itself # via a meta class. In that way the properties will always take # precedence. @property def __module__(self): return self.__wrapped__.__module__ @__module__.setter def __module__(self, value): self.__wrapped__.__module__ = value @property def __doc__(self): return self.__wrapped__.__doc__ @__doc__.setter def __doc__(self, value): self.__wrapped__.__doc__ = value # Need to also propagate the special __weakref__ attribute for case # where decorating classes which will define this. If do not define # it and use a function like inspect.getmembers() on a decorator # class it will fail. This can't be in the derived classes. @property def __weakref__(self): return self.__wrapped__.__weakref__ class _ProxyMetaType(type): def __new__(cls, name, bases, dictionary): # Copy our special properties into the class so that they # always take precedence over attributes of the same name added # during construction of a derived class. This is to save # duplicating the implementation for them in all derived classes. dictionary.update(vars(_ProxyMethods)) dictionary.pop('__dict__') return type.__new__(cls, name, bases, dictionary) class Proxy(with_metaclass(_ProxyMetaType)): __factory__ = None def __init__(self, factory): self.__dict__['__factory__'] = factory @cached_property def __wrapped__(self): self = self.__dict__ if '__factory__' in self: factory = self['__factory__'] return factory() else: raise ValueError("Proxy hasn't been initiated: __factory__ is missing.") __name__ = property(make_proxy_method(operator.attrgetter('__name__'))) __class__ = property(make_proxy_method(operator.attrgetter('__class__'))) __annotations__ = property(make_proxy_method(operator.attrgetter('__anotations__'))) __dir__ = make_proxy_method(dir) __str__ = make_proxy_method(str) if PY3: __bytes__ = make_proxy_method(bytes) def __repr__(self, __getattr__=object.__getattribute__): if '__wrapped__' in self.__dict__: return '<%s at 0x%x wrapping %r at 0x%x with factory %r>' % ( type(self).__name__, id(self), self.__wrapped__, id(self.__wrapped__), self.__factory__ ) else: return '<%s at 0x%x with factory %r>' % ( type(self).__name__, id(self), self.__factory__ ) __reversed__ = make_proxy_method(reversed) if PY3: __round__ = make_proxy_method(round) __lt__ = make_proxy_method(operator.lt) __le__ = make_proxy_method(operator.le) __eq__ = make_proxy_method(operator.eq) __ne__ = make_proxy_method(operator.ne) __gt__ = make_proxy_method(operator.gt) __ge__ = make_proxy_method(operator.ge) __hash__ = make_proxy_method(hash) __nonzero__ = make_proxy_method(bool) __bool__ = make_proxy_method(bool) def __setattr__(self, name, value): if hasattr(type(self), name): self.__dict__[name] = value else: setattr(self.__wrapped__, name, value) def __getattr__(self, name): if name in ('__wrapped__', '__factory__'): raise AttributeError(name) else: return getattr(self.__wrapped__, name) def __delattr__(self, name): if hasattr(type(self), name): del self.__dict__[name] else: delattr(self.__wrapped__, name) __add__ = make_proxy_method(operator.add) __sub__ = make_proxy_method(operator.sub) __mul__ = make_proxy_method(operator.mul) __div__ = make_proxy_method(operator.div if PY2 else operator.truediv) __truediv__ = make_proxy_method(operator.truediv) __floordiv__ = make_proxy_method(operator.floordiv) __mod__ = make_proxy_method(operator.mod) __divmod__ = make_proxy_method(divmod) __pow__ = make_proxy_method(pow) __lshift__ = make_proxy_method(operator.lshift) __rshift__ = make_proxy_method(operator.rshift) __and__ = make_proxy_method(operator.and_) __xor__ = make_proxy_method(operator.xor) __or__ = make_proxy_method(operator.or_) def __radd__(self, other): return other + self.__wrapped__ def __rsub__(self, other): return other - self.__wrapped__ def __rmul__(self, other): return other * self.__wrapped__ def __rdiv__(self, other): return operator.div(other, self.__wrapped__) def __rtruediv__(self, other): return operator.truediv(other, self.__wrapped__) def __rfloordiv__(self, other): return other // self.__wrapped__ def __rmod__(self, other): return other % self.__wrapped__ def __rdivmod__(self, other): return divmod(other, self.__wrapped__) def __rpow__(self, other, *args): return pow(other, self.__wrapped__, *args) def __rlshift__(self, other): return other << self.__wrapped__ def __rrshift__(self, other): return other >> self.__wrapped__ def __rand__(self, other): return other & self.__wrapped__ def __rxor__(self, other): return other ^ self.__wrapped__ def __ror__(self, other): return other | self.__wrapped__ __iadd__ = make_proxy_method(operator.iadd) __isub__ = make_proxy_method(operator.isub) __imul__ = make_proxy_method(operator.imul) __idiv__ = make_proxy_method(operator.idiv if PY2 else operator.itruediv) __itruediv__ = make_proxy_method(operator.itruediv) __ifloordiv__ = make_proxy_method(operator.ifloordiv) __imod__ = make_proxy_method(operator.imod) __ipow__ = make_proxy_method(operator.ipow) __ilshift__ = make_proxy_method(operator.ilshift) __irshift__ = make_proxy_method(operator.irshift) __iand__ = make_proxy_method(operator.iand) __ixor__ = make_proxy_method(operator.ixor) __ior__ = make_proxy_method(operator.ior) __neg__ = make_proxy_method(operator.neg) __pos__ = make_proxy_method(operator.pos) __abs__ = make_proxy_method(operator.abs) __invert__ = make_proxy_method(operator.invert) __int__ = make_proxy_method(int) if PY2: __long__ = make_proxy_method(long) # flake8: noqa __float__ = make_proxy_method(float) __oct__ = make_proxy_method(oct) __hex__ = make_proxy_method(hex) __index__ = make_proxy_method(operator.index) __len__ = make_proxy_method(len) __contains__ = make_proxy_method(operator.contains) __getitem__ = make_proxy_method(operator.getitem) __setitem__ = make_proxy_method(operator.setitem) __delitem__ = make_proxy_method(operator.delitem) if PY2: __getslice__ = make_proxy_method(operator.getslice) __setslice__ = make_proxy_method(operator.setslice) __delslice__ = make_proxy_method(operator.delslice) def __enter__(self): return self.__wrapped__.__enter__() def __exit__(self, *args, **kwargs): return self.__wrapped__.__exit__(*args, **kwargs) __iter__ = make_proxy_method(iter) def __call__(self, *args, **kwargs): return self.__wrapped__(*args, **kwargs) def __reduce__(self): return identity, (self.__wrapped__,) def __reduce_ex__(self, protocol): return identity, (self.__wrapped__,) lazy-object-proxy-1.3.1/src/lazy_object_proxy/compat.py0000664000175000017500000000030413102345227023544 0ustar ionelionel00000000000000import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" return meta("NewBase", bases, {}) lazy-object-proxy-1.3.1/src/lazy_object_proxy/cext.c0000664000175000017500000011353113102345227023025 0ustar ionelionel00000000000000/* ------------------------------------------------------------------------- */ #include "Python.h" #include "structmember.h" #ifndef PyVarObject_HEAD_INIT #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size, #endif #define Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(object) \ if (PyObject_TypeCheck(object, &Proxy_Type)) { \ object = Proxy__ensure_wrapped((ProxyObject *)object); \ if (!object) return NULL; \ } #define Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self) if (!Proxy__ensure_wrapped(self)) return NULL; #define Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self) if (!Proxy__ensure_wrapped(self)) return -1; #if PY_MAJOR_VERSION < 3 #define Py_hash_t long #endif /* ------------------------------------------------------------------------- */ typedef struct { PyObject_HEAD PyObject *dict; PyObject *wrapped; PyObject *factory; } ProxyObject; PyTypeObject Proxy_Type; /* ------------------------------------------------------------------------- */ static PyObject *identity_ref = NULL; static PyObject * identity(PyObject *self, PyObject *value) { Py_INCREF(value); return value; } /* ------------------------------------------------------------------------- */ PyDoc_STRVAR(identity_doc, "Indentity function: returns the single argument."); static struct PyMethodDef module_functions[] = { {"identity", identity, METH_O, identity_doc}, {NULL, NULL} }; /* ------------------------------------------------------------------------- */ static PyObject *Proxy__ensure_wrapped(ProxyObject *self) { PyObject *wrapped; if (self->wrapped) { return self->wrapped; } else { if (self->factory) { wrapped = PyObject_CallFunctionObjArgs(self->factory, NULL); if (wrapped) { self->wrapped = wrapped; return wrapped; } else { return NULL; } } else { PyErr_SetString(PyExc_ValueError, "Proxy hasn't been initiated: __factory__ is missing."); return NULL; } } } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ProxyObject *self; self = (ProxyObject *)type->tp_alloc(type, 0); if (!self) return NULL; self->dict = PyDict_New(); self->wrapped = NULL; self->factory = NULL; return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static int Proxy_raw_init(ProxyObject *self, PyObject *factory) { Py_INCREF(factory); Py_XDECREF(self->wrapped); Py_XDECREF(self->factory); self->factory = factory; return 0; } /* ------------------------------------------------------------------------- */ static int Proxy_init(ProxyObject *self, PyObject *args, PyObject *kwds) { PyObject *wrapped = NULL; static char *kwlist[] = { "wrapped", NULL }; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:ObjectProxy", kwlist, &wrapped)) { return -1; } return Proxy_raw_init(self, wrapped); } /* ------------------------------------------------------------------------- */ static int Proxy_traverse(ProxyObject *self, visitproc visit, void *arg) { Py_VISIT(self->dict); Py_VISIT(self->wrapped); Py_VISIT(self->factory); return 0; } /* ------------------------------------------------------------------------- */ static int Proxy_clear(ProxyObject *self) { Py_CLEAR(self->dict); Py_CLEAR(self->wrapped); Py_CLEAR(self->factory); return 0; } /* ------------------------------------------------------------------------- */ static void Proxy_dealloc(ProxyObject *self) { PyObject_GC_UnTrack(self); Proxy_clear(self); Py_TYPE(self)->tp_free(self); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_repr(ProxyObject *self) { #if PY_MAJOR_VERSION < 3 PyObject *factory_repr; factory_repr = PyObject_Repr(self->factory); if (factory_repr == NULL) return NULL; #endif if (self->wrapped) { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat("<%s at %p wrapping %R at %p with factory %R>", Py_TYPE(self)->tp_name, self, self->wrapped, self->wrapped, self->factory); #else PyObject *wrapped_repr; wrapped_repr = PyObject_Repr(self->wrapped); if (wrapped_repr == NULL) return NULL; return PyString_FromFormat("<%s at %p wrapping %s at %p with factory %s>", Py_TYPE(self)->tp_name, self, PyString_AS_STRING(wrapped_repr), self->wrapped, PyString_AS_STRING(factory_repr)); #endif } else { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat("<%s at %p with factory %R>", Py_TYPE(self)->tp_name, self, self->factory); #else return PyString_FromFormat("<%s at %p with factory %s>", Py_TYPE(self)->tp_name, self, PyString_AS_STRING(factory_repr)); #endif } } /* ------------------------------------------------------------------------- */ static Py_hash_t Proxy_hash(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); return PyObject_Hash(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_str(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_Str(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_add(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Add(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_subtract(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Subtract(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_multiply(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Multiply(o1, o2); } /* ------------------------------------------------------------------------- */ #if PY_MAJOR_VERSION < 3 static PyObject *Proxy_divide(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Divide(o1, o2); } #endif /* ------------------------------------------------------------------------- */ static PyObject *Proxy_remainder(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Remainder(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_divmod(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Divmod(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_power(PyObject *o1, PyObject *o2, PyObject *modulo) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Power(o1, o2, modulo); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_negative(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyNumber_Negative(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_positive(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyNumber_Positive(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_absolute(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyNumber_Absolute(self->wrapped); } /* ------------------------------------------------------------------------- */ static int Proxy_bool(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); return PyObject_IsTrue(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_invert(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyNumber_Invert(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_lshift(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Lshift(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_rshift(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Rshift(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_and(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_And(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_xor(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Xor(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_or(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_Or(o1, o2); } /* ------------------------------------------------------------------------- */ #if PY_MAJOR_VERSION < 3 static PyObject *Proxy_int(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyNumber_Int(self->wrapped); } #endif /* ------------------------------------------------------------------------- */ static PyObject *Proxy_long(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyNumber_Long(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_float(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyNumber_Float(self->wrapped); } /* ------------------------------------------------------------------------- */ #if PY_MAJOR_VERSION < 3 static PyObject *Proxy_oct(ProxyObject *self) { PyNumberMethods *nb; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); if ((nb = self->wrapped->ob_type->tp_as_number) == NULL || nb->nb_oct == NULL) { PyErr_SetString(PyExc_TypeError, "oct() argument can't be converted to oct"); return NULL; } return (*nb->nb_oct)(self->wrapped); } #endif /* ------------------------------------------------------------------------- */ #if PY_MAJOR_VERSION < 3 static PyObject *Proxy_hex(ProxyObject *self) { PyNumberMethods *nb; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); if ((nb = self->wrapped->ob_type->tp_as_number) == NULL || nb->nb_hex == NULL) { PyErr_SetString(PyExc_TypeError, "hex() argument can't be converted to hex"); return NULL; } return (*nb->nb_hex)(self->wrapped); } #endif /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_add(ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceAdd(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_subtract( ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceSubtract(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_multiply( ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceMultiply(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ #if PY_MAJOR_VERSION < 3 static PyObject *Proxy_inplace_divide( ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceDivide(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } #endif /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_remainder( ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceRemainder(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_power(ProxyObject *self, PyObject *other, PyObject *modulo) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlacePower(self->wrapped, other, modulo); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_lshift(ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceLshift(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_rshift(ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceRshift(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_and(ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceAnd(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_xor(ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceXor(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_or(ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceOr(self->wrapped, other); Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_floor_divide(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_FloorDivide(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_true_divide(PyObject *o1, PyObject *o2) { Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2); return PyNumber_TrueDivide(o1, o2); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_floor_divide( ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceFloorDivide(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_inplace_true_divide( ProxyObject *self, PyObject *other) { PyObject *object = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(other); object = PyNumber_InPlaceTrueDivide(self->wrapped, other); if (!object) return NULL; Py_DECREF(self->wrapped); self->wrapped = object; Py_INCREF(self); return (PyObject *)self; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_index(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyNumber_Index(self->wrapped); } /* ------------------------------------------------------------------------- */ static Py_ssize_t Proxy_length(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); return PyObject_Length(self->wrapped); } /* ------------------------------------------------------------------------- */ static int Proxy_contains(ProxyObject *self, PyObject *value) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); return PySequence_Contains(self->wrapped, value); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_getitem(ProxyObject *self, PyObject *key) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetItem(self->wrapped, key); } /* ------------------------------------------------------------------------- */ static int Proxy_setitem(ProxyObject *self, PyObject *key, PyObject* value) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); if (value == NULL) return PyObject_DelItem(self->wrapped, key); else return PyObject_SetItem(self->wrapped, key, value); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_dir( ProxyObject *self, PyObject *args) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_Dir(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_enter( ProxyObject *self, PyObject *args, PyObject *kwds) { PyObject *method = NULL; PyObject *result = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); method = PyObject_GetAttrString(self->wrapped, "__enter__"); if (!method) return NULL; result = PyObject_Call(method, args, kwds); Py_DECREF(method); return result; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_exit( ProxyObject *self, PyObject *args, PyObject *kwds) { PyObject *method = NULL; PyObject *result = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); method = PyObject_GetAttrString(self->wrapped, "__exit__"); if (!method) return NULL; result = PyObject_Call(method, args, kwds); Py_DECREF(method); return result; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_bytes( ProxyObject *self, PyObject *args) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_Bytes(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_reversed( ProxyObject *self, PyObject *args) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_CallFunctionObjArgs((PyObject *)&PyReversed_Type, self->wrapped, NULL); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_reduce( ProxyObject *self, PyObject *args) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return Py_BuildValue("(O(O))", identity_ref, self->wrapped); } /* ------------------------------------------------------------------------- */ #if PY_MAJOR_VERSION >= 3 static PyObject *Proxy_round( ProxyObject *self, PyObject *args) { PyObject *module = NULL; PyObject *dict = NULL; PyObject *round = NULL; PyObject *result = NULL; Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); module = PyImport_ImportModule("builtins"); if (!module) return NULL; dict = PyModule_GetDict(module); round = PyDict_GetItemString(dict, "round"); if (!round) { Py_DECREF(module); return NULL; } Py_INCREF(round); Py_DECREF(module); result = PyObject_CallFunctionObjArgs(round, self->wrapped, NULL); Py_DECREF(round); return result; } #endif /* ------------------------------------------------------------------------- */ static PyObject *Proxy_get_name( ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetAttrString(self->wrapped, "__name__"); } /* ------------------------------------------------------------------------- */ static int Proxy_set_name(ProxyObject *self, PyObject *value) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); return PyObject_SetAttrString(self->wrapped, "__name__", value); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_get_qualname( ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetAttrString(self->wrapped, "__qualname__"); } /* ------------------------------------------------------------------------- */ static int Proxy_set_qualname(ProxyObject *self, PyObject *value) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); return PyObject_SetAttrString(self->wrapped, "__qualname__", value); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_get_module( ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetAttrString(self->wrapped, "__module__"); } /* ------------------------------------------------------------------------- */ static int Proxy_set_module(ProxyObject *self, PyObject *value) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); if (PyObject_SetAttrString(self->wrapped, "__module__", value) == -1) return -1; return PyDict_SetItemString(self->dict, "__module__", value); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_get_doc( ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetAttrString(self->wrapped, "__doc__"); } /* ------------------------------------------------------------------------- */ static int Proxy_set_doc(ProxyObject *self, PyObject *value) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); if (PyObject_SetAttrString(self->wrapped, "__doc__", value) == -1) return -1; return PyDict_SetItemString(self->dict, "__doc__", value); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_get_class( ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetAttrString(self->wrapped, "__class__"); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_get_annotations( ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetAttrString(self->wrapped, "__annotations__"); } /* ------------------------------------------------------------------------- */ static int Proxy_set_annotations(ProxyObject *self, PyObject *value) { Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); return PyObject_SetAttrString(self->wrapped, "__annotations__", value); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_get_wrapped( ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); Py_INCREF(self->wrapped); return self->wrapped; } /* ------------------------------------------------------------------------- */ static int Proxy_set_wrapped(ProxyObject *self, PyObject *value) { if (value) Py_INCREF(value); Py_XDECREF(self->wrapped); self->wrapped = value; return 0; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_get_factory( ProxyObject *self) { Py_INCREF(self->factory); return self->factory; } /* ------------------------------------------------------------------------- */ static int Proxy_set_factory(ProxyObject *self, PyObject *value) { if (value) Py_INCREF(value); Py_XDECREF(self->factory); self->factory = value; return 0; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_getattro( ProxyObject *self, PyObject *name) { PyObject *object = NULL; PyObject *result = NULL; static PyObject *getattr_str = NULL; object = PyObject_GenericGetAttr((PyObject *)self, name); if (object) return object; PyErr_Clear(); if (!getattr_str) { #if PY_MAJOR_VERSION >= 3 getattr_str = PyUnicode_InternFromString("__getattr__"); #else getattr_str = PyString_InternFromString("__getattr__"); #endif } object = PyObject_GenericGetAttr((PyObject *)self, getattr_str); if (!object) return NULL; result = PyObject_CallFunctionObjArgs(object, name, NULL); Py_DECREF(object); return result; } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_getattr( ProxyObject *self, PyObject *args) { PyObject *name = NULL; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args, "U:__getattr__", &name)) return NULL; #else if (!PyArg_ParseTuple(args, "S:__getattr__", &name)) return NULL; #endif Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetAttr(self->wrapped, name); } /* ------------------------------------------------------------------------- */ static int Proxy_setattro( ProxyObject *self, PyObject *name, PyObject *value) { if (PyObject_HasAttr((PyObject *)Py_TYPE(self), name)) return PyObject_GenericSetAttr((PyObject *)self, name, value); Proxy__ENSURE_WRAPPED_OR_RETURN_MINUS1(self); return PyObject_SetAttr(self->wrapped, name, value); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_richcompare(ProxyObject *self, PyObject *other, int opcode) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_RichCompare(self->wrapped, other, opcode); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_iter(ProxyObject *self) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_GetIter(self->wrapped); } /* ------------------------------------------------------------------------- */ static PyObject *Proxy_call( ProxyObject *self, PyObject *args, PyObject *kwds) { Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self); return PyObject_Call(self->wrapped, args, kwds); } /* ------------------------------------------------------------------------- */; static PyNumberMethods Proxy_as_number = { (binaryfunc)Proxy_add, /*nb_add*/ (binaryfunc)Proxy_subtract, /*nb_subtract*/ (binaryfunc)Proxy_multiply, /*nb_multiply*/ #if PY_MAJOR_VERSION < 3 (binaryfunc)Proxy_divide, /*nb_divide*/ #endif (binaryfunc)Proxy_remainder, /*nb_remainder*/ (binaryfunc)Proxy_divmod, /*nb_divmod*/ (ternaryfunc)Proxy_power, /*nb_power*/ (unaryfunc)Proxy_negative, /*nb_negative*/ (unaryfunc)Proxy_positive, /*nb_positive*/ (unaryfunc)Proxy_absolute, /*nb_absolute*/ (inquiry)Proxy_bool, /*nb_nonzero/nb_bool*/ (unaryfunc)Proxy_invert, /*nb_invert*/ (binaryfunc)Proxy_lshift, /*nb_lshift*/ (binaryfunc)Proxy_rshift, /*nb_rshift*/ (binaryfunc)Proxy_and, /*nb_and*/ (binaryfunc)Proxy_xor, /*nb_xor*/ (binaryfunc)Proxy_or, /*nb_or*/ #if PY_MAJOR_VERSION < 3 0, /*nb_coerce*/ #endif #if PY_MAJOR_VERSION < 3 (unaryfunc)Proxy_int, /*nb_int*/ (unaryfunc)Proxy_long, /*nb_long*/ #else (unaryfunc)Proxy_long, /*nb_int*/ 0, /*nb_long/nb_reserved*/ #endif (unaryfunc)Proxy_float, /*nb_float*/ #if PY_MAJOR_VERSION < 3 (unaryfunc)Proxy_oct, /*nb_oct*/ (unaryfunc)Proxy_hex, /*nb_hex*/ #endif (binaryfunc)Proxy_inplace_add, /*nb_inplace_add*/ (binaryfunc)Proxy_inplace_subtract, /*nb_inplace_subtract*/ (binaryfunc)Proxy_inplace_multiply, /*nb_inplace_multiply*/ #if PY_MAJOR_VERSION < 3 (binaryfunc)Proxy_inplace_divide, /*nb_inplace_divide*/ #endif (binaryfunc)Proxy_inplace_remainder, /*nb_inplace_remainder*/ (ternaryfunc)Proxy_inplace_power, /*nb_inplace_power*/ (binaryfunc)Proxy_inplace_lshift, /*nb_inplace_lshift*/ (binaryfunc)Proxy_inplace_rshift, /*nb_inplace_rshift*/ (binaryfunc)Proxy_inplace_and, /*nb_inplace_and*/ (binaryfunc)Proxy_inplace_xor, /*nb_inplace_xor*/ (binaryfunc)Proxy_inplace_or, /*nb_inplace_or*/ (binaryfunc)Proxy_floor_divide, /*nb_floor_divide*/ (binaryfunc)Proxy_true_divide, /*nb_true_divide*/ (binaryfunc)Proxy_inplace_floor_divide, /*nb_inplace_floor_divide*/ (binaryfunc)Proxy_inplace_true_divide, /*nb_inplace_true_divide*/ (unaryfunc)Proxy_index, /*nb_index*/ }; static PySequenceMethods Proxy_as_sequence = { (lenfunc)Proxy_length, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ (objobjproc)Proxy_contains, /* sq_contains */ }; static PyMappingMethods Proxy_as_mapping = { (lenfunc)Proxy_length, /*mp_length*/ (binaryfunc)Proxy_getitem, /*mp_subscript*/ (objobjargproc)Proxy_setitem, /*mp_ass_subscript*/ }; static PyMethodDef Proxy_methods[] = { { "__dir__", (PyCFunction)Proxy_dir, METH_NOARGS, 0 }, { "__enter__", (PyCFunction)Proxy_enter, METH_VARARGS | METH_KEYWORDS, 0 }, { "__exit__", (PyCFunction)Proxy_exit, METH_VARARGS | METH_KEYWORDS, 0 }, { "__getattr__", (PyCFunction)Proxy_getattr, METH_VARARGS , 0 }, { "__bytes__", (PyCFunction)Proxy_bytes, METH_NOARGS, 0 }, { "__reversed__", (PyCFunction)Proxy_reversed, METH_NOARGS, 0 }, { "__reduce__", (PyCFunction)Proxy_reduce, METH_NOARGS, 0 }, { "__reduce_ex__", (PyCFunction)Proxy_reduce, METH_O, 0 }, #if PY_MAJOR_VERSION >= 3 { "__round__", (PyCFunction)Proxy_round, METH_NOARGS, 0 }, #endif { NULL, NULL }, }; static PyGetSetDef Proxy_getset[] = { { "__name__", (getter)Proxy_get_name, (setter)Proxy_set_name, 0 }, { "__qualname__", (getter)Proxy_get_qualname, (setter)Proxy_set_qualname, 0 }, { "__module__", (getter)Proxy_get_module, (setter)Proxy_set_module, 0 }, { "__doc__", (getter)Proxy_get_doc, (setter)Proxy_set_doc, 0 }, { "__class__", (getter)Proxy_get_class, NULL, 0 }, { "__annotations__", (getter)Proxy_get_annotations, (setter)Proxy_set_annotations, 0 }, { "__wrapped__", (getter)Proxy_get_wrapped, (setter)Proxy_set_wrapped, 0 }, { "__factory__", (getter)Proxy_get_factory, (setter)Proxy_set_factory, 0 }, { NULL }, }; PyTypeObject Proxy_Type = { PyVarObject_HEAD_INIT(NULL, 0) "Proxy", /*tp_name*/ sizeof(ProxyObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)Proxy_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (unaryfunc)Proxy_repr, /*tp_repr*/ &Proxy_as_number, /*tp_as_number*/ &Proxy_as_sequence, /*tp_as_sequence*/ &Proxy_as_mapping, /*tp_as_mapping*/ (hashfunc)Proxy_hash, /*tp_hash*/ (ternaryfunc)Proxy_call, /*tp_call*/ (unaryfunc)Proxy_str, /*tp_str*/ (getattrofunc)Proxy_getattro, /*tp_getattro*/ (setattrofunc)Proxy_setattro, /*tp_setattro*/ 0, /*tp_as_buffer*/ #if PY_MAJOR_VERSION < 3 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES, /*tp_flags*/ #else Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ #endif 0, /*tp_doc*/ (traverseproc)Proxy_traverse, /*tp_traverse*/ (inquiry)Proxy_clear, /*tp_clear*/ (richcmpfunc)Proxy_richcompare, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ (getiterfunc)Proxy_iter, /*tp_iter*/ 0, /*tp_iternext*/ Proxy_methods, /*tp_methods*/ 0, /*tp_members*/ Proxy_getset, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ offsetof(ProxyObject, dict), /*tp_dictoffset*/ (initproc)Proxy_init, /*tp_init*/ PyType_GenericAlloc, /*tp_alloc*/ Proxy_new, /*tp_new*/ PyObject_GC_Del, /*tp_free*/ 0, /*tp_is_gc*/ }; /* ------------------------------------------------------------------------- */ #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "lazy_object_proxy.cext", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ module_functions, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif static PyObject * moduleinit(void) { PyObject *module; PyObject *dict; #if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&moduledef); #else module = Py_InitModule3("lazy_object_proxy.cext", module_functions, NULL); #endif if (module == NULL) return NULL; if (PyType_Ready(&Proxy_Type) < 0) return NULL; dict = PyModule_GetDict(module); if (dict == NULL) return NULL; identity_ref = PyDict_GetItemString(dict, "identity"); if (identity_ref == NULL) return NULL; Py_INCREF(identity_ref); Py_INCREF(&Proxy_Type); PyModule_AddObject(module, "Proxy", (PyObject *)&Proxy_Type); return module; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initcext(void) { moduleinit(); } #else PyMODINIT_FUNC PyInit_cext(void) { return moduleinit(); } #endif /* ------------------------------------------------------------------------- */ lazy-object-proxy-1.3.1/src/lazy_object_proxy/utils.py0000664000175000017500000000044313102345227023425 0ustar ionelionel00000000000000def identity(obj): return obj class cached_property(object): def __init__(self, func): self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value lazy-object-proxy-1.3.1/.cookiecutterrc0000664000175000017500000000204113102352621020374 0ustar ionelionel00000000000000# Generated by cookiepatcher, a small shim around cookiecutter (pip install cookiepatcher) cookiecutter: appveyor: 'yes' c_extension_cython: 'no' c_extension_optional: 'yes' c_extension_support: 'yes' codacy: 'yes' codeclimate: 'yes' codecov: 'yes' command_line_interface: 'no' command_line_interface_bin_name: '-' coveralls: 'yes' distribution_name: lazy-object-proxy email: contact@ionelmc.ro full_name: Ionel Cristian Mărieș github_username: ionelmc landscape: 'yes' package_name: lazy_object_proxy project_name: lazy-object-proxy project_short_description: A fast and thorough lazy object proxy. release_date: '2016-04-14' repo_name: python-lazy-object-proxy requiresio: 'yes' scrutinizer: 'yes' sphinx_doctest: 'no' sphinx_theme: sphinx-py3doc-enhanced-theme test_matrix_configurator: 'yes' test_matrix_separate_coverage: 'no' test_runner: pytest travis: 'yes' version: 1.2.2 website: https://blog.ionelmc.ro year: 2014-2017 lazy-object-proxy-1.3.1/ci/0000775000175000017500000000000013103065765015757 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/ci/appveyor-download.py0000775000175000017500000000736513102352620022005 0ustar ionelionel00000000000000#!/usr/bin/env python """ Use the AppVeyor API to download Windows artifacts. Taken from: https://bitbucket.org/ned/coveragepy/src/tip/ci/download_appveyor.py # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt """ from __future__ import unicode_literals import argparse import os import zipfile import requests def make_auth_headers(): """Make the authentication headers needed to use the Appveyor API.""" path = os.path.expanduser("~/.appveyor.token") if not os.path.exists(path): raise RuntimeError( "Please create a file named `.appveyor.token` in your home directory. " "You can get the token from https://ci.appveyor.com/api-token" ) with open(path) as f: token = f.read().strip() headers = { 'Authorization': 'Bearer {}'.format(token), } return headers def download_latest_artifacts(account_project, build_id): """Download all the artifacts from the latest build.""" if build_id is None: url = "https://ci.appveyor.com/api/projects/{}".format(account_project) else: url = "https://ci.appveyor.com/api/projects/{}/build/{}".format(account_project, build_id) build = requests.get(url, headers=make_auth_headers()).json() jobs = build['build']['jobs'] print(u"Build {0[build][version]}, {1} jobs: {0[build][message]}".format(build, len(jobs))) for job in jobs: name = job['name'] print(u" {0}: {1[status]}, {1[artifactsCount]} artifacts".format(name, job)) url = "https://ci.appveyor.com/api/buildjobs/{}/artifacts".format(job['jobId']) response = requests.get(url, headers=make_auth_headers()) artifacts = response.json() for artifact in artifacts: is_zip = artifact['type'] == "Zip" filename = artifact['fileName'] print(u" {0}, {1} bytes".format(filename, artifact['size'])) url = "https://ci.appveyor.com/api/buildjobs/{}/artifacts/{}".format(job['jobId'], filename) download_url(url, filename, make_auth_headers()) if is_zip: unpack_zipfile(filename) os.remove(filename) def ensure_dirs(filename): """Make sure the directories exist for `filename`.""" dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): os.makedirs(dirname) def download_url(url, filename, headers): """Download a file from `url` to `filename`.""" ensure_dirs(filename) response = requests.get(url, headers=headers, stream=True) if response.status_code == 200: with open(filename, 'wb') as f: for chunk in response.iter_content(16 * 1024): f.write(chunk) else: print(u" Error downloading {}: {}".format(url, response)) def unpack_zipfile(filename): """Unpack a zipfile, using the names in the zip.""" with open(filename, 'rb') as fzip: z = zipfile.ZipFile(fzip) for name in z.namelist(): print(u" extracting {}".format(name)) ensure_dirs(name) z.extract(name) parser = argparse.ArgumentParser(description='Download artifacts from AppVeyor.') parser.add_argument('--id', metavar='PROJECT_ID', default='ionelmc/python-lazy-object-proxy', help='Project ID in AppVeyor.') parser.add_argument('build', nargs='?', metavar='BUILD_ID', help='Build ID in AppVeyor. Eg: master-123') if __name__ == "__main__": # import logging # logging.basicConfig(level="DEBUG") args = parser.parse_args() download_latest_artifacts(args.id, args.build) lazy-object-proxy-1.3.1/ci/appveyor-bootstrap.py0000664000175000017500000001101113102352646022177 0ustar ionelionel00000000000000""" AppVeyor will at least have few Pythons around so there's no point of implementing a bootstrapper in PowerShell. This is a port of https://github.com/pypa/python-packaging-user-guide/blob/master/source/code/install.ps1 with various fixes and improvements that just weren't feasible to implement in PowerShell. """ from __future__ import print_function from os import environ from os.path import exists from subprocess import check_call try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve BASE_URL = "https://www.python.org/ftp/python/" GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py" GET_PIP_PATH = "C:\get-pip.py" URLS = { ("2.6", "64"): BASE_URL + "2.6.6/python-2.6.6.amd64.msi", ("2.6", "32"): BASE_URL + "2.6.6/python-2.6.6.msi", ("2.7", "64"): BASE_URL + "2.7.10/python-2.7.13.amd64.msi", ("2.7", "32"): BASE_URL + "2.7.10/python-2.7.13.msi", # NOTE: no .msi installer for 3.3.6 ("3.3", "64"): BASE_URL + "3.3.3/python-3.3.5.amd64.msi", ("3.3", "32"): BASE_URL + "3.3.3/python-3.3.5.msi", ("3.4", "64"): BASE_URL + "3.4.3/python-3.4.6.amd64.msi", ("3.4", "32"): BASE_URL + "3.4.3/python-3.4.6.msi", ("3.5", "64"): BASE_URL + "3.5.0/python-3.5.3-amd64.exe", ("3.5", "32"): BASE_URL + "3.5.0/python-3.5.3.exe", ("3.6", "64"): BASE_URL + "3.6.0/python-3.6.0-amd64.exe", ("3.6", "32"): BASE_URL + "3.6.0/python-3.6.0.exe", } INSTALL_CMD = { # Commands are allowed to fail only if they are not the last command. Eg: uninstall (/x) allowed to fail. "2.6": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"], ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]], "2.7": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"], ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]], "3.3": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"], ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]], "3.4": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"], ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]], "3.5": [["{path}", "/quiet", "TargetDir={home}"]], "3.6": [["{path}", "/quiet", "TargetDir={home}"]], } def download_file(url, path): print("Downloading: {} (into {})".format(url, path)) progress = [0, 0] def report(count, size, total): progress[0] = count * size if progress[0] - progress[1] > 1000000: progress[1] = progress[0] print("Downloaded {:,}/{:,} ...".format(progress[1], total)) dest, _ = urlretrieve(url, path, reporthook=report) return dest def install_python(version, arch, home): print("Installing Python", version, "for", arch, "bit architecture to", home) if exists(home): return path = download_python(version, arch) print("Installing", path, "to", home) success = False for cmd in INSTALL_CMD[version]: cmd = [part.format(home=home, path=path) for part in cmd] print("Running:", " ".join(cmd)) try: check_call(cmd) except Exception as exc: print("Failed command", cmd, "with:", exc) if exists("install.log"): with open("install.log") as fh: print(fh.read()) else: success = True if success: print("Installation complete!") else: print("Installation failed") def download_python(version, arch): for _ in range(3): try: return download_file(URLS[version, arch], "installer.exe") except Exception as exc: print("Failed to download:", exc) print("Retrying ...") def install_pip(home): pip_path = home + "/Scripts/pip.exe" python_path = home + "/python.exe" if exists(pip_path): print("pip already installed.") else: print("Installing pip...") download_file(GET_PIP_URL, GET_PIP_PATH) print("Executing:", python_path, GET_PIP_PATH) check_call([python_path, GET_PIP_PATH]) def install_packages(home, *packages): cmd = [home + "/Scripts/pip.exe", "install"] cmd.extend(packages) check_call(cmd) if __name__ == "__main__": install_python(environ['PYTHON_VERSION'], environ['PYTHON_ARCH'], environ['PYTHON_HOME']) install_pip(environ['PYTHON_HOME']) install_packages(environ['PYTHON_HOME'], "setuptools>=18.0.1", "wheel", "tox", "virtualenv>=13.1.0") lazy-object-proxy-1.3.1/ci/appveyor-with-compiler.cmd0000664000175000017500000000311113103065617023062 0ustar ionelionel00000000000000:: To build extensions for 64 bit Python 3, we need to configure environment :: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of: :: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1) :: :: To build extensions for 64 bit Python 2, we need to configure environment :: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of: :: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0) :: :: 32 bit builds do not require specific environment configurations. :: :: Note: this script needs to be run with the /E:ON and /V:ON flags for the :: cmd interpreter, at least for (SDK v7.0) :: :: More details at: :: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows :: http://stackoverflow.com/a/13751649/163740 :: :: Author: Olivier Grisel :: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/ SET COMMAND_TO_RUN=%* SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows SET WIN_WDK="c:\Program Files (x86)\Windows Kits\10\Include\wdf" ECHO SDK: %WINDOWS_SDK_VERSION% ARCH: %PYTHON_ARCH% IF "%PYTHON_VERSION%"=="3.5" GOTO main IF "%PYTHON_VERSION%"=="3.6" GOTO main IF "%PYTHON_ARCH%"=="32" GOTO main SET DISTUTILS_USE_SDK=1 SET MSSdk=1 "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION% CALL "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release :main IF EXIST %WIN_WDK% ( REM See: https://connect.microsoft.com/VisualStudio/feedback/details/1610302/ REN %WIN_WDK% 0wdf ) ECHO Executing: %COMMAND_TO_RUN% CALL %COMMAND_TO_RUN% || EXIT 1 lazy-object-proxy-1.3.1/ci/bootstrap.py0000775000175000017500000000454313102352620020343 0ustar ionelionel00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import os import sys from os.path import abspath from os.path import dirname from os.path import exists from os.path import join if __name__ == "__main__": base_path = dirname(dirname(abspath(__file__))) print("Project path: {0}".format(base_path)) env_path = join(base_path, ".tox", "bootstrap") if sys.platform == "win32": bin_path = join(env_path, "Scripts") else: bin_path = join(env_path, "bin") if not exists(env_path): import subprocess print("Making bootstrap env in: {0} ...".format(env_path)) try: subprocess.check_call(["virtualenv", env_path]) except subprocess.CalledProcessError: subprocess.check_call([sys.executable, "-m", "virtualenv", env_path]) print("Installing `jinja2` and `matrix` into bootstrap environment...") subprocess.check_call([join(bin_path, "pip"), "install", "jinja2", "matrix"]) activate = join(bin_path, "activate_this.py") # noinspection PyCompatibility exec(compile(open(activate, "rb").read(), activate, "exec"), dict(__file__=activate)) import jinja2 import matrix jinja = jinja2.Environment( loader=jinja2.FileSystemLoader(join(base_path, "ci", "templates")), trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True ) tox_environments = {} for (alias, conf) in matrix.from_file(join(base_path, "setup.cfg")).items(): python = conf["python_versions"] deps = conf["dependencies"] tox_environments[alias] = { "python": "python" + python if "py" not in python else python, "deps": deps.split(), } if "coverage_flags" in conf: cover = {"false": False, "true": True}[conf["coverage_flags"].lower()] tox_environments[alias].update(cover=cover) if "environment_variables" in conf: env_vars = conf["environment_variables"] tox_environments[alias].update(env_vars=env_vars.split()) for name in os.listdir(join("ci", "templates")): with open(join(base_path, name), "w") as fh: fh.write(jinja.get_template(name).render(tox_environments=tox_environments)) print("Wrote {}".format(name)) print("DONE.") lazy-object-proxy-1.3.1/ci/templates/0000775000175000017500000000000013103065765017755 5ustar ionelionel00000000000000lazy-object-proxy-1.3.1/ci/templates/tox.ini0000664000175000017500000000546613102433674021300 0ustar ionelionel00000000000000[tox] envlist = clean, check, {% for env in tox_environments|sort %} {{ env }}, {% endfor %} report, docs [testenv] basepython = {docs,spell}: {env:TOXPYTHON:python2.7} {bootstrap,clean,check,report,extension-coveralls,coveralls,codecov}: {env:TOXPYTHON:python3} setenv = PYTHONPATH={toxinidir}/tests PYTHONUNBUFFERED=yes passenv = * deps = setuptools>=6.0 pytest pytest-capturelog pytest-benchmark commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test -vv --ignore=src} [testenv:spell] setenv = SPELLCHECK=1 commands = sphinx-build -b spelling docs dist/docs skip_install = true usedevelop = false deps = -r{toxinidir}/docs/requirements.txt sphinxcontrib-spelling pyenchant [testenv:docs] deps = -r{toxinidir}/docs/requirements.txt commands = sphinx-build {posargs:-E} -b html docs dist/docs sphinx-build -b linkcheck docs dist/docs [testenv:bootstrap] deps = jinja2 matrix skip_install = true usedevelop = false commands = python ci/bootstrap.py passenv = * [testenv:check] deps = docutils check-manifest flake8 readme-renderer pygments isort skip_install = true usedevelop = false commands = python setup.py check --strict --metadata --restructuredtext check-manifest {toxinidir} flake8 src tests setup.py isort --verbose --check-only --diff --recursive src tests setup.py [testenv:coveralls] deps = coveralls skip_install = true usedevelop = false commands = coveralls --merge=extension-coveralls.json [] [testenv:codecov] deps = codecov skip_install = true usedevelop = false commands = coverage xml --ignore-errors codecov [] [testenv:extension-coveralls] deps = cpp-coveralls skip_install = true usedevelop = false commands = coveralls --build-root=. --include=src --dump=extension-coveralls.json [] [testenv:report] deps = coverage skip_install = true usedevelop = false commands = coverage combine --append coverage report coverage html [testenv:clean] commands = coverage erase skip_install = true usedevelop = false deps = coverage {% for env, config in tox_environments|dictsort %} [testenv:{{ env }}] basepython = {env:TOXPYTHON:{{ config.python }}} {% if config.cover or config.env_vars %} setenv = {[testenv]setenv} {% endif %} {% for var in config.env_vars %} {{ var }} {% endfor %} {% if config.cover %} WITH_COVERAGE=yes SETUPPY_CFLAGS=-coverage usedevelop = true commands = python setup.py clean --all build_ext --force --inplace {posargs:py.test --cov --cov-report=term-missing -vv} {% endif %} {% if config.cover or config.deps %} deps = {[testenv]deps} {% endif %} {% if config.cover %} pytest-cov {% endif %} {% for dep in config.deps %} {{ dep }} {% endfor %} {% endfor %} lazy-object-proxy-1.3.1/ci/templates/.travis.yml0000664000175000017500000000361413102352646022066 0ustar ionelionel00000000000000language: python sudo: false cache: pip env: global: - LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so - SEGFAULT_SIGNALS=all matrix: - TOXENV=check - TOXENV=docs matrix: include: {%- for env, config in tox_environments|dictsort %}{{ '' }} - python: '{{ env.split('-')[0] }}' env: - TOXENV={{ env }}{% if config.cover %},report,extension-coveralls,coveralls,codecov{% endif -%} {% endfor %} before_install: - python --version - uname -a - lsb_release -a install: - pip install -U tox virtualenv - virtualenv --version - easy_install --version - pip --version - tox --version - | set -ex if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then (cd $HOME wget https://bitbucket.org/squeaky/portable-pypy/downloads/pypy-5.7.1-linux_x86_64-portable.tar.bz2 tar xf pypy-5.7.1-linux_x86_64-portable.tar.bz2 pypy-5.7.1-linux_x86_64-portable/bin/pypy -m ensurepip pypy-5.7.1-linux_x86_64-portable/bin/pypy -m pip install -U virtualenv) export PATH=$HOME/pypy-5.7.1-linux_x86_64-portable/bin/:$PATH export TOXPYTHON=$HOME/pypy-5.7.1-linux_x86_64-portable/bin/pypy fi if [[ $TRAVIS_PYTHON_VERSION == 'pypy3' ]]; then (cd $HOME wget https://bitbucket.org/squeaky/portable-pypy/downloads/pypy3.5-5.7.1-beta-linux_x86_64-portable.tar.bz2 tar xf pypy3.5-5.7.1-beta-linux_x86_64-portable.tar.bz2 pypy3.5-5.7.1-beta-linux_x86_64-portable/bin/pypy3 -m ensurepip pypy3.5-5.7.1-beta-linux_x86_64-portable/bin/pypy3 -m pip install -U virtualenv) export PATH=$HOME/pypy3.5-5.7.1-beta-linux_x86_64-portable/bin/:$PATH export TOXPYTHON=$HOME/pypy3.5-5.7.1-beta-linux_x86_64-portable/bin/pypy3 fi set +x script: - tox -v after_failure: - more .tox/log/* | cat - more .tox/*/log/* | cat notifications: email: on_success: never on_failure: always lazy-object-proxy-1.3.1/ci/templates/appveyor.yml0000664000175000017500000000375013102433674022347 0ustar ionelionel00000000000000version: '{branch}-{build}' build: off cache: - '%LOCALAPPDATA%\pip\Cache' environment: global: WITH_COMPILER: 'cmd /E:ON /V:ON /C .\ci\appveyor-with-compiler.cmd' matrix: - TOXENV: check TOXPYTHON: C:\Python27\python.exe PYTHON_HOME: C:\Python27 PYTHON_VERSION: '2.7' PYTHON_ARCH: '32' {% for env, config in tox_environments|dictsort %}{{ '' }}{% if config.python.startswith('python') %} - TOXENV: '{{ env }}{% if config.cover %},report,codecov{% endif %}' TOXPYTHON: C:\{{ config.python.replace('.', '').capitalize() }}\python.exe PYTHON_HOME: C:\{{ config.python.replace('.', '').capitalize() }} PYTHON_VERSION: '{{ config.python[-3:] }}' PYTHON_ARCH: '32' - TOXENV: '{{ env }}{% if config.cover %},report,codecov{% endif %}' TOXPYTHON: C:\{{ config.python.replace('.', '').capitalize() }}-x64\python.exe {%- if config.python != 'python3.5' %} WINDOWS_SDK_VERSION: v7.{{ '1' if config.python[-3] == '3' else '0' }} {%- endif %} PYTHON_HOME: C:\{{ config.python.replace('.', '').capitalize() }}-x64 PYTHON_VERSION: '{{ config.python[-3:] }}' PYTHON_ARCH: '64' {% endif %}{% endfor %} init: - ps: echo $env:TOXENV - ps: ls C:\Python* install: - python -u ci\appveyor-bootstrap.py - '%PYTHON_HOME%\Scripts\virtualenv --version' - '%PYTHON_HOME%\Scripts\easy_install --version' - '%PYTHON_HOME%\Scripts\pip --version' - '%PYTHON_HOME%\Scripts\tox --version' test_script: - '%WITH_COMPILER% %PYTHON_HOME%\Scripts\tox' after_test: - IF "%TOXENV:~-6,6%" == "-nocov" %WITH_COMPILER% %TOXPYTHON% setup.py bdist_wheel on_failure: - ps: dir "env:" - ps: get-content .tox\*\log\* artifacts: - path: dist\* ### To enable remote debugging uncomment this (also, see: http://www.appveyor.com/docs/how-to/rdp-to-build-worker): # on_finish: # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) lazy-object-proxy-1.3.1/.bumpversion.cfg0000664000175000017500000000032313103065740020463 0ustar ionelionel00000000000000[bumpversion] current_version = 1.3.1 commit = True tag = True [bumpversion:file:setup.py] [bumpversion:file:README.rst] [bumpversion:file:docs/conf.py] [bumpversion:file:src/lazy_object_proxy/__init__.py] lazy-object-proxy-1.3.1/appveyor.yml0000664000175000017500000001232413102433674017753 0ustar ionelionel00000000000000version: '{branch}-{build}' build: off cache: - '%LOCALAPPDATA%\pip\Cache' environment: global: WITH_COMPILER: 'cmd /E:ON /V:ON /C .\ci\appveyor-with-compiler.cmd' matrix: - TOXENV: check TOXPYTHON: C:\Python27\python.exe PYTHON_HOME: C:\Python27 PYTHON_VERSION: '2.7' PYTHON_ARCH: '32' - TOXENV: '2.6-cover,report,codecov' TOXPYTHON: C:\Python26\python.exe PYTHON_HOME: C:\Python26 PYTHON_VERSION: '2.6' PYTHON_ARCH: '32' - TOXENV: '2.6-cover,report,codecov' TOXPYTHON: C:\Python26-x64\python.exe WINDOWS_SDK_VERSION: v7.0 PYTHON_HOME: C:\Python26-x64 PYTHON_VERSION: '2.6' PYTHON_ARCH: '64' - TOXENV: '2.6-nocov' TOXPYTHON: C:\Python26\python.exe PYTHON_HOME: C:\Python26 PYTHON_VERSION: '2.6' PYTHON_ARCH: '32' - TOXENV: '2.6-nocov' TOXPYTHON: C:\Python26-x64\python.exe WINDOWS_SDK_VERSION: v7.0 PYTHON_HOME: C:\Python26-x64 PYTHON_VERSION: '2.6' PYTHON_ARCH: '64' - TOXENV: '2.7-cover,report,codecov' TOXPYTHON: C:\Python27\python.exe PYTHON_HOME: C:\Python27 PYTHON_VERSION: '2.7' PYTHON_ARCH: '32' - TOXENV: '2.7-cover,report,codecov' TOXPYTHON: C:\Python27-x64\python.exe WINDOWS_SDK_VERSION: v7.0 PYTHON_HOME: C:\Python27-x64 PYTHON_VERSION: '2.7' PYTHON_ARCH: '64' - TOXENV: '2.7-nocov' TOXPYTHON: C:\Python27\python.exe PYTHON_HOME: C:\Python27 PYTHON_VERSION: '2.7' PYTHON_ARCH: '32' - TOXENV: '2.7-nocov' TOXPYTHON: C:\Python27-x64\python.exe WINDOWS_SDK_VERSION: v7.0 PYTHON_HOME: C:\Python27-x64 PYTHON_VERSION: '2.7' PYTHON_ARCH: '64' - TOXENV: '3.3-cover,report,codecov' TOXPYTHON: C:\Python33\python.exe PYTHON_HOME: C:\Python33 PYTHON_VERSION: '3.3' PYTHON_ARCH: '32' - TOXENV: '3.3-cover,report,codecov' TOXPYTHON: C:\Python33-x64\python.exe WINDOWS_SDK_VERSION: v7.1 PYTHON_HOME: C:\Python33-x64 PYTHON_VERSION: '3.3' PYTHON_ARCH: '64' - TOXENV: '3.3-nocov' TOXPYTHON: C:\Python33\python.exe PYTHON_HOME: C:\Python33 PYTHON_VERSION: '3.3' PYTHON_ARCH: '32' - TOXENV: '3.3-nocov' TOXPYTHON: C:\Python33-x64\python.exe WINDOWS_SDK_VERSION: v7.1 PYTHON_HOME: C:\Python33-x64 PYTHON_VERSION: '3.3' PYTHON_ARCH: '64' - TOXENV: '3.4-cover,report,codecov' TOXPYTHON: C:\Python34\python.exe PYTHON_HOME: C:\Python34 PYTHON_VERSION: '3.4' PYTHON_ARCH: '32' - TOXENV: '3.4-cover,report,codecov' TOXPYTHON: C:\Python34-x64\python.exe WINDOWS_SDK_VERSION: v7.1 PYTHON_HOME: C:\Python34-x64 PYTHON_VERSION: '3.4' PYTHON_ARCH: '64' - TOXENV: '3.4-nocov' TOXPYTHON: C:\Python34\python.exe PYTHON_HOME: C:\Python34 PYTHON_VERSION: '3.4' PYTHON_ARCH: '32' - TOXENV: '3.4-nocov' TOXPYTHON: C:\Python34-x64\python.exe WINDOWS_SDK_VERSION: v7.1 PYTHON_HOME: C:\Python34-x64 PYTHON_VERSION: '3.4' PYTHON_ARCH: '64' - TOXENV: '3.5-cover,report,codecov' TOXPYTHON: C:\Python35\python.exe PYTHON_HOME: C:\Python35 PYTHON_VERSION: '3.5' PYTHON_ARCH: '32' - TOXENV: '3.5-cover,report,codecov' TOXPYTHON: C:\Python35-x64\python.exe PYTHON_HOME: C:\Python35-x64 PYTHON_VERSION: '3.5' PYTHON_ARCH: '64' - TOXENV: '3.5-nocov' TOXPYTHON: C:\Python35\python.exe PYTHON_HOME: C:\Python35 PYTHON_VERSION: '3.5' PYTHON_ARCH: '32' - TOXENV: '3.5-nocov' TOXPYTHON: C:\Python35-x64\python.exe PYTHON_HOME: C:\Python35-x64 PYTHON_VERSION: '3.5' PYTHON_ARCH: '64' - TOXENV: '3.6-cover,report,codecov' TOXPYTHON: C:\Python36\python.exe PYTHON_HOME: C:\Python36 PYTHON_VERSION: '3.6' PYTHON_ARCH: '32' - TOXENV: '3.6-cover,report,codecov' TOXPYTHON: C:\Python36-x64\python.exe WINDOWS_SDK_VERSION: v7.1 PYTHON_HOME: C:\Python36-x64 PYTHON_VERSION: '3.6' PYTHON_ARCH: '64' - TOXENV: '3.6-nocov' TOXPYTHON: C:\Python36\python.exe PYTHON_HOME: C:\Python36 PYTHON_VERSION: '3.6' PYTHON_ARCH: '32' - TOXENV: '3.6-nocov' TOXPYTHON: C:\Python36-x64\python.exe WINDOWS_SDK_VERSION: v7.1 PYTHON_HOME: C:\Python36-x64 PYTHON_VERSION: '3.6' PYTHON_ARCH: '64' init: - ps: echo $env:TOXENV - ps: ls C:\Python* install: - python -u ci\appveyor-bootstrap.py - '%PYTHON_HOME%\Scripts\virtualenv --version' - '%PYTHON_HOME%\Scripts\easy_install --version' - '%PYTHON_HOME%\Scripts\pip --version' - '%PYTHON_HOME%\Scripts\tox --version' test_script: - '%WITH_COMPILER% %PYTHON_HOME%\Scripts\tox' after_test: - IF "%TOXENV:~-6,6%" == "-nocov" %WITH_COMPILER% %TOXPYTHON% setup.py bdist_wheel on_failure: - ps: dir "env:" - ps: get-content .tox\*\log\* artifacts: - path: dist\* ### To enable remote debugging uncomment this (also, see: http://www.appveyor.com/docs/how-to/rdp-to-build-worker): # on_finish: # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))