syntactic sugar for def?
Eric Snow
ericsnowcurrently at gmail.com
Wed Sep 28 18:38:26 EDT 2011
On Wed, Sep 28, 2011 at 3:26 PM, Ethan Furman <ethan at stoneleaf.us> 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
functions?
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
opcodes[3].
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.
-eric
[1] http://www.python.org/dev/peps/pep-3115/
http://mail.python.org/pipermail/python-3000/2007-March/006338.html
[2] http://hg.python.org/cpython/file/default/Python/bltinmodule.c#l35
[3] http://hg.python.org/cpython/file/default/Python/ceval.c#l2680
[4] http://www.python.org/dev/peps/pep-0302/
http://docs.python.org/release/2.3.5/whatsnew/section-pep302.html
http://docs.python.org/dev/reference/simple_stmts.html#the-import-statement
[5] http://docs.python.org/dev/reference/datamodel.html#customizing-class-creation
http://www.python.org/doc/essays/metaclasses/
[6] http://mail.python.org/pipermail/python-ideas/2011-March/009391.html
[7] http://mail.python.org/pipermail/python-ideas/2011-March/009625.html
http://mail.python.org/pipermail/python-ideas/2011-April/009765.html
>
> Any clues for me? Heck, I'll even be grateful for outright answers!
>
> ~Ethan~
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list