Timur Izhbulatov — Independent Electronic Music

Using inline types for mocking objects

Fri, 22 Apr 2011 01:00:00 in Tech stuff | permalink

python

A code snippet from my recent work:

def run_cmd(cmd, pipe=True, dry_run=False):
    log.debug('%r', cmd)
    def mock_child():
        return type('dummy_child', (), dict(wait=lambda x: None))()
    if dry_run:
        return mock_child() 
    stdout = subprocess.PIPE if pipe else None
    try:
        child = subprocess.Popen(cmd, stdout=stdout, shell=True)
    except Exception:
        log.exception(cmd + ':')
        return mock_child()                                                                                                                
    return child

Mock object is only used locally in run_cmd(), so why pollute module namespace with unnecessary extra class? Client code uses only one method, wait(), so the implementation is short.