[Python-ideas] Another way to avoid clumsy lambdas, while adding new functionality
Steven D'Aprano
steve at pearwood.info
Wed Mar 5 12:43:44 CET 2014
On Tue, Mar 04, 2014 at 10:54:30PM -0800, David Mertz wrote:
> As *I* am thinking of it, a "thunk" is really just like a C macro. Not
> even really like a Lisp macro. So it's not like a function in that it
> doesn't define a scope, doesn't have a call stack, etc. It's just "pretend
> I typed these other literal symbols here." Maybe I should stop calling the
> idea a thunk, and just call it a macro.
I'm intrigued by this suggestion. I think that what I'm really after is
two things: lazy evaluation, and dynamic scoping. I think a macro would
give us both.
But hasn't Guido said No Macros at some point?
> However, I'm pulled in several directions here. On the one hand, if it
> really is essentially the same thing as a code object, I'm not convinced we
> actually need syntax for it. That is, what's really the point of having
>
> a = $(expr) # or `expr`, or `(expr), or c"expr"
>
> If it's simply a slightly shorter way of spelling:
>
> a = compile(expr, "<string>", "eval")
You can't write it like that. You have to wrap the expression is quotes
and turn it into a string:
a = compile("expr", "<string>", "eval")
which means you lose syntax highlighting. Perhaps the ability to get
syntax highlighting is not sufficient to justify this idea.
Another disadvantage: the ever-present temptation to pass a
user-generated string to compile:
a = compile(template % some_string, "<string>", "eval")
If some_string came from an untrusted source, you are now the proud
owner of a brand new code injection vulnerability. But with syntax, you
cannot generate a thunk/macro except from code you write yourself. It's
still code written by you, it's just that evaluation is delayed.
--
Steven
More information about the Python-ideas
mailing list