As a learning exercise, I'm trying to implement a class which will emulate the behavior of python's complex
builtin, but with different behavior of the __str__
and __repr__
methods: I want them to print in the format...
(1.0,2.0)
...instead of:
(1+2j)
I first tried simply subclassing from complex
and redefining __str__
and __repr__
, but this has the problem that when non-overridden methods are called, a standard complex
is returned, and printed in the standard format:
>>> a = ComplexWrapper(1.0,1.0)
>>> a
(1.0,1.0)
>>> b = ComplexWrapper(2.0,3.0)
>>> b
(2.0,3.0)
>>> a + b
(3+4j)
When the desired output is (3.0,4.0)
.
I was reading about metaclasses and thought they would solve my problem. Starting from the answer in Python Class Decorator, my current implementation is as follows:
def complex_str(z):
return '(' + str(z.real) + ',' + str(z.imag) + ')'
def complex_repr(z):
return '(' + repr(z.real) + ',' + repr(z.imag) + ')'
class CmplxMeta(type):
def __new__(cls, name, bases, attrs):
attrs['__str__'] = complex_str
attrs['__repr__'] = complex_repr
return super(CmplxMeta, cls).__new__(cls, name, bases, attrs)
class ComplexWrapper(complex):
__metaclass__ = CmplxMeta
Unfortunately, this seems to have the same behavior as the previous solution (e.g. when two ComplexWrapper
instances are added to each other).
I admit, I don't fully understand metaclasses. Maybe my problem can be solved in a different way?
Of course, I could manually redefine the relevant methods such as __add__
, __subtract__
, etc. But that would be very repetitive, so I would prefer a more elegant solution.
Any help appreciated.
EDIT: Response to agf's answer:
So a number of things I don't understand about your code:
Where does the
__new__
method of theReturnTypeWrapper
metaclass get its arguments from? If they are passed automatically, I would expect in this case thatname = "Complex", bases = (complex), dict = {}
. Is that correct? Is this method of automatic passing of class data specific to metaclasses?Why do you use
cls = type.__new__(mcs, name, bases, dct)
instead ofcls = type(mcs, name, bases, dct)
? Is it just to avoid confusion with the "other meaning" oftype()
?I copied your code, and added my special implementations of
__str__
and__repr__
in yourComplexWrapper
class. But it doesn't work; printing any object of typeComplex
just prints in the standard Python format. I don't understand that, as the two methods should have been picked up in the for loop of the metaclass, but should have been overridden by my definitions afterward.
The relevant section of my code:
class Complex(complex):
__metaclass__ = ReturnTypeWrapper
wrapped_base = complex
def __str__(self):
return '(' + str(self.real) + ',' + str(self.imag) + ')'
def __repr__(self):
return '(' + repr(self.real) + ',' + repr(self.imag) + ')'
And its behavior:
>>> type(a)
<class 'Cmplx2.Complex'>
>>> a.__str__
<bound method Complex.wrapper of (1+1j)>
>>> a.__str__()
'(1+1j)'
>>>
Thanks again for your answer and feel free to edit/remove the above if you address them in your answer!
Your current approach won't work. How you define your class isn't the issue -- the methods of
complex
are creating new instances ofcomplex
when you call them, rather than using thetype
of the input objects. You'll always get back instances ofcomplex
rather thanComplexWrapper
, so your customized methods won't be called:Instead, you need to convert the new
complex
objects returned by the methods ofcomplex
to return objects of the derived class.This metaclass wraps all the methods of the specified base class and attaches the wrapped methods to the class. The wrapper checks if the value to be returned is an instance of the base class (but excluding instances of subclasses), and if it is, converts it to an instance of the derived class.
Note that this won't wrap the
__coerce__
special method, since it returns atuple
ofcomplex
s; the wrapper can easily be converted to look inside sequences if necessary.The
__objclass__
attribute of unbound methods seems to be undocumented, but it points to the class the method is defined on, so I used it to filter out methods defined on classes other than the one we're converting from. I also use it here to filter out attributes that aren't unbound methods.