4

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?

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Once again, lets not keep writing bad examples for lambda. They are used to write anonymous functions. Once you assign them to a variable, you should have used def.
3

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())

6 Comments

but you are passing an argument here (f).
you can hard-code it but generally when we are opening a file it's not recommended because your path will always change.
Sure but that is what OP explicitly asked for.
@Ev.Kounis Updated the answer to deal with both the conditions. . Thanks :)
Assigning a lambda to a variable completely invalidates the reason for having lambdas in the first place. lambda is used to write anonymous functions. If you want a named function, use def. This may just be a toy example but do we really need another example of improper use of lambda?
|
1

Just try it!

>>> open('filename.txt', 'w').write('this is filename.txt contents')
29
>>> def call_this(fctn):
...     return fctn()
... 
>>> print(call_this(lambda: open('filename.txt').read()))
this is filename.txt contents

It works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.