Skip to content

ENH: Support ExtensionArray operators via a mixin #21261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Jun 29, 2018
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Other Enhancements
^^^^^^^^^^^^^^^^^^
- :func:`to_datetime` now supports the ``%Z`` and ``%z`` directive when passed into ``format`` (:issue:`13486`)
- :func:`to_csv` now supports ``compression`` keyword when a file handle is passed. (:issue:`21227`)
- ``ExtensionArray`` has a ``ExtensionOpsMixin`` factory that allows default operators to be defined (:issue:`20659`, :issue:`19577`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make a separate sub-section. pls expand this a bit, I know what you mean, but I doubt the average reader does.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the note here still accurate or has the factory been changed to just mixins?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've written a section for whatsnew

-

.. _whatsnew_0240.api_breaking:
Expand Down
5 changes: 4 additions & 1 deletion pandas/api/extensions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@
register_index_accessor,
register_series_accessor)
from pandas.core.algorithms import take # noqa
from pandas.core.arrays.base import ExtensionArray # noqa
from pandas.core.arrays.base import (ExtensionArray, # noqa
ExtensionArithmeticMixin,
ExtensionComparisonMixin,
ExtensionOpsBase)
from pandas.core.dtypes.dtypes import ExtensionDtype # noqa
5 changes: 4 additions & 1 deletion pandas/core/arrays/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
from .base import ExtensionArray # noqa
from .base import (ExtensionArray, # noqa
ExtensionArithmeticMixin,
ExtensionComparisonMixin,
ExtensionOpsBase)
from .categorical import Categorical # noqa
126 changes: 126 additions & 0 deletions pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,16 @@
"""
import numpy as np

import operator

from pandas.errors import AbstractMethodError
from pandas.compat.numpy import function as nv
from pandas.compat import set_function_name, PY3
import pandas.core.common as com
from pandas.core.dtypes.common import (
is_extension_array_dtype,
is_list_like)
from pandas.core import ops

_not_implemented_message = "{} does not implement {}."

Expand Down Expand Up @@ -610,3 +618,121 @@ def _ndarray_values(self):
used for interacting with our indexers.
"""
return np.array(self)


class ExtensionOpsBase(object):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should not contain a scalar based implemetation, if you really want to add that make it a separate MixIin (inherit from object)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note this is currently not a "base" class as what you have in mind, so it might be you just find the naming wrong?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it IS a Base class for the arithemetic / comparison ops. This is the wrong place to put this logic. This needs to return NotImplementeError. as I have said multiple times.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback see my comment #21261 (comment) . The class ExtensionOpsBase (and I'm open to new names) is not meant to be used directly as a parent class. So why would it need to return NotImplementedError? In fact, if someone just puts ExtensionOpsBase as a parent, it will do nothing beyond defining create_method().

"""
A base class for the mixins for different operators.
Can also be used to define an individual method for a specific
operator using the class method create_method()
"""
@classmethod
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blank line above this for PEP8?

Copy link
Contributor Author

@Dr-Irv Dr-Irv Jun 1, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It passed the PEP8 tests....... But I will add it in.

def create_method(cls, op):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you make this a private method? (_create_method)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jorisvandenbossche See my reply here #21261 (comment) as to why I think it should not be private.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's fine to have it private for users (and I think that is better, as a end-user should never have to use this), but have it documented for extension array authors. We have other methods like that on the ExtensionArray class as well, like _from_sequence.
We just need to clearly document it

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jorisvandenbossche OK, that makes sense. I'll make that change.

"""
A class method that returns a method that will correspond to an
operator for an ExtensionArray subclass.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mention that is to dispatch to the relevant operator defined on the scalars

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


Parameters
----------
op: An operator that takes arguments op(a, b)

Returns
-------
A method that can be bound to a method of a class

Usage
-----
Given an ExtensionArray subclass called MyClass, use

mymethod = create_method(my_operator)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would give here an actual example (eg __add__ = ExtensionOpsBase._create_method(operators.add))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

in the class definition of MyClass to create the operator

"""
op_name = ops._get_op_name(op, False)

