Skip to content

Commit

Permalink
Merge 67f456e into 7f5d852
Browse files Browse the repository at this point in the history
  • Loading branch information
Scott Sanderson committed Aug 10, 2017
2 parents 7f5d852 + 67f456e commit 4974489
Show file tree
Hide file tree
Showing 16 changed files with 73 additions and 15 deletions.
3 changes: 1 addition & 2 deletions tests/pipeline/base.py
@@ -1,13 +1,12 @@
"""
Base class for Pipeline API unit tests.
"""
from functools import wraps

import numpy as np
from numpy import arange, prod
from pandas import DataFrame, Timestamp
from six import iteritems

from zipline.utils.compat import wraps
from zipline.pipeline.engine import SimplePipelineEngine
from zipline.pipeline import ExecutionPlan
from zipline.pipeline.term import AssetExists, InputDates
Expand Down
2 changes: 1 addition & 1 deletion zipline/__main__.py
@@ -1,12 +1,12 @@
import errno
import os
from functools import wraps

import click
import logbook
import pandas as pd
from six import text_type

from zipline.utils.compat import wraps
from zipline.data import bundles as bundles_module
from zipline.utils.cli import Date, Timestamp
from zipline.utils.run_algo import _run, load_extensions
Expand Down
3 changes: 1 addition & 2 deletions zipline/assets/asset_db_migrations.py
@@ -1,11 +1,10 @@
from functools import wraps

from alembic.migration import MigrationContext
from alembic.operations import Operations
import sqlalchemy as sa
from toolz.curried import do, operator as op

from zipline.assets.asset_writer import write_version_info
from zipline.utils.compat import wraps
from zipline.errors import AssetDBImpossibleDowngrade
from zipline.utils.preprocess import preprocess
from zipline.utils.sqlite_utils import coerce_string_to_eng
Expand Down
1 change: 1 addition & 0 deletions zipline/pipeline/classifiers/classifier.py
Expand Up @@ -410,6 +410,7 @@ def _compute(self, arrays, dates, assets, mask):
return result.astype(int64_dtype)

def short_repr(self):
"""Short repr to use when rendering Pipeline graphs."""
return type(self).__name__ + '(%d)' % self.params['bins']


Expand Down
1 change: 1 addition & 0 deletions zipline/pipeline/data/dataset.py
Expand Up @@ -215,6 +215,7 @@ def __repr__(self):
)

def short_repr(self):
"""Short repr to use when rendering Pipeline graphs."""
return self.qualname


Expand Down
1 change: 1 addition & 0 deletions zipline/pipeline/expression.py
Expand Up @@ -319,6 +319,7 @@ def __repr__(self):
)

