0

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

2
  • To clarify, you want x = 1; y=2; z = f(x, y) to print f(1, 2), and set z? Commented Aug 16, 2013 at 11:08
  • I would already be happy with having it print f(1, 2) Commented Aug 16, 2013 at 11:49

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks Eric, looks like what I was looking for. Will have a look at those wraps
@wraps(f) is not essential for the functionality here - it's just good practice
1

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 :)

1 Comment

thanks le_vine, not familiar with decorators. something new to look into

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.