def _binop(self, other):
def convert_values(parm):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor detail, but I find 'values' (or 'param') is clearer than 'parm'

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed

if isinstance(parm, ExtensionArray):
ovalues = list(parm)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is it needed to convert to a list? ExtensionArrays support iterating through them (which returns the scalars)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

elif is_extension_array_dtype(parm):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A Series is also 'list-like', so I think this elif will not be reached.
But given that you simply iterate through it (which will be the same for series or extensionarray), I think you can simply remove that part.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

ovalues = parm.values
elif is_list_like(parm):
ovalues = parm
else: # Assume its an object
ovalues = [parm] * len(self)
return ovalues
lvalues = convert_values(self)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should not be needed as the calling object will always be already an ExtensionArray?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Fixed

rvalues = convert_values(other)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably do alignment as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't need to, for a few reasons:

  • The _binop method from here is a method on ExtensionArray (i.e., isinstance(self, ExtensionArray) == True
  • This method is called by dispatch_to_extension_ops in ops.py, which is called after alignment has already been done in _arith_method_SERIES and alignment is ensured in _comp_method_SERIES

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, OK, this is also tested?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jorisvandenbossche Yes, this is tested because I am using the same tests that are used for general operators on Series, which tests things that are misaligned, etc.

See pandas/tests/extension/tests/decimal/test_decimal.py that leverages the TestSeriesOperators.test_operators method from pandas\tests\series\test_operators .

As an aside, doing it this way uncovered the issues with .get and .combine that I submitted.


try:
res = [op(a, b) for (a, b) in zip(lvalues, rvalues)]
except TypeError:
msg = ("ExtensionDtype invalid operation " +
"{opn} between {one} and {two}")
raise TypeError(msg.format(opn=op_name,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally I would not care catching the error.
Eg for the decimal test case:

In [8]: import decimal

In [9]: d = decimal.Decimal('1.1')

In [10]: d + 'a'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-c0db2fc01a1f> in <module>()
----> 1 d + 'a'

TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'str'

which is already a nice error (and IMO even clearer, because it does not contain references to "Extension" which normal users don't necessarily are familiar with)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Fixed.

one=type(lvalues),
two=type(rvalues)))

res_values = com._values_from_object(res)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this does anything for a list (it just passes it through), so this can be removed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I removed it and things still work. Had copied this from elsewhere.


try:
res_values = self._from_sequence(res_values)
except TypeError:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would it makes sense to have a separate _make_comparision_op and _make_aithmetics_op ?
The the comparison one should not need to try the conversion to ExtensionArray (if you want this to happen like in your case, you can still use the arithmetic one to add the comparison ops manually on your class)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see your point. But if someone else had the same use case as me, where the comparison ops need to return an object rather than a boolean, then they'd have to know the workaround you suggest, and so then the question is whether we document it.

I'm leaving this as is for now, but will accept if you really want me to change it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One reason to split it up would be to avoid the extra overhead to try to convert it to an ExtensionArray in case of the boolean ops (although for a good implementation this probably should not be too much overhead ..)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I've done the split for the next commit. I added a parameter to create_method() to specify whether to try the coercion to the underlying dtype, and said to not do it for the comparison operators.

pass

return res_values

name = '__{name}__'.format(name=op_name)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are you defining create_method as anything other than NotImplementedError

this is way too opionated - if u want to define a function to do this and an author can use this ok
but it should not be the default

maybe if u want to create an ExtensionOpsMixinForScalars (long name though)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please take a closer look at the diff if you give such an opinionated (pun intended :-)) comment

  • this is not the default, it's an optional mixin extension authors can reuse (so what you suggest?)
  • so it is exactly the point to be opinionated and fallback to the scalars (we might try to think of a better name that reflects this, as you suggested)
  • it is what we discussed in the other PR

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jorisvandenbossche maybe I wasn't clear.

ExtensionOpsBase should simply have NotImplementedError for the actual implementation of the arithmethic and comaprison ops. Scalar implementations of this will IMHO rarely be used and simply cluttering things up. This can be put as a separate MixIn class if you wish for inclusion by an author, including it here is forcing a pretty bad idiom: coupling the interface and implementation, and is quite error prone because its not opt in. If an author extends and adds ops, they immediate get an implementation, which could very easiy be buggy / not work / work in unexpected ways.

I think the ops implementation is so important that this must be an explicit choice.

The point of the mixin is to avoid the boilerplate of writing __div__ - .... and so on. NOT the implementation.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be put as a separate MixIn class if you wish for inclusion by an author,

Again, this is what this PR is doing.
To repeat from above, is might be it is just the name of ExtensionOpsBase which is not clear? (with which I agree)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback @jorisvandenbossche Maybe the naming is misleading. So let me clarify the intent of the PR.

The goal here is that if someone extends ExtensionArray (let's call it MyArray for sake of discussion) where they are storing objects (let's call them MyClass) that already have the arithmetic and/or comparison operators defined for the class MyClass, they can use these mixins to get those operators defined on the MyArray subclass by simply adding the mixin as one of the base classes of MyArray.

An example is Decimal. The operators are defined there, so the mixin gives you the operators on DecimalArray "for free". I also have my own application that extends ExtensionArray and it uses the same principal.

The use of these 3 classes (ExtensionOpsBase, ExtensionArithmeticMixin and ExtensionComparisonMixin) is optional for people who are writing their own subclass of ExtensionArray. The ExtensionOpsBase class is just a base class for the 2 mixin classes. It contains the create_method() method that allows one to create an individual operator, under the assumption that MyClass has the operator defined. Aside from the use of the two mixin classes that define all of the operators, ExtensionOpsBase.createmethod() can be used to define individual methods. So, for example, if the MyClass class only supports addition, you can choose to not use the mixin, and just do something like the following in MyArray to create the operator.

    __add__ = ExtensionOpsBase.create_method(operator.add)

IMHO, it seems that @jorisvandenbossche understands what I'm trying to do, but @jreback may not fully understand it.

If you think there is a better name for ExtensionOpsBase, I'm open to suggestions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jorisvandenbossche I've tried a variety of implementations without the base class, and couldn't get it to work. I'll rename as you suggest.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

renaming looks ok to me

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Next commit will use the renaming

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the naming conventions. Maybe the NotImplemented versions of the methods belong on the base ExtensionArray?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jbrockmendel The NotImplemented versions are there by default for any class, so I don't think we need to do anything. In other words, if you write a class MyClass that extends ExtensionArray and you don't define the methods for operators, they are by default NotImplemented.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can also pass True to _get_op_name, and then that function does this formatting for you

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed

return set_function_name(_binop, name, cls)


class ExtensionArithmeticMixin(ExtensionOpsBase):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inherit from object

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You will need to be clearer what your objection is. In the way @Dr-Irv implemented it, he needs to subclass the other class, to have the create_method implementation. If you don't like the way how it is currently split in three classes, be specific about that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same point as above create_method needs to return NotImplementedError in this class, hence you don't need a base class. I am being pedantic on purpose here. What you are doing is coupling way to tight the scalar implementation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jreback can't inherit from object, as the set_function_name call in create_method() needs to know the parent class. (or maybe you know some other way to do this)

I don't see the point that create_method needs to return NotImplementedError, as the whole point of what I'm doing here is to just provide the capability to have the operators on ExtensionArray use the underlying operators of the elements on the array.

"""A mixin for defining the arithmetic operations on an ExtensionArray
class, where it assumed that the underlying objects have the operators
already defined.

Usage
------
If you have defined a subclass MyClass(ExtensionArray), then
use MyClass(ExtensionArray, ExtensionArithmeticMixin) to
get the arithmetic operators
"""

__add__ = ExtensionOpsBase.create_method(operator.add)
__radd__ = ExtensionOpsBase.create_method(ops.radd)
__sub__ = ExtensionOpsBase.create_method(operator.sub)
__rsub__ = ExtensionOpsBase.create_method(ops.rsub)
__mul__ = ExtensionOpsBase.create_method(operator.mul)
__rmul__ = ExtensionOpsBase.create_method(ops.rmul)
__pow__ = ExtensionOpsBase.create_method(operator.pow)
__rpow__ = ExtensionOpsBase.create_method(ops.rpow)
__mod__ = ExtensionOpsBase.create_method(operator.mod)
__rmod__ = ExtensionOpsBase.create_method(ops.rmod)
__floordiv__ = ExtensionOpsBase.create_method(operator.floordiv)
__rfloordiv__ = ExtensionOpsBase.create_method(ops.rfloordiv)
__truediv__ = ExtensionOpsBase.create_method(operator.truediv)
__rtruediv__ = ExtensionOpsBase.create_method(ops.rtruediv)
if not PY3:
__div__ = ExtensionOpsBase.create_method(operator.div)
__rdiv__ = ExtensionOpsBase.create_method(ops.rdiv)

__divmod__ = ExtensionOpsBase.create_method(divmod)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rdivmod is a thing

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed.



class ExtensionComparisonMixin(ExtensionOpsBase):
"""A mixin for defining the comparison operations on an ExtensionArray
class, where it assumed that the underlying objects have the operators
already defined.

Usage
------
If you have defined a subclass MyClass(ExtensionArray), then
use MyClass(ExtensionArray, ExtensionComparisonMixin) to
get the arithmetic operators
"""
__eq__ = ExtensionOpsBase.create_method(operator.eq)
__ne__ = ExtensionOpsBase.create_method(operator.ne)
__lt__ = ExtensionOpsBase.create_method(operator.lt)
__gt__ = ExtensionOpsBase.create_method(operator.gt)
__le__ = ExtensionOpsBase.create_method(operator.le)
__ge__ = ExtensionOpsBase.create_method(operator.ge)
10 changes: 7 additions & 3 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2972,16 +2972,20 @@ def get_value(self, series, key):
# use this, e.g. DatetimeIndex
s = getattr(series, '_values', None)
if isinstance(s, (ExtensionArray, Index)) and is_scalar(key):
# GH 20825
# GH 20882, 21257
# Unify Index and ExtensionArray treatment
# First try to convert the key to a location
# If that fails, see if key is an integer, and
# If that fails, raise a KeyError if an integer
# index, otherwise, see if key is an integer, and
# try that
try:
iloc = self.get_loc(key)
return s[iloc]
except KeyError:
if is_integer(key):
if (len(self) > 0 and
self.inferred_type in ['integer', 'boolean']):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What makes this necessary? I'm not clear on how it relates to the Mixin classes.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this you can comment on the relevant other PR (#21260)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jbrockmendel the other PR (#21260) was needed to make the tests here work right.

raise
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pls move all non-ops code to another PR

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The same answer as above: this is needed for the test to pass untill the other PRs are merged (to say: it is already moved to separate PRs)

elif is_integer(key):
return s[key]

s = com._values_from_object(series)
Expand Down
27 changes: 27 additions & 0 deletions pandas/core/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
is_bool_dtype,
is_list_like,
is_scalar,
is_extension_array_dtype,
_ensure_object)
from pandas.core.dtypes.cast import (
maybe_upcast_putmask, find_common_type,
Expand Down Expand Up @@ -990,6 +991,26 @@ def _construct_divmod_result(left, result, index, name, dtype):
)


