Fully dynamic d by opDotExp overloading

bearophile bearophileHUGS at lycos.com
Sat Apr 18 00:05:10 PDT 2009


Andrei Alexandrescu:
> Pascalize!S s;
> s.foo(); // works
> s.Foo(); // works too
> s.fOo(); // yup, works again

I can show something even more extreme :-)

What we are discussing in this thread is named the __getattr__ method in Python:
http://docs.python.org/reference/datamodel.html#object.__getattr__

Note that in Python there's something even more powerful, __getattribute__:
http://docs.python.org/reference/datamodel.html#object.__getattribute__

So I have created this, that I actually use in a large Graph class of mine that has many methods:
http://code.activestate.com/recipes/409000/
Such class can be used from the interactive shell too, to play with graphs in an interactive way, modify them, plot them, etc.
Often you may not remember the name of a method you need, or you may mistype it. In such situation __getattr__ is being called. It collects the class method names, removed the useless ones, and performs a similarity search between the given wrong method name and the strings in that list. Then returns the 4-5 most similar ones, each one followed by their docstring, that shows the function signature and the purpose of the method. So you can usually find the method you were looking for, and use it. This is useful both when using such Graph class from the command line and when you are writing code without an IDE that helps you finding method names.
That Python code of mine becomes doable in D too (using for example my very fast approximate string distance. This is a case where you don't need the list of changes, but just the distance number. So superdan can rest in peace).

Bye,
bearophile



More information about the Digitalmars-d mailing list