Skip to content

Commit

Permalink
Merge pull request #241 from bashtage/vendor-cached-property
Browse files Browse the repository at this point in the history
MAINT: Vendor cached_property
  • Loading branch information
bashtage committed Oct 3, 2018
2 parents 8893cdf + 0a2b4f2 commit 4a1130e
Show file tree
Hide file tree
Showing 8 changed files with 192 additions and 5 deletions.
1 change: 1 addition & 0 deletions .coveragerc
Expand Up @@ -6,6 +6,7 @@ include = */arch/*
omit =
*/_version.py
*/compat/*
*/vendor/*
plugins = Cython.Coverage

[report]
Expand Down
2 changes: 1 addition & 1 deletion .travis.yml
Expand Up @@ -79,7 +79,7 @@ before_install:
- echo conda create --yes --quiet -n arch-test ${PKGS}
- conda create --yes --quiet -n arch-test ${PKGS}
- source activate arch-test
- pip install flake8 nbconvert nbformat pytest coverage coveralls pytest-cov codecov pytest-xdist
- pip install flake8 nbconvert nbformat pytest coverage coveralls pytest-cov codecov pytest-xdist cached_property
- if [[ "$STATSMODELS_MASTER" == true ]]; then sh ./ci/statsmodels-master.sh; fi;
- |
if [[ "$DOCBUILD" == true ]]; then
Expand Down
2 changes: 1 addition & 1 deletion appveyor.yml
Expand Up @@ -22,7 +22,7 @@ build_script:
- cmd: conda config --set always_yes yes
- cmd: conda update conda --quiet
- cmd: conda install numpy cython pytest pandas scipy patsy statsmodels matplotlib numba nbconvert nbformat pip pyyaml setuptools pyqt pyparsing --quiet
- cmd: pip install pytest-xdist
- cmd: pip install pytest-xdist cached_property
- cmd: python setup.py develop

test_script:
Expand Down
2 changes: 1 addition & 1 deletion arch/univariate/base.py
Expand Up @@ -8,7 +8,6 @@
import datetime as dt
import warnings

from cached_property import cached_property
import numpy as np
import scipy.stats as stats
import pandas as pd
Expand All @@ -21,6 +20,7 @@
from arch.utility.array import ensure1d, DocStringInheritor
from arch.utility.exceptions import ConvergenceWarning, StartingValueWarning, \
convergence_warning, starting_value_warning
from arch.vendor.cached_property import cached_property

__all__ = ['implicit_constant', 'ARCHModelResult', 'ARCHModel', 'ARCHModelForecast']

Expand Down
2 changes: 1 addition & 1 deletion arch/univariate/mean.py
Expand Up @@ -7,7 +7,6 @@
import copy
from collections import OrderedDict

from cached_property import cached_property
import numpy as np
from pandas import DataFrame
from scipy.optimize import OptimizeResult
Expand All @@ -18,6 +17,7 @@
from arch.univariate.distribution import Normal, StudentsT, SkewStudent, GeneralizedError
from arch.univariate.volatility import ARCH, GARCH, HARCH, ConstantVariance, EGARCH
from arch.utility.array import ensure1d, parse_dataframe, cutoff_to_index
from arch.vendor.cached_property import cached_property

__all__ = ['HARX', 'ConstantMean', 'ZeroMean', 'ARX', 'arch_model', 'LS']

Expand Down
7 changes: 7 additions & 0 deletions arch/vendor/__init__.py
@@ -0,0 +1,7 @@
try:
# Prefer system installed version if available
from cached_property import cached_property
except ImportError:
from arch.vendor.cached_property import cached_property

__all__ = ['cached_property']
179 changes: 179 additions & 0 deletions arch/vendor/cached_property.py
@@ -0,0 +1,179 @@
"""
Copyright (c) 2015, Daniel Greenfeld
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* 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.
* Neither the name of cached-property nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
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.
"""

# -*- coding: utf-8 -*-

__author__ = "Daniel Greenfeld"
__email__ = "pydanny@gmail.com"
__version__ = "1.5.1"
__license__ = "BSD"

from time import time
import threading

try:
import asyncio
except (ImportError, SyntaxError):
asyncio = None


class cached_property(object):
"""
A property that is only computed once per instance and then replaces itself
with an ordinary attribute. Deleting the attribute resets the property.
Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
""" # noqa

def __init__(self, func):
self.__doc__ = getattr(func, "__doc__")
self.func = func

def __get__(self, obj, cls):
if obj is None:
return self

if asyncio and asyncio.iscoroutinefunction(self.func):
return self._wrap_in_coroutine(obj)

value = obj.__dict__[self.func.__name__] = self.func(obj)
return value

def _wrap_in_coroutine(self, obj):

@asyncio.coroutine
def wrapper():
future = asyncio.ensure_future(self.func(obj))
obj.__dict__[self.func.__name__] = future
return future

return wrapper()


class threaded_cached_property(object):
"""
A cached_property version for use in environments where multiple threads
might concurrently try to access the property.
"""

def __init__(self, func):
self.__doc__ = getattr(func, "__doc__")
self.func = func
self.lock = threading.RLock()

def __get__(self, obj, cls):
if obj is None:
return self

obj_dict = obj.__dict__
name = self.func.__name__
with self.lock:
try:
# check if the value was computed before the lock was acquired
return obj_dict[name]

except KeyError:
# if not, do the calculation and release the lock
return obj_dict.setdefault(name, self.func(obj))


class cached_property_with_ttl(object):
"""
A property that is only computed once per instance and then replaces itself
with an ordinary attribute. Setting the ttl to a number expresses how long
the property will last before being timed out.
"""

def __init__(self, ttl=None):
if callable(ttl):
func = ttl
ttl = None
else:
func = None
self.ttl = ttl
self._prepare_func(func)

def __call__(self, func):
self._prepare_func(func)
return self

def __get__(self, obj, cls):
if obj is None:
return self

now = time()
obj_dict = obj.__dict__
name = self.__name__
try:
value, last_updated = obj_dict[name]
except KeyError:
pass
else:
ttl_expired = self.ttl and self.ttl < now - last_updated
if not ttl_expired:
return value

value = self.func(obj)
obj_dict[name] = (value, now)
return value

def __delete__(self, obj):
obj.__dict__.pop(self.__name__, None)

def __set__(self, obj, value):
obj.__dict__[self.__name__] = (value, time())

def _prepare_func(self, func):
self.func = func
if func:
self.__doc__ = func.__doc__
self.__name__ = func.__name__
self.__module__ = func.__module__


# Aliases to make cached_property_with_ttl easier to use
cached_property_ttl = cached_property_with_ttl
timed_cached_property = cached_property_with_ttl


class threaded_cached_property_with_ttl(cached_property_with_ttl):
"""
A cached_property version for use in environments where multiple threads
might concurrently try to access the property.
"""

def __init__(self, ttl=None):
super(threaded_cached_property_with_ttl, self).__init__(ttl)
self.lock = threading.RLock()

def __get__(self, obj, cls):
with self.lock:
return super(threaded_cached_property_with_ttl, self).__get__(obj, cls)


# Alias to make threaded_cached_property_with_ttl easier to use
threaded_cached_property_ttl = threaded_cached_property_with_ttl
timed_threaded_cached_property = threaded_cached_property_with_ttl
2 changes: 1 addition & 1 deletion setup.cfg
Expand Up @@ -14,7 +14,7 @@ parentdir_prefix = arch-

[tool:pytest]
minversion = 3.6
testpaths = linearmodels
testpaths = arch
addopts = --strict
filterwarnings =
ignore:`formatargspec`:DeprecationWarning:statsmodels
Expand Down

0 comments on commit 4a1130e

Please sign in to comment.