Is it possible in python to write a lambda function that does not need any parameters passed to it? For instance, is there a way to translate this function:
def file_opener():
f = open('filename.txt').read()
return f
or any other function with no passed input into a lambda expression?
You certainly can do it..
x = lambda : 6
print(x()) # prints -> 6
You probably shouldn't though. Once you feel the need to bind a function to a variable name you should go the long road instead (def ..
) as you do it in your example.
Try this (Recommended as no hard-coding is present):
file = lambda f: open(f).read()
print (file('open.txt'))
If you don't want to pass filename as an argument then use this:
f = lambda: open('open.txt').read()
print (f())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With