Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't print work in a lambda?

People also ask

Why you should never print in Lambda?

Before I let you go, I should warn that the downside to replacing print statements with proper logging is that you lose any terminal output generated from local executions of your Lambda.

How can I access the output of print statements from Lambda?

Navigate to the monitoring tab of your lambda function and click the “view logs in CloudWatch” button. You should now be inside CloudWatch viewing your log output.

Where does Lambda print to?

If your AWS Lambda function uses Python, then any print() statement will be sent to the logs. The logs are displayed when a function is manually run in the console. Also, logs are sent the Amazon CloudWatch Logs for later reference.

Can Lambda return a value?

The lambda function can take many arguments but can return only one expression.


A lambda's body has to be a single expression. In Python 2.x, print is a statement. However, in Python 3, print is a function (and a function application is an expression, so it will work in a lambda). You can (and should, for forward compatibility :) use the back-ported print function if you are using the latest Python 2.x:

In [1324]: from __future__ import print_function

In [1325]: f = lambda x: print(x)

In [1326]: f("HI")
HI

In cases where I am using this for simple stubbing out I use this:

fn = lambda x: sys.stdout.write(str(x) + "\n")

which works perfectly.


what you've written is equivalent to

def anon():
    return print "x"

which also results in a SyntaxError, python doesn't let you assign a value to print in 2.xx; in python3 you could say

lambda: print('hi')

and it would work because they've changed print to be a function instead of a statement.


The body of a lambda has to be an expression that returns a value. print, being a statement, doesn't return anything, not even None. Similarly, you can't assign the result of print to a variable:

>>> x = print "hello"
  File "<stdin>", line 1
    x = print "hello"
            ^
SyntaxError: invalid syntax

You also can't put a variable assignment in a lambda, since assignments are statements:

>>> lambda y: (x = y)
  File "<stdin>", line 1
    lambda y: (x = y)
                 ^
SyntaxError: invalid syntax

You can do something like this.

Create a function to transform print statement into a function:

def printf(text):
   print text

And print it:

lambda: printf("Testing")