1

This is more curiosity than practical.

I have a library function that accepts a function and passes in a variable, but I want to also call that function with other arguments.

def libFunc(fn):
  fn("passes in a useless value")

def foo(a, b):
  print(f"i want to call this function using libFunc with args {a}, {b}")

# This works fine
num1, num2 = 5, 10
libFunc(lambda x, a=num1, b=num2 : foo(a, b))

# is there a way to avoid using a lambda function here, maybe using a named function?
# i.e. what is the equivalent named function of the above lambda function
def bar(uselessValue, a, b):
  return foo(a, b)

# my attempt but I'm not sure how to deal with the first argument being unknown
# without using partial functions from libraries
libFunc( bar(uselessValue=???, a=num1, b=num2) )
2
  • 2
    Am I missing something? Why not def bar(uselessValue, a=num1, b=num2): and call it with libFunc(bar)? Lambdas are nothing special, you can always replace them with named functions. Commented Jul 20, 2021 at 6:01
  • @ggorlen ah that works indeed. I was originally trying to reuse a function that was defined before num1 and num2 were defined. With or without the lambda I would have the repeated function definition. Thank you! Commented Jul 20, 2021 at 6:09

1 Answer 1

2

I think ggorlen's answer is the best answer, but if you still want to know how to create a partial function without built-in library to do it, you can try this.

code:

def libFunc(fn):
  fn("passes in a useless value")

def foo(a, b):
  print(f"i want to call this function using libFunc with args {a}, {b}")

def partial(func, *args,**kwargs):
    def wrapper(uselessvalue):
        return func(*args,**kwargs)
    return wrapper

num1, num2 = 5, 10
libFunc(partial(foo,a=num1, b=num2))

result:

i want to call this function using libFunc with args 5, 10
Sign up to request clarification or add additional context in comments.

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.