Unification Idea

Alex Martelli aleaxit at yahoo.com
Thu May 10 07:29:01 EDT 2001


"Raymond Hettinger" <othello at javanet.com> wrote in message
news:3AF9B5BB.505746B4 at javanet.com...
> Complex numbers define: .real, .imag, and .conjugate().
> I think we ought to define them for floats, ints, and longs also.

It WOULD ease polymorphic use of various number types
as if they were complex, yes.  I suspect the usage of
complex numbers may be considered too rare to warrant
adding attributes/methods to numeric types that now
have none.


> arr = [ 2,10L, 5.1, 3+2j ]
> map( lambda z: z.conjugate(), arr )            # This is what I would like
to do
>
> map( lambda z: type(z)==types.ComplexType and z.conjugate() or z, arr )
# vs.
> what I have to do now

I think a better "works now" solution might be:

    def conj(x):
        try: return x.conjugate()
        except AttributeError: return x
    map(conj, arr)

This lets arr contain arbitrary user-types that
implement the .conjugate() method, just like
your "would like to do" case would, rather than
constraining behaviour through a type-test.

If you do this often, you only need write the
simple functions conj(), real() and imag()
once, of course, and you can stick them in
your builtins or whatever... it's _almost_
as good as if they were "real" built-ins:-).


Alex






More information about the Python-list mailing list