dman
dman

Reputation: 11073

Python Decorator Object Not Being Available

I get

NameError: global name 'git' is not defined

for git.add(log_filename). I don't understand why since repo = Repo(ABSOLUTE_PATH) and git = repo.git is called before original_function = function(ABSOLUTE_PATH, GIT_WORKING_DIR, log_name, remove_logs). Shouldn't the git object be available to the called function?

I would like to utilize the decorator in this instance, since a separate function will be using similar functionality. How can I make this decorator work?

 def raw_git(function):
    @wraps(function)
    def wrapper(ABSOLUTE_PATH, GIT_WORKING_DIR,
            log_name=None, remove_logs=None):
        try:
            repo = Repo(ABSOLUTE_PATH)
            git = repo.git
        except NoSuchPathError:
            raise Exception("Error in finding local git path!")
        original_function = function(ABSOLUTE_PATH, GIT_WORKING_DIR,
                log_name, remove_logs)
        return original_function
    return wrapper


@raw_git
def git_add_log(ABSOLUTE_PATH, GIT_WORKING_DIR,
        log_name=None, remove_logs=None):
    log_name = GIT_WORKING_DIR + "/" + log_name
    try:
        git.add(log_filename)
        git.commit(message="Removing oldest logs")
        git.push()
    except GitCommandError:
        raise Exception("There was an error with git command "
                "for removing oldest log(s)")

Upvotes: 0

Views: 71

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125058

git is a local name inside the wrapper function. It is not visible outside of that namespace, so not in git_add_log.

Give that function a git argument instead, and pass in the object when you call the wrapped function:

def raw_git(function):
    @wraps(function)
    def wrapper(ABSOLUTE_PATH, GIT_WORKING_DIR,
            log_name=None, remove_logs=None):
        try:
            repo = Repo(ABSOLUTE_PATH)
            git = repo.git
        except NoSuchPathError:
            raise Exception("Error in finding local git path!")
        original_function = function(git, ABSOLUTE_PATH, GIT_WORKING_DIR,
                log_name, remove_logs)
        return original_function
    return wrapper


@raw_git
def git_add_log(git, ABSOLUTE_PATH, GIT_WORKING_DIR,
        log_name=None, remove_logs=None):
    log_name = GIT_WORKING_DIR + "/" + log_name
    try:
        git.add(log_filename)
        git.commit(message="Removing oldest logs")
        git.push()
    except GitCommandError:
        raise Exception("There was an error with git command "
                "for removing oldest log(s)")

Upvotes: 2

Related Questions