[Python-Dev] Shorthand for lambda

Ka-Ping Yee python-dev at zesty.ca
Wed Mar 23 19:11:55 CET 2005


On Wed, 23 Mar 2005, Josiah Carlson wrote:
> Paul Moore <p.f.moore at gmail.com> wrote:
> > I thought about it, but couldn't convince myself that it would work
> > properly in all cases. I was thinking in terms of operator overloading
> > of everything possible - how did you do it?
>
> PyTables allows something very similar for "in-kernel" searches of data,
> but only on a single constraint.  I would imagine that Ka-Ping did it by
> only allowing a single operation per item.

You can do more than one operation, but the usage is still quite limited.
The item placeholder must be the first operand for it to work.

    >>> numbers = [3, 8, 4, 1, 2]
    >>> filter(_ < 5, numbers)
    [3, 4, 1, 2]
    >>> map(_ * 5 + 7, numbers)
    [10, 15, 11, 8, 9]

I tried implementing __len__, but that doesn't work because Python
enforces a type restriction.

    >>> words = 'lovely spam and eggs'.split()
    >>> filter(len(_) == 4, words)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: __len__() should return an int

__getitem__ and __getattr__ mostly work.  However, in order to call a
method on the placeholder you have to add an underscore to distinguish
it from retrieving an attribute.

    >>> filter(_.endswith_('s'), words)
    ['eggs']

You can check out http://zesty.ca/python for the gory details.

As Jeremy wrote, the proper way to do map and filter is to use a
list comprehension, so these are bad examples.  The original
motivation was to provide a way to write lambda expressions for
cases where you aren't doing map or filter.  For that, it works,
but only in limited cases.

I realize this isn't that practical.  It's mainly for your
amusement -- yet another in a long tradition of hacks that use
operator overloading to hijack the Python parser.  (Also a long
tradition of me doing silly things in public.)


-- ?!ng


More information about the Python-Dev mailing list