[Python-3000] 'defop' syntax with no new keywords

Steven Bethard steven.bethard at gmail.com
Fri Dec 8 19:11:09 CET 2006

On 12/8/06, Talin <talin at acm.org> wrote:
> Another mini-brainstorm, which is how to represent PJE's 'defop' syntax
> without adding any keywords:
> Alternative 1. Omitting the function name in 'def' statements.
>    @overload(len):
>    def (self):
>       ... compute len( self ) ...
> Alternative 2: Function name in parens:
>    @overload
>    def (len)(self):
>       ...

Why can't we just use the regular ``def`` syntax, with an appropriate
hook in ``type``, so that if you define a ``__len__`` function and
``len`` exists in an enclosing scope ``len.__addmethod__`` is called.
So just like you do now, you'd write::

    def __len__(self):

Here's a proof-of-concept interactive session::

    >>> import __builtin__
    >>> class Type(type):
    ...     def __init__(cls, name, bases, bodydict):
    ...         for name, value in bodydict.items():
    ...             if callable(value):
    ...                 if name.startswith('__') and name.endswith('__'):
    ...                     name = name[2:-2]
    ...                 if name in globals() or hasattr(__builtin__, name):
    ...                     # in the real code, this would actually do the call
    ...                     format = '--> %s.__addmethod__(%s.%s, %s)'
    ...                     tup = name, cls.__name__, value.__name__,
    ...                     print format % tup
    >>> def overloadable_function(self):
    ...     pass
    >>> class C(object):
    ...     __metaclass__ = Type
    ...     def __len__(self):
    ...         return 4
    ...     def overloadable_function(self):
    ...         return 'foo'
    ...     def regular_method(self):
    ...         return 'bar'
    --> overloadable_function.__addmethod__(C.overloadable_function, C)
    --> len.__addmethod__(C.__len__, C)

Note that the hook is in the metaclass so that the class exists when
``__addmethod__`` is called.  The real version might need to be a
little more careful about what it considers a function and how it
looks in the enclosing scope, and we'd have to decide where
``__addmethod__`` gets called for things like ``__add__`` or
``__getitem__``, but hopefully the idea is clear.

I suspect the one small modification you'd want to make to the ``def``
statement then would be to allow dotted names so that you could do
something like::

    ...     def mapping.__getitem__(self):
    ...         return 'foo'

which would then call
``mapping.__getitem__.__addmethod__(C.__getitem__, C)``.  If we went
this route, we could then define a a plain ``__getitem__`` method as
being equivalent to ``mapping.__getitem__`` or maybe

I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
        --- Bucky Katt, Get Fuzzy

More information about the Python-3000 mailing list