def dispatch_to_extension_op(left, right, op_name):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this be accomplished with:

return dispatch_to_index_op(op, left, right, left.values.__class__)

?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless we require that the ExtensionArray constructor handles objects of itself (and does not copy them), we cannot do the your example code (and currently we don't require this from extension array implementations I think.
It is also don't think it necessarily improves readability of the code by reusing that.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough. Eventually dispatch_to_index_op is intended to give way to an EA-based dispatch.

"""
Assume that left is a Series backed by an ExtensionArray,
apply the operator defined by op_name.
"""

method = getattr(left.values, op_name, None)
if method is not None:
res_values = method(right)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment as before, can we do here op(left, right) instead of getting the method manually ? (similar as what happens in dispatch_to_index_op) ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've made that change. Thanks.

if method is None or res_values is NotImplemented:
msg = "ExtensionArray invalid operation {opn} between {one} and {two}"
raise TypeError(msg.format(opn=op_name,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

given my comment above, this should not be needed (as the ExtensionArray op will raise the appropriate error)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that makes sense. I changed it.

one=type(left.values),
two=type(right)))

res_name = get_op_result_name(left, right)
return left._constructor(res_values, index=left.index,
name=res_name)


def _arith_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
Expand Down Expand Up @@ -1058,6 +1079,9 @@ def wrapper(left, right):
raise TypeError("{typ} cannot perform the operation "
"{op}".format(typ=type(left).__name__, op=str_rep))

elif is_extension_array_dtype(left):
return dispatch_to_extension_op(left, right, op_name)

lvalues = left.values
rvalues = right
if isinstance(rvalues, ABCSeries):
Expand Down Expand Up @@ -1208,6 +1232,9 @@ def wrapper(self, other, axis=None):
return self._constructor(res_values, index=self.index,
name=res_name)

elif is_extension_array_dtype(self):
return dispatch_to_extension_op(self, other, op_name)

elif isinstance(other, ABCSeries):
# By this point we have checked that self._indexed_same(other)
res_values = na_op(self.values, other.values)
Expand Down
27 changes: 18 additions & 9 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -2196,23 +2196,22 @@ def _binop(self, other, func, level=None, fill_value=None):
result.name = None
return result

def combine(self, other, func, fill_value=np.nan):
def combine(self, other, func, fill_value=None):
"""
Perform elementwise binary operation on two Series using given function
with optional fill value when an index is missing from one Series or
the other

Parameters
----------
other : Series or scalar value
func : function
Function that takes two scalars as inputs and return a scalar
fill_value : scalar value

The default specifies to use the appropriate NaN value for
the underlying dtype of the Series
Returns
-------
result : Series

Examples
--------
>>> s1 = Series([1, 2])
Expand All @@ -2221,26 +2220,36 @@ def combine(self, other, func, fill_value=np.nan):
0 0
1 2
dtype: int64

See Also
--------
Series.combine_first : Combine Series values, choosing the calling
Series's values first
"""
self_is_ext = is_extension_array_dtype(self.values)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move all of this (combine stuff) to another PR on top of this one.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if fill_value is None:
fill_value = na_value_for_dtype(self.dtype, False)

if isinstance(other, Series):
new_index = self.index.union(other.index)
new_name = ops.get_op_result_name(self, other)
new_values = np.empty(len(new_index), dtype=self.dtype)
for i, idx in enumerate(new_index):
new_values = []
for idx in new_index:
lv = self.get(idx, fill_value)
rv = other.get(idx, fill_value)
with np.errstate(all='ignore'):
new_values[i] = func(lv, rv)
new_values.append(func(lv, rv))
else:
new_index = self.index
with np.errstate(all='ignore'):
new_values = func(self._values, other)
new_values = [func(lv, other) for lv in self._values]
new_name = self.name

if self_is_ext and not is_categorical_dtype(self.values):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't use shorthands like this

make this simpler, something like

if is_categorical_dtype(...):
    pass
elif is_extension_dtype(...):
   ....

much more readable

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment that in #21183

try:
new_values = self._values._from_sequence(new_values)
except TypeError:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are you catching a TypeError?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is also for the other PR, but: because the result might not necessarily be an ExtensionArray.

This is of course a bit an unclear area of combine, but currently there is no restriction on the function that the dtype needs to be preserved in the result of the function.

pass

return self._constructor(new_values, index=new_index, name=new_name)

def combine_first(self, other):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/extension/base/getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def test_get(self, data):
expected = s.iloc[[0, 1]]
self.assert_series_equal(result, expected)

assert s.get(-1) == s.iloc[-1]
assert s.get(-1) is None
assert s.get(s.index.max() + 1) is None

s = pd.Series(data[:6], index=list('abcdef'))
Expand Down
11 changes: 8 additions & 3 deletions pandas/tests/extension/decimal/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
import numpy as np

import pandas as pd
from pandas.core.arrays import ExtensionArray
from pandas.core.arrays import (ExtensionArray,
ExtensionArithmeticMixin,
ExtensionComparisonMixin)
from pandas.core.dtypes.base import ExtensionDtype


Expand All @@ -24,11 +26,14 @@ def construct_from_string(cls, string):
"'{}'".format(cls, string))


