tags:

views:

58

answers:

1

Hello,

at the moment my python code often looks like this:

...
if not dry_run:
    result = shutil.copyfile(...)
else:
    print "   DRY-RUN: shutil.copyfile(...) "
...

I now think about writting something like a dry runner method:

def dry_runner(cmd, dry_run, message, before="", after=""):
    if dry_run:
        print before + "DRY-RUN: " + message + after
     # return execute(cmd)

But the cmd will be executed first and the result is given to dry_runner method.

How can I code such a method the pythonic way?

+3  A: 

You could use this generic wrapper function:

def execute(func, *args):
    print 'before', func
    if not dry:
        func(*args)
    print 'after', func

>>> execute(shutil.copyfile, 'src', 'dst')
compie