Skip to content

Instantly share code, notes, and snippets.

@erynofwales
Last active January 1, 2016 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erynofwales/8072857 to your computer and use it in GitHub Desktop.
Save erynofwales/8072857 to your computer and use it in GitHub Desktop.
Python seems to invoke Complex's __init__ with the string '3', but complex's (the Python built-in class) __init__ with the string '3#'
In [3]: number.Complex('3')
> /Users/eryn/Code/sibilant/sibilant/number.py(51)__init__()
-> exact = exact is not None
(Pdb) c
Out[3]: (3+0j)
In [4]: number.Complex('3#')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-4dce8b9d03a9> in <module>()
----> 1 number.Complex('3#')
ValueError: complex() arg is a malformed string
In [5]:
class Number(numbers.Number):
def __init__(self, exact=None):
self.exact = exact
@property
def is_exact(self):
if self.exact is not None:
return self.exact
# TODO: Number is inexact if it contains:
# 1. a decimal point (3.14)
# 2. an exponent (3e5)
# 3. a # in place of a digit (34#)
return False
def _replace_hashes(self, value):
if not isinstance(value, basestring):
# Nothing to do, not a string.
return value
return value.replace('#', '0')
class Complex(Number, complex):
def __init__(self, real, imag=None, exact=None):
exact = exact is not None
import pdb; pdb.set_trace()
real_inexact = self._replace_hashes(real)
exact = (real == real_inexact)
if imag is None:
complex.__init__(self, real_inexact)
else:
imag_inexact = self._replace_hashes(imag)
exact = exact and (imag == imag_inexact)
complex.__init__(self, real_inexact, imag_inexact)
Number.__init__(self, exact)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment