syntactic sugar for def?

Eric Snow ericsnowcurrently at
Wed Sep 28 18:38:26 EDT 2011

On Wed, Sep 28, 2011 at 3:26 PM, Ethan Furman <ethan at> wrote:
> I remember that 'class' is sugar for type(....).
> I don't remember if 'def' is sugar for something besides lambda.

This is something I have thought about a lot since PyCon this year.  I
apologize in advance.  <wink>

Since 3.0, class statements are syntactic sugar for some extra steps
beyond "meta(...)" [1].  In CPython this is facilitated through the
"hidden" __build_class__() builtin[2].  We have the __import__()
builtin for customizing module creation. But, as you asked, what about

Currently there isn't a way to customize function creation.  There is
no __build_function__() builtin.  The best you can do is, like others
have said, directly call FunctionType(...) or type(f)(...) where f is
an existing function.

I expect that if there were a __build_function__, it would wrap the
code that is currently run for the MAKE_FUNCTION/MAKE_CLOSURE

Also, both modules and classes have mechanisms built-in to allow for
customization in certain parts of the creation process (PEP 302[4] and
metaclasses[5], respectively).  Functions lack this as well, though
there hasn't been a big clamor for it.  :)  Nick Coghlan proposed an
interesting idea for this in March[6], with some later follow-up[7].
Nothing much came of it though.

Definitely an interesting topic, which has led me to learn a lot about
Python and CPython.



> Any clues for me?  Heck, I'll even be grateful for outright answers!
> ~Ethan~
> --

More information about the Python-list mailing list