class DecimalArray(ExtensionArray):
class DecimalArray(ExtensionArray, ExtensionArithmeticMixin,
ExtensionComparisonMixin):
dtype = DecimalDtype()

def __init__(self, values):
assert all(isinstance(v, decimal.Decimal) for v in values)
for val in values:
if not isinstance(val, self.dtype.type):
raise TypeError
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

erorr message

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed (and also in pandas/tests/extension/json/array.py)

values = np.asarray(values, dtype=object)

self._data = values
Expand Down
36 changes: 36 additions & 0 deletions pandas/tests/extension/decimal/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@

from pandas.tests.extension import base

from pandas.tests.series.test_operators import TestSeriesOperators
from pandas.util._decorators import cache_readonly

from .array import DecimalDtype, DecimalArray, make_data


Expand Down Expand Up @@ -183,3 +186,36 @@ def test_dataframe_constructor_with_different_dtype_raises():
xpr = "Cannot coerce extension array to dtype 'int64'. "
with tm.assert_raises_regex(ValueError, xpr):
pd.DataFrame({"A": arr}, dtype='int64')


_ts = pd.Series(DecimalArray(make_data()))


class TestOperator(BaseDecimal, TestSeriesOperators):
@cache_readonly
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

never do this. use a fixture

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unavoidable, because I am subclassing the tests.series.tests_operators.TestSeriesOperators class. That class inherits from tests.series.common.TestData, which defines ts as a @cache_readonly property. The method I use for testing (TestSeriesOperators.test_operators()) has references to self.ts, i.e., it doesn't use a fixture, and I can't see how to override that definition so we get a DecimalArray series and reuse all that testing code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Never mind, I redid the tests as you suggested elsewhere

