3

I want to pass a function, f(a=1,b=2) into g and use the 'a' value in g

def f(a,b): pass

def g(f): #print f.a

g(f(1,2)) should result in an output of 1

I looked into the inspect module but can't seem to get hold of f in g

This is as far as my programming knowledge has got me :

def g(f):
  print(list(inspect.signature(f).parameters.keys()))

g(f(1,2)) results in: TypeError: None is not a callable object

3 Answers 3

2

This is not possible. When you call g(f(1,2)), f(1,2) is finished before g runs. The only way this would be possible would be for f to return its arguments.

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

Comments

1

You need to call g appropriately, so the f, as a function, is an argument:

g(f, 1, 2)

Now work that into your function:

def g(f, *args):
  print(list(inspect.signature(f).parameters.keys()))

... and from here, you can iterate through args to make the proper call to f.

Does that get you moving?

1 Comment

yes that helps a lot given i can not access the parameters of f in g directly...thanks
0

You could do something like this:

def f(a, b):
    print(a)
    print(b)

Then define wrapper as:

def wrapper(func, a, b):
    func(a, b)

Or if you want more flexibility use *args:

def wrapper(func, *args):
    func(*args)

That flexibility comes with some risk if the number of arguments don't match. Which means you'll need to take care that all func passed to wrapper have a consistent signature.

You could use **kwargs which would help with the above, then:

def wrapper(func, **kwargs):
    func(**kwargs)

Then calls to wrapper would look like:

wrapper(f, a=1, b=2)

This would allow for more flexibility and signature of func could vary as needed.

You could turn wrapper into a decorator but that's another question.

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.