[Python-il] Silly Python riddle

Ram Rachum ram at rachum.com
Sat Dec 17 18:27:38 IST 2011

On Sat, Dec 17, 2011 at 6:14 PM, Shai Berger <shai at platonix.com> wrote:
>  >
> > (Note that these are the only commands that I ran. You're not allowed to
> > run any other commands before them.)
> >
> > The riddle: What's the shortest thing you can put instead of *???* so my
> > second command would not raise an exception?
> >
> >
> ???= (yield)
> right?
> (mailed privately, to avoid ruining the fun...)

Yep!!! I just almost finished writing the email to tell everyone that when
I got your answer.

Congrats for solving the riddle Shai.

So as Shai said, the solution is:

> **>>> f = lambda: g(*(yield)*)
> >>> f()

Funny, isn't it? I was surprised to see that the `yield` keyword can be
used in a lambda function.

So when you type `f()`, it just returns a generator. If you'll try to
exhaust it, an exception will be raised because `g` doesn't exist, but
that's a new line :)

It's funny that in this case, Python seems to throw away the value of the
lambda function! As we know, the `yield` keyword actually forms a statement
whose value is `None`, unless you used the generator's `.send` instead of
`.next`. So you could also use `.send` to send in whatever value you want
into the lambda function, and Python will just throw it away. Unless I'm
missing something.

So that's the only case I can think of where Python completely throws away
the value of a lambda function.

Another funny thing that I learned from this riddle is that when you do a
function invocation in Python, Python accesses the function *before* it
looks at the arguments.

So if were to do:

adfgadgof(1 / 0)

Python will complain about the non-existent function before it even sees
the division-by-zero.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://hamakor.org.il/pipermail/python-il/attachments/20111217/a26b4ec7/attachment.htm>

More information about the Python-il mailing list