0

It is easy to save function into a variable like

pr = print
pr(5)  # 5 

But if this possible to save function with arguments without a call, like

some_var = defer print(5)  # No call! 
some_var()  # 5

I tried to use lambda, but it's lead to syntaxys error `l = lambda 5:

Why I need it? For example to no repeat multiple "if" branches:

example:

def foo()
l1 = lambda: 1
l2 = lambda: 2
if 1:
    func = l1
elif 2:
    func = l2
else:
   func = some_outer_func, some_inner_func  
return func  # To use "func" need additional "if" branches for type and length of a returned value
1

2 Answers 2

1

functools.partial takes a function of many arguments and returns a function with fewer arguments with some of the arguments "saved"

from functools import partial

print_five = partial(print, 5)
print_five()  # 5

It also works with keyword arguments

def foo(a, b=False):
    print(a, b)

bar = partial(foo, b=True)
foo(1)  # 1 False
bar(1)  # 1 True
Sign up to request clarification or add additional context in comments.

2 Comments

Very unfortunately that python does not have special key word for this. Anyway I can't use it with chunks of functions like outer(inner(defered_func)) # need partial for every func
Are you looking to chain function calls?
1

The way with lambda:

pr = lambda: print(5)
pr()

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.