简体   繁体   中英

Can I write a lambda function in python of more than one line, and call other functions?

I'm reading Structure and Interpretation of Computer Programs - famous in the field of computer science.

Encouraged by the functional programming, I tried to code in Python instead of Scheme because I find it easier to use. But then comes the question: I've needed a Lambda function many times, but I can't figure out how to use lambda to write an unnamed function with complicated operation.

Here, I want to write a lambda function with a string variable exp as its only argument and execute the exec(exp) . But I get an Error:

>>> t = lambda exp : exec(exp)
File "<stdin>", line 1
t = lambda exp : exec(exp)
                    ^
SyntaxError: invalid syntax

how does it happen? How to cope with it?

I read my Python guide book and searched Google without finding the answer I want. Does it mean that the lambda function in python is only designed to be syntactic sugar?

You can't use a statement inside lambda body that's why you get that error, lambda only expects expressions.

But in Python 3 exec is a function and works fine there:

>>> t = lambda x: exec(x)
>>> t("print('hello')")
hello

In Python 2 you can use compile() with eval() :

>>> t = lambda x: eval(compile(x, 'None','single'))
>>> strs = "print 'hello'"
>>> t(strs)
hello

help on compile() :

compile(...)
    compile(source, filename, mode[, flags[, dont_inherit]]) -> code object

    Compile the source string (a Python module, statement or expression)
    into a code object that can be executed by the exec statement or eval().
    The filename will be used for run-time error messages.
    The mode must be 'exec' to compile a module, 'single' to compile a
    single (interactive) statement, or 'eval' to compile an expression.
    The flags argument, if present, controls which future statements influence
    the compilation of the code.
    The dont_inherit argument, if non-zero, stops the compilation inheriting
    the effects of any future statements in effect in the code calling
    compile; if absent or zero these statements do influence the compilation,
    in addition to any features explicitly specified.

lambda statements (not functions) can only be one line, and can only consist of an expression. The expression can contain a function call, eg lambda: my_func() . exec , however, is a statement, not a function and as a result cannot be used as part of an expression.

The question of multi-line lambdas has been debated several times within the python community, but the conclusion is that its usually better and lesss error-prone to explicitly define a function if that's what's needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM