Reputation:
I am trying to use lambda for a usecase, but it seems not working. The following is what I tried
The below is what I used, in stackflow I came across many people getting output for this, but for me its None
from __future__ import print_function
f = lambda x: print(x)
f()
f("Hello") ### now out put is shown expected is Hello output
f("Hello") is None ## I checked if its None and it is
>>> True
l = lambda x : sys.stdout.write(x)
l('hello') # this time its showing output as 5 instead of printing hello
>>> 5
I even tried something which is not using lambda, unfourtunately that too not working, and got None
from functools import partial
spam = partial(print, 'Hello!')
spam()
spam() is None
>>> True
I got this from the last answer in this question assigning print function to variable
Can anyone help me what I am missing and why I am not able to print the string?
Upvotes: 3
Views: 370
Reputation: 42040
l = lambda x : sys.stdout.write(x)
l('hello') # this time its showing output as 5 instead of printing hello
>>> 5
it's probably because the write is not flushed, you can force this by manually calling
sys.stdout.flush()
As for why it's returns hello5
is because the Python shell prints out the return value of the previous statement, sys.stdout.write()
returns the count of the written characters which in case of 'hello' is 5. thus they become concatenated into hello5
. If you ran this in a normal Python file i.e python filename.py
it would never print the 5
and only hello
.
Upvotes: 2
Reputation: 5958
What's not expected? that f('Hello') is None
evaluate to True
? Well that's expected because it is None
.
lambda x: print(x)
has no 'return', only a side effect, and the side effect is to print stuff to the output. This is similar to a function
def func(x):
print(x)
which has no return statement, hence, if you evaluate the function, it's output will be None
.
Upvotes: 2