Marmstrong
Marmstrong

Reputation: 1786

Print parameters passed to the function

Is there a pythonic way of printing all the parameters that were passed to a function?

I have a function like the one below ...

def modify_setting(self, keyword, method=None, value=None, limit=None, parameter=None):

When I call this function I won't be passing every argument a parameter. All I think of is to verbosely call each argument, like below, but this produces results that I don't want.

print "{} Modified: {}, {}, {}, {}".format(keyword,  method, value, limit, parameter)

Result:

Acquisition Mode Modified: Static, 10, None, None

What I want (or similar):

Acquisition Mode Modified: Static, 10

Upvotes: 0

Views: 1714

Answers (2)

wwii
wwii

Reputation: 23743

You could use a decorator - I imagine decorators are pythonic:

def dump_args(func):
    "This decorator dumps out the arguments passed to a function before calling it"
    argnames = func.func_code.co_varnames[:func.func_code.co_argcount]
    fname = func.func_name

    def echo_func(*args,**kwargs):
        print fname, ":", ', '.join(
            '%s=%r' % entry
            for entry in zip(argnames,args) + kwargs.items())
        return func(*args, **kwargs)

    return echo_func

@dump_args
def f1(a,b,c):
    print a + b + c

>>> f1(1, 2, 3)
f1 : a=1, b=2, c=3
6
>>>

@dump_args
def f2(a, b = None, c = None):
    print '{}/{}/{}'.format(a, b, c)

>>> f2(1, c = 3)
f2 : a=1, c=3
1/None/3
>>>

decorator was found here: https://wiki.python.org/moin/PythonDecoratorLibrary

Upvotes: 1

loopbackbee
loopbackbee

Reputation: 23322

If all your defaults are None, you can simply print the variables that aren't:

print "{} Modified: {}".format(keyword,  method, ", ".join( [str(v) for v in (value, limit, parameter) if not v is None]))

You could structure the code a little better:

vars= (value, limit, parameter)
vars_str= ", ".join( [str(v) for v in vars if not v is None]
print "{} Modified: {}".format(keyword,  method, vars_str)

Upvotes: 1

Related Questions