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

Ben Souchet
  • 1,450
  • 6
  • 20

3 Answers3

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.

Anonymous
  • 11,748
  • 6
  • 35
  • 57
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?

Prune
  • 76,765
  • 14
  • 60
  • 81
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.