def change_directory(path=None):
    """
    Context manager that changes directory and resets it when existing
    
    >>> with change_directory('/tmp'):
    >>>     pass
    """
    if path is not None:
        try:
            oldpwd = getcwd()
            logger.debug('changing directory from %s to %s' % (oldpwd, path))
            chdir(path)
            yield
        finally:
            chdir(oldpwd)
    else:
        yield