dynamic classes and duck typing

bearophile bearophileHUGS at lycos.com
Tue Dec 1 11:36:37 PST 2009


I suggest Walter to don't try to say that D2 is "better" than Python, it's a waste of time and it means nothing.

Walter Bright:

>can you do Bill Baxter's swizzler? Can you do Don Clugston's FPU code generator?<

Python is more more flexible. See the __getattr__ standard method:

class Reg4(object):
    ORDER = dict((c,i) for i,c in enumerate("wxyz"))
    def __init__(self, data=None):
        self.data = [None] * 4
        if data:
            for i, item in enumerate(data):
                self.data[i] = item
    def __getattr__(self, attr):
        assert sorted(list(attr)) == ['w', 'x', 'y', 'z']
        self.data[:] = (self.data[Reg4.ORDER[c]] for c in attr)

r = Reg4("ABCD")
print r.data
r.xyzw
print r.data


Output:
['A', 'B', 'C', 'D']
['B', 'C', 'D', 'A']

If you want the r.xyzw() syntax, that too can be done, creating new methods on the fly.

In Python there's also the __getattribute__ that's a little more powerful than __getattr__:
http://pyref.infogami.com/__getattribute__


>That doesn't help if you really need to do a little assembler.<

That Reg4() class can actually use true SSE registers, generating and running very efficient asm computational kernels using corepy:
http://www.corepy.org/

And you can also use GPUs with PyCuda and PyOpenCL in Python:
http://mathema.tician.de/software/pycuda
http://python-opencl.next-touch.com/

With Python + CorePy today you can write heavy numerical code that's faster than all D code.

Bye,
bearophile



More information about the Digitalmars-d mailing list