Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty Parameter for Python Lambda Function

Tags:

python

lambda

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?

like image 392
Ajax1234 Avatar asked Sep 18 '25 03:09

Ajax1234


2 Answers

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.

like image 76
Ma0 Avatar answered Sep 20 '25 17:09

Ma0


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())
like image 30
Prakhar Verma Avatar answered Sep 20 '25 16:09

Prakhar Verma