pythoninspect

python get parameters of passed function


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


Solution

  • 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?