Error adding two Color objects
Created originally on Bitbucket by ekinoshita (Eric Kinoshita)
TLDR: Color(rgb='FF00FF00') + Color(rgb='FF0000AA')
raises TypeError: expected <type 'long'>
- mokey patch below.
I've been using a lot the style_range
function (as presented on http://openpyxl.readthedocs.io/en/latest/styles.html#styling-merged-cells). And it raises weird TypeError
s coming out of lines like the following:
cell.border = cell.border + top
That exception can be easily reproduced by doing this:
>>> from openpyxl.styles import Border, Side
>>>
>>> Border(top=Side(style='thin', color='FF00FF00')) + Border(top=Side(style='thin', color='FF0000FF'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my_venv/local/lib/python2.7/site-packages/openpyxl/descriptors/serialisable.py", line 208, in __add__
vals[el] = a + b
File "my_venv/local/lib/python2.7/site-packages/openpyxl/descriptors/serialisable.py", line 208, in __add__
vals[el] = a + b
File "my_venv/local/lib/python2.7/site-packages/openpyxl/descriptors/serialisable.py", line 211, in __add__
return self.__class__(**vals)
File "my_venv/local/lib/python2.7/site-packages/openpyxl/styles/colors.py", line 86, in __init__
self.indexed = indexed
File "my_venv/local/lib/python2.7/site-packages/openpyxl/descriptors/base.py", line 69, in __set__
value = _convert(self.expected_type, value)
File "my_venv/local/lib/python2.7/site-packages/openpyxl/descriptors/base.py", line 59, in _convert
raise TypeError('expected ' + str(expected_type))
TypeError: expected <type 'long'>
I did some digging and I found out that the original error happens when it tries to add two colors:
>>> from openpyxl.styles import Color
>>>
>>> Color(rgb='FF00FF00') + Color(rgb='FF0000AA')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my_venv/local/lib/python2.7/site-packages/openpyxl/descriptors/serialisable.py", line 211, in __add__
return self.__class__(**vals)
File "my_venv/local/lib/python2.7/site-packages/openpyxl/styles/colors.py", line 86, in __init__
self.indexed = indexed
File "my_venv/local/lib/python2.7/site-packages/openpyxl/descriptors/base.py", line 69, in __set__
value = _convert(self.expected_type, value)
File "my_venv/local/lib/python2.7/site-packages/openpyxl/descriptors/base.py", line 59, in _convert
raise TypeError('expected ' + str(expected_type))
TypeError: expected <type 'long'>
I found that the Color
class inherits the despcriptors.serializable.Serialisable.__add__
method, and its implementation does not suit to the Color
class. I'm using the following monkey patch and it seems to work fine:
def _new_color_add(self, other):
return other if isinstance(other, Color) else self
Color.__add__ = _new_color_add