Remove some long obsolete files...
This commit is contained in:
parent
f62cf61548
commit
1ae297ae8b
|
@ -1,142 +0,0 @@
|
||||||
"""File-like objects that read/write an array buffer.
|
|
||||||
|
|
||||||
This implements (nearly) all stdio methods.
|
|
||||||
|
|
||||||
f = ArrayIO() # ready for writing
|
|
||||||
f = ArrayIO(buf) # ready for reading
|
|
||||||
f.close() # explicitly release resources held
|
|
||||||
flag = f.isatty() # always false
|
|
||||||
pos = f.tell() # get current position
|
|
||||||
f.seek(pos) # set current position
|
|
||||||
f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
|
|
||||||
buf = f.read() # read until EOF
|
|
||||||
buf = f.read(n) # read up to n bytes
|
|
||||||
buf = f.readline() # read until end of line ('\n') or EOF
|
|
||||||
list = f.readlines()# list of f.readline() results until EOF
|
|
||||||
f.write(buf) # write at current position
|
|
||||||
f.writelines(list) # for line in list: f.write(line)
|
|
||||||
f.getvalue() # return whole file's contents as a string
|
|
||||||
|
|
||||||
Notes:
|
|
||||||
- This is very similar to StringIO. StringIO is faster for reading,
|
|
||||||
but ArrayIO is faster for writing.
|
|
||||||
- ArrayIO uses an array object internally, but all its interfaces
|
|
||||||
accept and return strings.
|
|
||||||
- Using a real file is often faster (but less convenient).
|
|
||||||
- fileno() is left unimplemented so that code which uses it triggers
|
|
||||||
an exception early.
|
|
||||||
- Seeking far beyond EOF and then writing will insert real null
|
|
||||||
bytes that occupy space in the buffer.
|
|
||||||
- There's a simple test set (see end of this file).
|
|
||||||
"""
|
|
||||||
|
|
||||||
import string
|
|
||||||
from array import array
|
|
||||||
|
|
||||||
class ArrayIO:
|
|
||||||
def __init__(self, buf = ''):
|
|
||||||
self.buf = array('c', buf)
|
|
||||||
self.pos = 0
|
|
||||||
self.closed = 0
|
|
||||||
self.softspace = 0
|
|
||||||
def close(self):
|
|
||||||
if not self.closed:
|
|
||||||
self.closed = 1
|
|
||||||
del self.buf, self.pos
|
|
||||||
def isatty(self):
|
|
||||||
return 0
|
|
||||||
def seek(self, pos, mode = 0):
|
|
||||||
if mode == 1:
|
|
||||||
pos = pos + self.pos
|
|
||||||
elif mode == 2:
|
|
||||||
pos = pos + len(self.buf)
|
|
||||||
self.pos = max(0, pos)
|
|
||||||
def tell(self):
|
|
||||||
return self.pos
|
|
||||||
def read(self, n = -1):
|
|
||||||
if n < 0:
|
|
||||||
newpos = len(self.buf)
|
|
||||||
else:
|
|
||||||
newpos = min(self.pos+n, len(self.buf))
|
|
||||||
r = self.buf[self.pos:newpos].tostring()
|
|
||||||
self.pos = newpos
|
|
||||||
return r
|
|
||||||
def readline(self):
|
|
||||||
i = string.find(self.buf[self.pos:].tostring(), '\n')
|
|
||||||
if i < 0:
|
|
||||||
newpos = len(self.buf)
|
|
||||||
else:
|
|
||||||
newpos = self.pos+i+1
|
|
||||||
r = self.buf[self.pos:newpos].tostring()
|
|
||||||
self.pos = newpos
|
|
||||||
return r
|
|
||||||
def readlines(self):
|
|
||||||
lines = string.splitfields(self.read(), '\n')
|
|
||||||
if not lines:
|
|
||||||
return lines
|
|
||||||
for i in range(len(lines)-1):
|
|
||||||
lines[i] = lines[i] + '\n'
|
|
||||||
if not lines[-1]:
|
|
||||||
del lines[-1]
|
|
||||||
return lines
|
|
||||||
def write(self, s):
|
|
||||||
if not s: return
|
|
||||||
a = array('c', s)
|
|
||||||
n = self.pos - len(self.buf)
|
|
||||||
if n > 0:
|
|
||||||
self.buf[len(self.buf):] = array('c', '\0')*n
|
|
||||||
newpos = self.pos + len(a)
|
|
||||||
self.buf[self.pos:newpos] = a
|
|
||||||
self.pos = newpos
|
|
||||||
def writelines(self, list):
|
|
||||||
self.write(string.joinfields(list, ''))
|
|
||||||
def flush(self):
|
|
||||||
pass
|
|
||||||
def getvalue(self):
|
|
||||||
return self.buf.tostring()
|
|
||||||
|
|
||||||
|
|
||||||
# A little test suite
|
|
||||||
|
|
||||||
def test():
|
|
||||||
import sys
|
|
||||||
if sys.argv[1:]:
|
|
||||||
file = sys.argv[1]
|
|
||||||
else:
|
|
||||||
file = '/etc/passwd'
|
|
||||||
lines = open(file, 'r').readlines()
|
|
||||||
text = open(file, 'r').read()
|
|
||||||
f = ArrayIO()
|
|
||||||
for line in lines[:-2]:
|
|
||||||
f.write(line)
|
|
||||||
f.writelines(lines[-2:])
|
|
||||||
if f.getvalue() != text:
|
|
||||||
raise RuntimeError, 'write failed'
|
|
||||||
length = f.tell()
|
|
||||||
print 'File length =', length
|
|
||||||
f.seek(len(lines[0]))
|
|
||||||
f.write(lines[1])
|
|
||||||
f.seek(0)
|
|
||||||
print 'First line =', `f.readline()`
|
|
||||||
here = f.tell()
|
|
||||||
line = f.readline()
|
|
||||||
print 'Second line =', `line`
|
|
||||||
f.seek(-len(line), 1)
|
|
||||||
line2 = f.read(len(line))
|
|
||||||
if line != line2:
|
|
||||||
raise RuntimeError, 'bad result after seek back'
|
|
||||||
f.seek(len(line2), 1)
|
|
||||||
list = f.readlines()
|
|
||||||
line = list[-1]
|
|
||||||
f.seek(f.tell() - len(line))
|
|
||||||
line2 = f.read()
|
|
||||||
if line != line2:
|
|
||||||
raise RuntimeError, 'bad result after seek back from EOF'
|
|
||||||
print 'Read', len(list), 'more lines'
|
|
||||||
print 'File length =', f.tell()
|
|
||||||
if f.tell() != length:
|
|
||||||
raise RuntimeError, 'bad length'
|
|
||||||
f.close()
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
test()
|
|
|
@ -1,241 +0,0 @@
|
||||||
"""Object-oriented interface to the parser module.
|
|
||||||
|
|
||||||
This module exports four classes which together provide an interface
|
|
||||||
to the parser module. Together, the three classes represent two ways
|
|
||||||
to create parsed representations of Python source and the two starting
|
|
||||||
data types (source text and tuple representations). Each class
|
|
||||||
provides interfaces which are identical other than the constructors.
|
|
||||||
The constructors are described in detail in the documentation for each
|
|
||||||
class and the remaining, shared portion of the interface is documented
|
|
||||||
below. Briefly, the classes provided are:
|
|
||||||
|
|
||||||
AST
|
|
||||||
Defines the primary interface to the AST objects and supports creation
|
|
||||||
from the tuple representation of the parse tree.
|
|
||||||
|
|
||||||
ExpressionAST
|
|
||||||
Supports creation of expression constructs from source text.
|
|
||||||
|
|
||||||
SuiteAST
|
|
||||||
Supports creation of statement suites from source text.
|
|
||||||
|
|
||||||
FileSuiteAST
|
|
||||||
Convenience subclass of the `SuiteAST' class; loads source text of the
|
|
||||||
suite from an external file.
|
|
||||||
|
|
||||||
Common Methods
|
|
||||||
--------------
|
|
||||||
|
|
||||||
Aside from the constructors, several methods are provided to allow
|
|
||||||
access to the various interpretations of the parse tree and to check
|
|
||||||
conditions of the construct represented by the parse tree.
|
|
||||||
|
|
||||||
ast()
|
|
||||||
Returns the corresponding `parser.ASTType' object.
|
|
||||||
|
|
||||||
code()
|
|
||||||
Returns the compiled code object.
|
|
||||||
|
|
||||||
filename()
|
|
||||||
Returns the name of the associated source file, if known.
|
|
||||||
|
|
||||||
isExpression()
|
|
||||||
Returns true value if parse tree represents an expression, or a false
|
|
||||||
value otherwise.
|
|
||||||
|
|
||||||
isSuite()
|
|
||||||
Returns true value if parse tree represents a suite of statements, or
|
|
||||||
a false value otherwise.
|
|
||||||
|
|
||||||
text()
|
|
||||||
Returns the source text, or None if not available.
|
|
||||||
|
|
||||||
tuple()
|
|
||||||
Returns the tuple representing the parse tree.
|
|
||||||
"""
|
|
||||||
|
|
||||||
__version__ = '$Revision$'
|
|
||||||
__copyright__ = """Copyright (c) 1995, 1996 by Fred L. Drake, Jr.
|
|
||||||
|
|
||||||
This software may be used and distributed freely for any purpose provided
|
|
||||||
that this notice is included unchanged on any and all copies. The author
|
|
||||||
does not warrant or guarantee this software in any way.
|
|
||||||
"""
|
|
||||||
|
|
||||||
class AST:
|
|
||||||
"""Base class for Abstract Syntax Tree objects.
|
|
||||||
|
|
||||||
Creates an Abstract Syntax Tree based on the tuple representation
|
|
||||||
of the parse tree. The parse tree can represent either an
|
|
||||||
expression or a suite; which will be recognized automatically.
|
|
||||||
This base class provides all of the query methods for subclass
|
|
||||||
objects defined in this module.
|
|
||||||
"""
|
|
||||||
import parser # import internally to avoid
|
|
||||||
_p = parser # namespace pollution at the
|
|
||||||
# top level
|
|
||||||
_text = None
|
|
||||||
_code = None
|
|
||||||
_ast = None
|
|
||||||
_type = 'unknown'
|
|
||||||
_tupl = None
|
|
||||||
|
|
||||||
def __init__(self, tuple):
|
|
||||||
"""Create an `AST' instance from a tuple-tree representation.
|
|
||||||
|
|
||||||
tuple
|
|
||||||
The tuple tree to convert.
|
|
||||||
|
|
||||||
The tuple-tree may represent either an expression or a suite; the
|
|
||||||
type will be determined automatically. Line number information may
|
|
||||||
optionally be present for any subset of the terminal tokens.
|
|
||||||
"""
|
|
||||||
if type(tuple) is not type(()):
|
|
||||||
raise TypeError, 'Base AST class requires tuple parameter.'
|
|
||||||
|
|
||||||
self._tupl = tuple
|
|
||||||
self._ast = self._p.tuple2ast(tuple)
|
|
||||||
self._type = (self._p.isexpr(self._ast) and 'expression') or 'suite'
|
|
||||||
|
|
||||||
def list(self, line_info = 0):
|
|
||||||
"""Returns a fresh list representing the parse tree.
|
|
||||||
|
|
||||||
line_info
|
|
||||||
If true, includes line number information for terminal tokens in
|
|
||||||
the output data structure,
|
|
||||||
"""
|
|
||||||
return self._p.ast2list(self._ast, line_info)
|
|
||||||
|
|
||||||
def tuple(self, line_info = 0):
|
|
||||||
"""Returns the tuple representing the parse tree.
|
|
||||||
|
|
||||||
line_info
|
|
||||||
If true, includes line number information for terminal tokens in
|
|
||||||
the output data structure,
|
|
||||||
"""
|
|
||||||
if self._tupl is None:
|
|
||||||
self._tupl = self._p.ast2tuple(self._ast, line_info)
|
|
||||||
return self._tupl
|
|
||||||
|
|
||||||
def code(self):
|
|
||||||
"""Returns the compiled code object.
|
|
||||||
|
|
||||||
The code object returned by this method may be passed to the
|
|
||||||
exec statement if `AST.isSuite()' is true or to the eval()
|
|
||||||
function if `AST.isExpression()' is true. All the usual rules
|
|
||||||
regarding execution of code objects apply.
|
|
||||||
"""
|
|
||||||
if not self._code:
|
|
||||||
self._code = self._p.compileast(self._ast)
|
|
||||||
return self._code
|
|
||||||
|
|
||||||
def ast(self):
|
|
||||||
"""Returns the corresponding `parser.ASTType' object.
|
|
||||||
"""
|
|
||||||
return self._ast
|
|
||||||
|
|
||||||
def filename(self):
|
|
||||||
"""Returns the name of the source file if known, or None.
|
|
||||||
"""
|
|
||||||
return None
|
|
||||||
|
|
||||||
def text(self):
|
|
||||||
"""Returns the source text, or None if not available.
|
|
||||||
|
|
||||||
If the instance is of class `AST', None is returned since no
|
|
||||||
source text is available. If of class `ExpressionAST' or
|
|
||||||
`SuiteAST', the source text passed to the constructor is
|
|
||||||
returned.
|
|
||||||
"""
|
|
||||||
return self._text
|
|
||||||
|
|
||||||
def isSuite(self):
|
|
||||||
"""Determine if `AST' instance represents a suite of statements.
|
|
||||||
"""
|
|
||||||
return self._type == 'suite'
|
|
||||||
|
|
||||||
def isExpression(self):
|
|
||||||
"""Determine if `AST' instance represents an expression.
|
|
||||||
"""
|
|
||||||
return self._type == 'expression'
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class SuiteAST(AST):
|
|
||||||
"""Statement suite parse tree representation.
|
|
||||||
|
|
||||||
This subclass of the `AST' base class represents statement suites
|
|
||||||
parsed from the source text of a Python suite. If the source text
|
|
||||||
does not represent a parsable suite of statements, the appropriate
|
|
||||||
exception is raised by the parser.
|
|
||||||
"""
|
|
||||||
_type = 'suite'
|
|
||||||
|
|
||||||
def __init__(self, text):
|
|
||||||
"""Initialize a `SuiteAST' from source text.
|
|
||||||
|
|
||||||
text
|
|
||||||
Source text to parse.
|
|
||||||
"""
|
|
||||||
if type(text) is not type(''):
|
|
||||||
raise TypeError, 'SuiteAST requires source text parameter.'
|
|
||||||
self._text = text
|
|
||||||
self._ast = self._p.suite(text)
|
|
||||||
|
|
||||||
def isSuite(self):
|
|
||||||
return 1
|
|
||||||
|
|
||||||
def isExpression(self):
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
class FileSuiteAST(SuiteAST):
|
|
||||||
"""Representation of a python source file syntax tree.
|
|
||||||
|
|
||||||
This provides a convenience wrapper around the `SuiteAST' class to
|
|
||||||
load the source text from an external file.
|
|
||||||
"""
|
|
||||||
def __init__(self, fileName):
|
|
||||||
"""Initialize a `SuiteAST' from a source file.
|
|
||||||
|
|
||||||
fileName
|
|
||||||
Name of the external source file.
|
|
||||||
"""
|
|
||||||
self._fileName = fileName
|
|
||||||
SuiteAST.__init__(self, open(fileName).read())
|
|
||||||
|
|
||||||
def filename(self):
|
|
||||||
return self._fileName
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class ExpressionAST(AST):
|
|
||||||
"""Expression parse tree representation.
|
|
||||||
|
|
||||||
This subclass of the `AST' base class represents expression
|
|
||||||
constructs parsed from the source text of a Python expression. If
|
|
||||||
the source text does not represent a parsable expression, the
|
|
||||||
appropriate exception is raised by the Python parser.
|
|
||||||
"""
|
|
||||||
_type = 'expression'
|
|
||||||
|
|
||||||
def __init__(self, text):
|
|
||||||
"""Initialize an expression AST from source text.
|
|
||||||
|
|
||||||
text
|
|
||||||
Source text to parse.
|
|
||||||
"""
|
|
||||||
if type(text) is not type(''):
|
|
||||||
raise TypeError, 'ExpressionAST requires source text parameter.'
|
|
||||||
self._text = text
|
|
||||||
self._ast = self._p.expr(text)
|
|
||||||
|
|
||||||
def isSuite(self):
|
|
||||||
return 0
|
|
||||||
|
|
||||||
def isExpression(self):
|
|
||||||
return 1
|
|
||||||
|
|
||||||
|
|
||||||
#
|
|
||||||
# end of file
|
|
|
@ -1,275 +0,0 @@
|
||||||
# Complex numbers
|
|
||||||
# ---------------
|
|
||||||
|
|
||||||
# This module represents complex numbers as instances of the class Complex.
|
|
||||||
# A Complex instance z has two data attribues, z.re (the real part) and z.im
|
|
||||||
# (the imaginary part). In fact, z.re and z.im can have any value -- all
|
|
||||||
# arithmetic operators work regardless of the type of z.re and z.im (as long
|
|
||||||
# as they support numerical operations).
|
|
||||||
#
|
|
||||||
# The following functions exist (Complex is actually a class):
|
|
||||||
# Complex([re [,im]) -> creates a complex number from a real and an imaginary part
|
|
||||||
# IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes)
|
|
||||||
# Polar([r [,phi [,fullcircle]]]) ->
|
|
||||||
# the complex number z for which r == z.radius() and phi == z.angle(fullcircle)
|
|
||||||
# (r and phi default to 0)
|
|
||||||
#
|
|
||||||
# Complex numbers have the following methods:
|
|
||||||
# z.abs() -> absolute value of z
|
|
||||||
# z.radius() == z.abs()
|
|
||||||
# z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units
|
|
||||||
# z.phi([fullcircle]) == z.angle(fullcircle)
|
|
||||||
#
|
|
||||||
# These standard functions and unary operators accept complex arguments:
|
|
||||||
# abs(z)
|
|
||||||
# -z
|
|
||||||
# +z
|
|
||||||
# not z
|
|
||||||
# repr(z) == `z`
|
|
||||||
# str(z)
|
|
||||||
# hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero
|
|
||||||
# the result equals hash(z.re)
|
|
||||||
# Note that hex(z) and oct(z) are not defined.
|
|
||||||
#
|
|
||||||
# These conversions accept complex arguments only if their imaginary part is zero:
|
|
||||||
# int(z)
|
|
||||||
# long(z)
|
|
||||||
# float(z)
|
|
||||||
#
|
|
||||||
# The following operators accept two complex numbers, or one complex number
|
|
||||||
# and one real number (int, long or float):
|
|
||||||
# z1 + z2
|
|
||||||
# z1 - z2
|
|
||||||
# z1 * z2
|
|
||||||
# z1 / z2
|
|
||||||
# pow(z1, z2)
|
|
||||||
# cmp(z1, z2)
|
|
||||||
# Note that z1 % z2 and divmod(z1, z2) are not defined,
|
|
||||||
# nor are shift and mask operations.
|
|
||||||
#
|
|
||||||
# The standard module math does not support complex numbers.
|
|
||||||
# (I suppose it would be easy to implement a cmath module.)
|
|
||||||
#
|
|
||||||
# Idea:
|
|
||||||
# add a class Polar(r, phi) and mixed-mode arithmetic which
|
|
||||||
# chooses the most appropriate type for the result:
|
|
||||||
# Complex for +,-,cmp
|
|
||||||
# Polar for *,/,pow
|
|
||||||
|
|
||||||
|
|
||||||
import types, math
|
|
||||||
|
|
||||||
if not hasattr(math, 'hypot'):
|
|
||||||
def hypot(x, y):
|
|
||||||
# XXX I know there's a way to compute this without possibly causing
|
|
||||||
# overflow, but I can't remember what it is right now...
|
|
||||||
return math.sqrt(x*x + y*y)
|
|
||||||
math.hypot = hypot
|
|
||||||
|
|
||||||
twopi = math.pi*2.0
|
|
||||||
halfpi = math.pi/2.0
|
|
||||||
|
|
||||||
def IsComplex(obj):
|
|
||||||
return hasattr(obj, 're') and hasattr(obj, 'im')
|
|
||||||
|
|
||||||
def Polar(r = 0, phi = 0, fullcircle = twopi):
|
|
||||||
phi = phi * (twopi / fullcircle)
|
|
||||||
return Complex(math.cos(phi)*r, math.sin(phi)*r)
|
|
||||||
|
|
||||||
class Complex:
|
|
||||||
|
|
||||||
def __init__(self, re=0, im=0):
|
|
||||||
if IsComplex(re):
|
|
||||||
im = im + re.im
|
|
||||||
re = re.re
|
|
||||||
if IsComplex(im):
|
|
||||||
re = re - im.im
|
|
||||||
im = im.re
|
|
||||||
self.re = re
|
|
||||||
self.im = im
|
|
||||||
|
|
||||||
def __setattr__(self, name, value):
|
|
||||||
if hasattr(self, name):
|
|
||||||
raise TypeError, "Complex numbers have set-once attributes"
|
|
||||||
self.__dict__[name] = value
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
if not self.im:
|
|
||||||
return 'Complex(%s)' % `self.re`
|
|
||||||
else:
|
|
||||||
return 'Complex(%s, %s)' % (`self.re`, `self.im`)
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
if not self.im:
|
|
||||||
return `self.re`
|
|
||||||
else:
|
|
||||||
return 'Complex(%s, %s)' % (`self.re`, `self.im`)
|
|
||||||
|
|
||||||
def __coerce__(self, other):
|
|
||||||
if IsComplex(other):
|
|
||||||
return self, other
|
|
||||||
return self, Complex(other) # May fail
|
|
||||||
|
|
||||||
def __cmp__(self, other):
|
|
||||||
return cmp(self.re, other.re) or cmp(self.im, other.im)
|
|
||||||
|
|
||||||
def __hash__(self):
|
|
||||||
if not self.im: return hash(self.re)
|
|
||||||
mod = sys.maxint + 1L
|
|
||||||
return int((hash(self.re) + 2L*hash(self.im) + mod) % (2L*mod) - mod)
|
|
||||||
|
|
||||||
def __neg__(self):
|
|
||||||
return Complex(-self.re, -self.im)
|
|
||||||
|
|
||||||
def __pos__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
def __abs__(self):
|
|
||||||
return math.hypot(self.re, self.im)
|
|
||||||
##return math.sqrt(self.re*self.re + self.im*self.im)
|
|
||||||
|
|
||||||
|
|
||||||
def __int__(self):
|
|
||||||
if self.im:
|
|
||||||
raise ValueError, "can't convert Complex with nonzero im to int"
|
|
||||||
return int(self.re)
|
|
||||||
|
|
||||||
def __long__(self):
|
|
||||||
if self.im:
|
|
||||||
raise ValueError, "can't convert Complex with nonzero im to long"
|
|
||||||
return long(self.re)
|
|
||||||
|
|
||||||
def __float__(self):
|
|
||||||
if self.im:
|
|
||||||
raise ValueError, "can't convert Complex with nonzero im to float"
|
|
||||||
return float(self.re)
|
|
||||||
|
|
||||||
def __nonzero__(self):
|
|
||||||
return not (self.re == self.im == 0)
|
|
||||||
|
|
||||||
abs = radius = __abs__
|
|
||||||
|
|
||||||
def angle(self, fullcircle = twopi):
|
|
||||||
return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi)
|
|
||||||
|
|
||||||
phi = angle
|
|
||||||
|
|
||||||
def __add__(self, other):
|
|
||||||
return Complex(self.re + other.re, self.im + other.im)
|
|
||||||
|
|
||||||
__radd__ = __add__
|
|
||||||
|
|
||||||
def __sub__(self, other):
|
|
||||||
return Complex(self.re - other.re, self.im - other.im)
|
|
||||||
|
|
||||||
def __rsub__(self, other):
|
|
||||||
return Complex(other.re - self.re, other.im - self.im)
|
|
||||||
|
|
||||||
def __mul__(self, other):
|
|
||||||
return Complex(self.re*other.re - self.im*other.im,
|
|
||||||
self.re*other.im + self.im*other.re)
|
|
||||||
|
|
||||||
__rmul__ = __mul__
|
|
||||||
|
|
||||||
def __div__(self, other):
|
|
||||||
# Deviating from the general principle of not forcing re or im
|
|
||||||
# to be floats, we cast to float here, otherwise division
|
|
||||||
# of Complex numbers with integer re and im parts would use
|
|
||||||
# the (truncating) integer division
|
|
||||||
d = float(other.re*other.re + other.im*other.im)
|
|
||||||
if not d: raise ZeroDivisionError, 'Complex division'
|
|
||||||
return Complex((self.re*other.re + self.im*other.im) / d,
|
|
||||||
(self.im*other.re - self.re*other.im) / d)
|
|
||||||
|
|
||||||
def __rdiv__(self, other):
|
|
||||||
return other / self
|
|
||||||
|
|
||||||
def __pow__(self, n, z=None):
|
|
||||||
if z is not None:
|
|
||||||
raise TypeError, 'Complex does not support ternary pow()'
|
|
||||||
if IsComplex(n):
|
|
||||||
if n.im: raise TypeError, 'Complex to the Complex power'
|
|
||||||
n = n.re
|
|
||||||
r = pow(self.abs(), n)
|
|
||||||
phi = n*self.angle()
|
|
||||||
return Complex(math.cos(phi)*r, math.sin(phi)*r)
|
|
||||||
|
|
||||||
def __rpow__(self, base):
|
|
||||||
return pow(base, self)
|
|
||||||
|
|
||||||
|
|
||||||
# Everything below this point is part of the test suite
|
|
||||||
|
|
||||||
def checkop(expr, a, b, value, fuzz = 1e-6):
|
|
||||||
import sys
|
|
||||||
print ' ', a, 'and', b,
|
|
||||||
try:
|
|
||||||
result = eval(expr)
|
|
||||||
except:
|
|
||||||
result = sys.exc_type
|
|
||||||
print '->', result
|
|
||||||
if (type(result) == type('') or type(value) == type('')):
|
|
||||||
ok = result == value
|
|
||||||
else:
|
|
||||||
ok = abs(result - value) <= fuzz
|
|
||||||
if not ok:
|
|
||||||
print '!!\t!!\t!! should be', value, 'diff', abs(result - value)
|
|
||||||
|
|
||||||
|
|
||||||
def test():
|
|
||||||
testsuite = {
|
|
||||||
'a+b': [
|
|
||||||
(1, 10, 11),
|
|
||||||
(1, Complex(0,10), Complex(1,10)),
|
|
||||||
(Complex(0,10), 1, Complex(1,10)),
|
|
||||||
(Complex(0,10), Complex(1), Complex(1,10)),
|
|
||||||
(Complex(1), Complex(0,10), Complex(1,10)),
|
|
||||||
],
|
|
||||||
'a-b': [
|
|
||||||
(1, 10, -9),
|
|
||||||
(1, Complex(0,10), Complex(1,-10)),
|
|
||||||
(Complex(0,10), 1, Complex(-1,10)),
|
|
||||||
(Complex(0,10), Complex(1), Complex(-1,10)),
|
|
||||||
(Complex(1), Complex(0,10), Complex(1,-10)),
|
|
||||||
],
|
|
||||||
'a*b': [
|
|
||||||
(1, 10, 10),
|
|
||||||
(1, Complex(0,10), Complex(0, 10)),
|
|
||||||
(Complex(0,10), 1, Complex(0,10)),
|
|
||||||
(Complex(0,10), Complex(1), Complex(0,10)),
|
|
||||||
(Complex(1), Complex(0,10), Complex(0,10)),
|
|
||||||
],
|
|
||||||
'a/b': [
|
|
||||||
(1., 10, 0.1),
|
|
||||||
(1, Complex(0,10), Complex(0, -0.1)),
|
|
||||||
(Complex(0, 10), 1, Complex(0, 10)),
|
|
||||||
(Complex(0, 10), Complex(1), Complex(0, 10)),
|
|
||||||
(Complex(1), Complex(0,10), Complex(0, -0.1)),
|
|
||||||
],
|
|
||||||
'pow(a,b)': [
|
|
||||||
(1, 10, 1),
|
|
||||||
(1, Complex(0,10), 'TypeError'),
|
|
||||||
(Complex(0,10), 1, Complex(0,10)),
|
|
||||||
(Complex(0,10), Complex(1), Complex(0,10)),
|
|
||||||
(Complex(1), Complex(0,10), 'TypeError'),
|
|
||||||
(2, Complex(4,0), 16),
|
|
||||||
],
|
|
||||||
'cmp(a,b)': [
|
|
||||||
(1, 10, -1),
|
|
||||||
(1, Complex(0,10), 1),
|
|
||||||
(Complex(0,10), 1, -1),
|
|
||||||
(Complex(0,10), Complex(1), -1),
|
|
||||||
(Complex(1), Complex(0,10), 1),
|
|
||||||
],
|
|
||||||
}
|
|
||||||
exprs = testsuite.keys()
|
|
||||||
exprs.sort()
|
|
||||||
for expr in exprs:
|
|
||||||
print expr + ':'
|
|
||||||
t = (expr,)
|
|
||||||
for item in testsuite[expr]:
|
|
||||||
apply(checkop, t+item)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
test()
|
|
|
@ -1,36 +0,0 @@
|
||||||
# THIS IS OBSOLETE -- USE MODULE 'compileall' INSTEAD!
|
|
||||||
|
|
||||||
# Utility module to import all modules in the path, in the hope
|
|
||||||
# that this will update their ".pyc" files.
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
# Sabotage 'gl' and 'stdwin' to prevent windows popping up...
|
|
||||||
for m in 'gl', 'stdwin', 'fl', 'fm':
|
|
||||||
sys.modules[m] = sys
|
|
||||||
|
|
||||||
exceptions = ['importall']
|
|
||||||
|
|
||||||
for dir in sys.path:
|
|
||||||
print 'Listing', dir
|
|
||||||
try:
|
|
||||||
names = os.listdir(dir)
|
|
||||||
except os.error:
|
|
||||||
print 'Can\'t list', dir
|
|
||||||
names = []
|
|
||||||
names.sort()
|
|
||||||
for name in names:
|
|
||||||
head, tail = name[:-3], name[-3:]
|
|
||||||
if tail == '.py' and head not in exceptions:
|
|
||||||
s = 'import ' + head
|
|
||||||
print s
|
|
||||||
try:
|
|
||||||
exec s + '\n'
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
del names[:]
|
|
||||||
print '\n[interrupt]'
|
|
||||||
break
|
|
||||||
except:
|
|
||||||
print 'Sorry:', sys.exc_type + ':',
|
|
||||||
print sys.exc_value
|
|
|
@ -1,2 +0,0 @@
|
||||||
import sys
|
|
||||||
sys.modules['ni'] = sys.modules[__name__]
|
|
Loading…
Reference in New Issue