0

I am looking to save the input parameters of a function as a string. I am using Python 3.7. I want so save that string for debugging.

What I could do easily would be something like this:

def Model(par1=150, par2=100)

#some processing

return results, par1

parameters = str(par1) + str(par2)

However, I want to be able to automatically save all parameters, even if I add more parameters later. So if I add a par3 = 300 to the function, "parameters" would also contain str(par3), instead of me having to add it manually.

The behavior I would like to have is something like this:

def Model(--any number of parameters--)

#some processing

return results

parameters = --all parameters of Model--

The reason I would like to have it done automatically is that I expect that otherwise it would cause more trouble than it being worse, as I would have to remember to manually change this all the time.

Is it possible to save ALL parameters of a function as a string (or in any other way that lets me easily check later which parameters a function ran with)?

petezurich
  • 9,280
  • 9
  • 43
  • 57

3 Answers3

2

You can try something like this

def foo(param1, param2):
    parameters = list(locals().items())
    print(parameters)
foo(100,200)

# Outputs 
[('param1', 100), ('param2', 200)]
0

Problem solved with

args = locals()

at the beginning of the function

0

If you want to get a bit fancy, you could create a decorator and use it wherever you need it. Here is just a simple one I wrote:

from functools import wraps

def save_params(func):
  @wraps(func)
  def wrapper(*args, **kwargs):
    print ('Calling {}({}{}{})'.format(
      func.__name__,
      ', '.join(map(str, args)),
      ', ' if kwargs else '',
      ', '.join('{}={}'.format(k, v) for k, v in kwargs.items())
    ))
    return func(*args, **kwargs)
  return wrapper

@save_params
def f(a, b, c=3):
  return a + b + c

Now whenever you call f() the arguments will get printed. @save_params could be used for any other methods to keep track of params passed in during debugging. It looks like this:

>>> f(1, 2)
Calling f(1, 2)
6
>>> f(1, 2, c=7)
Calling f(1, 2, c=7)
10
Faboor
  • 1,365
  • 2
  • 10
  • 23