def ts(self):
ts = _ts.copy()
ts.name = 'ts'
return ts

def test_operators(self):
def absfunc(v):
if isinstance(v, pd.Series):
vals = v.values
return pd.Series(vals._from_sequence([abs(i) for i in vals]))
else:
return abs(v)
context = decimal.getcontext()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what the heck is all this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am reusing the tests that are in the class pandas/tests/series/test_operators/TestSeriesOperators. For decimal, the default when dividing by zero is to raise an error, as opposed to in numpy, where inf is returned. So by changing the defaults for Decimal, we get the same behavior as numpy.

There is a related issue with respect to abs(), because the tests in TestSeriesOperators call np.abs(), but that doesn't work for the Decimal class.

divbyzerotrap = context.traps[decimal.DivisionByZero]
invalidoptrap = context.traps[decimal.InvalidOperation]
context.traps[decimal.DivisionByZero] = 0
context.traps[decimal.InvalidOperation] = 0
super(TestOperator, self).test_operators(absfunc)
context.traps[decimal.DivisionByZero] = divbyzerotrap
context.traps[decimal.InvalidOperation] = invalidoptrap

def test_operators_corner(self):
pytest.skip("Cannot add empty Series of float64 to DecimalArray")

def test_divmod(self):
pytest.skip("divmod not appropriate for Decimal type")
Loading