chrise
chrise

Reputation: 4253

print arguments on function invocation

Wondering what the easiest way is to get debug prints.

I am looking though some code and there is some functions that use a lot of generic text arguments as inputs. So I am looking for an easy way to print the line without having to modify it to avoid getting typos or errors in there

simple example, a line in the code

someFunction('%s_someString', variable, 
   '%s_moreStrings' %someOtherString, someMoreString, someObject)

So instead of checking

print 'someFunction('%s_someString', %s, '%s_moreStrings', 'someObject')  %
               (someOtherString, variable, someMoreString)

I am looking for a way to just print exactly that. I tried to do something like writing a function that would print a string and eval it, but this does not work the way I intend

someFunction('someOtherString_someString', variable,  
             'someMoreString_moreStrings', someObject)

Is there a way to do that

Upvotes: 0

Views: 130

Answers (2)

6160
6160

Reputation: 1002

Have you tried using decorators?

def DebugDecorator(func)

    def log(*args, **kw):
        print "{0}({1}".format(func.__name__, *args)
        return func(*args, **kw)


@DebugDecorator
def someFunction():
    code

edit: i was too slow :)

Upvotes: 1

Eric
Eric

Reputation: 97571

Here's a simple implementation:

from functools import wraps

def prints_invocation(f):
    @wraps(f)
    def wrapped(*args):
        print "%s(%s)" % (f.__name__, ', '.join(repr(a) for a in args))
        return f(*args)
    return wrapped
>>> @prints_invocation
... def add(x, y):
...     return x + y
>>> add(1, 2)
add(1, 2)
3

It would be fairly trivial to extend this to print kwargs and return values

Upvotes: 4

Related Questions