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
subclassing complex #47984
Comments
The following is quoted from the Python docs (ref/numeric_types): "Note: If the right operand's type is a subclass of the left operand's My issue is that the built-in complex type does not respect this rule class xcomplex( complex ):
def __new__(cls,*args,**kwargs):
return complex.__new__(cls,*args,**kwargs)
def __coerce__(self,other):
t = complex.__coerce__(self,other)
try:
return (self,xcomplex(t[1]))
except TypeError:
return t
def __add__(self,x):
return xcomplex( complex.__add__(self,x) )
def __radd__(self,x):
return xcomplex( complex.__radd__(self,x) ) print type(z + xz) # gives complex when xcomplex is required |
Confirmed in trunk. Here's a copy-n-past'able testcase: class xcomplex( complex ):
def __new__(cls,*args,**kwargs):
return complex.__new__(cls,*args,**kwargs)
def __coerce__(self,other):
t = complex.__coerce__(self,other)
try:
return (self,xcomplex(t[1]))
except TypeError:
return t
def __add__(self,x):
return xcomplex( complex.__add__(self,x) )
def __radd__(self,x):
return xcomplex( complex.__radd__(self,x) )
class xfloat(float):
def __new__(cls,*args,**kwargs):
return float.__new__(cls,*args,**kwargs)
def __coerce__(self,other):
t = float.__coerce__(self,other)
try:
return (self,float(t[1]))
except TypeError:
return t
def __add__(self,x):
return xfloat( float.__add__(self,x) )
def __radd__(self,x):
return xfloat( float.__radd__(self,x) )
z = 1j
xz = xcomplex(1j)
f = 1.0
xf = xfloat(1.0) print type(z + xz) |
I'll take a look. |
So there's a hint about what's happening here at the bottom of the section http://docs.python.org/reference/datamodel.html#id5 of the docs, where it says: """In the current implementation, the built-in numeric types int, long and In the OPs example, when z + xz is evaluated, xz is (successfully) coerced """New-style classes (those derived from object) never invoke the At the level of the C code, the practical difference between complex and |
I think this issue comes down to a doc fix, though I've opened bpo-5211 Here's a doc patch. |
While Mark Dickinson's patch fixes the documentation, it does not offer |
[gumtree]
Please see bpo-5211 for further discussion. |
Applied doc patch in r69573. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: