syntactic sugar for def?

Chris Kaynor ckaynor at zindagigames.com
Wed Sep 28 17:51:00 EDT 2011


On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle <arnodel at gmail.com> wrote:
> On 28 September 2011 22:26, 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.
>>
>> Any clues for me?  Heck, I'll even be grateful for outright answers!
>
> It's not really sugar.  But I think you mean something like this:
>
>
>>>> class A: pass
> ...
>>>> type(A)
> <class 'type'>
>>>> type is type(A)
> True
>
> So the closest you get for functions will be:
>
>>>> def f(): pass
> ...
>>>> type(f)
> <class 'function'>
>
> Try help(type(f)) to see how to use it to create a function object.
> The problem is that you need to provide a code object, and the easiest
> way to create a code object is to use a def statement :)

I would say compile isn't too much harder to use:
>>> c = compile('a = 123', 'test', 'exec')
>>> d = {}
>>> f = types.FunctionType(c, d, 'test')
>>> f()
>>> print d
{'a': 123}

Although it appears you get all of the variables defined as global
apparently (try "f = types.FunctionType(c, globals(), 'test')"
instead).

>
> HTH
>
> --
> Arnaud
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list