def short_repr(self):
"""Short repr to use when rendering Pipeline graphs."""
return "Expression: {expr}".format(
typename=type(self).__name__,
expr=self._expr,
Expand Down
6 changes: 5 additions & 1 deletion zipline/pipeline/factors/factor.py
@@ -1,14 +1,14 @@
"""
factor.py
"""
from functools import wraps
from operator import attrgetter
from numbers import Number
from math import ceil

from numpy import empty_like, inf, nan, where
from scipy.stats import rankdata

from zipline.utils.compat import wraps
from zipline.errors import BadPercentileBounds, UnknownRankMethod
from zipline.lib.normalize import naive_grouped_rowwise_apply
from zipline.lib.rank import masked_rankdata_2d, rankdata_1d_descending
Expand Down Expand Up @@ -283,6 +283,7 @@ def function_application(func):
if func not in NUMEXPR_MATH_FUNCS:
raise ValueError("Unsupported mathematical function '%s'" % func)

@with_doc(func)
@with_name(func)
def mathfunc(self):
if isinstance(self, NumericalExpression):
Expand Down Expand Up @@ -384,6 +385,8 @@ class Factor(RestrictedDTypeMixin, ComputableTerm):
__truediv__ = clsdict['__div__']
__rtruediv__ = clsdict['__rdiv__']

del clsdict # don't pollute the class namespace with this.

eq = binary_operator('==')

@expect_types(
Expand Down Expand Up @@ -1322,6 +1325,7 @@ def transform_name(self):
return self._transform.__name__

def short_repr(self):
"""Short repr to use when rendering Pipeline graphs."""
return type(self).__name__ + '(%r)' % self.transform_name


Expand Down
2 changes: 2 additions & 0 deletions zipline/pipeline/mixins.py
Expand Up @@ -216,6 +216,7 @@ def _compute(self, windows, dates, assets, mask):
return out

def short_repr(self):
"""Short repr to use when rendering Pipeline graphs."""
return type(self).__name__ + '(%d)' % self.window_length


Expand Down Expand Up @@ -280,6 +281,7 @@ def __repr__(self):
)

def short_repr(self):
"""Short repr to use when rendering Pipeline graphs."""
return self.name

@classmethod
Expand Down
2 changes: 1 addition & 1 deletion zipline/testing/core.py
@@ -1,6 +1,5 @@
from abc import ABCMeta, abstractmethod, abstractproperty
from contextlib import contextmanager
from functools import wraps
import gzip
from inspect import getargspec
from itertools import (
Expand Down Expand Up @@ -28,6 +27,7 @@

from zipline.assets import AssetFinder, AssetDBWriter
from zipline.assets.synthetic import make_simple_equity_info
from zipline.utils.compat import wraps
from zipline.data.data_portal import DataPortal
from zipline.data.loader import get_benchmark_filename, INDEX_MAPPING
from zipline.data.minute_bars import (
Expand Down
3 changes: 1 addition & 2 deletions zipline/utils/api_support.py
Expand Up @@ -13,9 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import wraps

import zipline.api
from zipline.utils.compat import wraps
from zipline.utils.algo_instance import get_algo_instance, set_algo_instance


Expand Down
39 changes: 39 additions & 0 deletions zipline/utils/compat.py
@@ -1,4 +1,5 @@
from six import PY2
import functools
import sys


Expand All @@ -12,6 +13,41 @@
def exc_clear():
sys.exc_clear()

def update_wrapper(wrapper,
wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
"""Backport of Python 3's functools.update_wrapper for __wrapped__.
"""
for attr in assigned:
try:
value = getattr(wrapped, attr)
except AttributeError:
pass
else:
setattr(wrapper, attr, value)
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Issue #17482: set __wrapped__ last so we don't inadvertently copy it
# from the wrapped function when updating __dict__
wrapper.__wrapped__ = wrapped
# Return the wrapper so this can be used as a decorator via partial()
return wrapper

def wraps(wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return functools.partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)

else:
from types import MappingProxyType as mappingproxy

Expand All @@ -20,6 +56,9 @@ def exc_clear():
# clears the exception.
pass

update_wrapper = functools.update_wrapper
wraps = functools.wraps


unicode = type(u'')

Expand Down
2 changes: 1 addition & 1 deletion zipline/utils/deprecate.py
Expand Up @@ -14,7 +14,7 @@
# limitations under the License.

import warnings
from functools import wraps
from zipline.utils.compat import wraps


def deprecated(msg=None, stacklevel=2):
Expand Down
4 changes: 3 additions & 1 deletion zipline/utils/input_validation.py
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from datetime import tzinfo
from functools import partial, wraps
from functools import partial
from operator import attrgetter

from numpy import dtype
Expand All @@ -22,6 +22,7 @@
from toolz import valmap, complement, compose
import toolz.curried.operator as op

from zipline.utils.compat import wraps
from zipline.utils.functional import getattrs
from zipline.utils.preprocess import call, preprocess

Expand Down Expand Up @@ -824,6 +825,7 @@ def __init__(self, *args, **kwargs):
self.messages = kwargs

def __call__(self, func):
@wraps(func)
def assert_keywords_and_call(*args, **kwargs):
for field, message in iteritems(self.messages):
if field in kwargs:
Expand Down
3 changes: 2 additions & 1 deletion zipline/utils/memoize.py
Expand Up @@ -2,13 +2,14 @@
Tools for memoization of function results.
"""
from collections import OrderedDict, Sequence
from functools import wraps
from itertools import compress
from weakref import WeakKeyDictionary, ref

from six.moves._thread import allocate_lock as Lock
from toolz.sandbox import unzip

from zipline.utils.compat import wraps


class lazyval(object):
"""Decorator that marks that an attribute of an instance should not be
Expand Down
3 changes: 2 additions & 1 deletion zipline/utils/preprocess.py
Expand Up @@ -3,13 +3,14 @@
"""
from textwrap import dedent
from types import CodeType
from functools import wraps
from inspect import getargspec
from uuid import uuid4

from toolz.curried.operator import getitem
from six import viewkeys, exec_, PY3

from zipline.utils.compat import wraps


_code_argorder = (
('co_argcount', 'co_kwonlyargcount') if PY3 else ('co_argcount',)
Expand Down
13 changes: 11 additions & 2 deletions zipline/utils/sentinel.py
Expand Up @@ -7,6 +7,16 @@
from textwrap import dedent


class _Sentinel(object):
"""Base class for Sentinel objects.
"""
__slots__ = ('__weakref__',)


def is_sentinel(obj):
return isinstance(obj, _Sentinel)


def sentinel(name, doc=None):
try:
value = sentinel._cache[name] # memoized
Expand All @@ -27,9 +37,8 @@ def sentinel(name, doc=None):
) % (name, value.__doc__, doc))

@object.__new__ # bind a single instance to the name 'Sentinel'
class Sentinel(object):
class Sentinel(_Sentinel):
__doc__ = doc
__slots__ = ('__weakref__',)
__name__ = name

def __new__(cls):
Expand Down

0 comments on commit 4974489

Please sign in to comment.