Himmators
Himmators

Reputation: 15006

Pass argument to callback?

I'm working on my first python script. I want to use a variable within a callback-function:

def run(self, edit):
    gitFolder = os.path.basename(gitRoot)
    #Get branch
    self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], self.branchDone)


def branchDone(self, result):
    build =  "./Build-Release.ps1 " + gitFolder + " " + result +" -Deploy;"
    print build

How do I make gitFolder available to the method branchDone?

Upvotes: 2

Views: 132

Answers (4)

Amit Kumar Gupta
Amit Kumar Gupta

Reputation: 18567

If you don't need branchDone except for as a callback, consider defining it as a closure inside run:

from subprocess import check_output

def run_command(command, callback):
    callback(check_output(command).strip())

class Foo(object):
    def run(self, edit):
        gitFolder = "some_magic"
        def branch_done(result):
            print "./Build-Release.ps1 " + gitFolder + " " + result + " -Deploy;"
        run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], branch_done)

Foo().run("edit")

Upvotes: 1

Devesh Saini
Devesh Saini

Reputation: 577

As I am observing, these are class methods, you can define a class attribute to share gitFolder across them.

def run(self, edit):
    self.gitFolder = os.path.basename(gitRoot)
    #Get branch
    self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], self.branchDone)


def branchDone(self, result):
    build =  "./Build-Release.ps1 " + self.gitFolder + " " + result +" -Deploy;"
    print build

Upvotes: 1

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

simply return gitFolder from run and call run in branchcode Try this:-

def run(self, edit):
    gitFolder = os.path.basename(gitRoot)
    #Get branch
    self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], self.branchDone)
    return gitFolder

def branchDone(self, result):
    build =  "./Build-Release.ps1 " + run() + " " + result +" -Deploy;" #run() returns gitfolders
    print build

There is another way

   def run(self, edit):
        self.gitFolder = os.path.basename(gitRoot)
        #Get branch
        self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], self.branchDone)


    def branchDone(self, result):
        build =  "./Build-Release.ps1 " + self.gitFolder + " " + result +" -Deploy;"  

But it carries a problem that you need to execute the run function before executing branchcode, else self.gitfolder will be undefined and raise Attribute error.

Upvotes: 2

bereal
bereal

Reputation: 34272

One way would be using functools.partial:

def run(self, edit):
    gitFolder = os.path.basename(gitRoot)
    #Get branch
    callback = functools.partial(self.branchDone, gitFolder)
    self.run_command(['git', 'rev-parse','--abbrev-ref','HEAD'], callback)

def branchDone(self, gitFolder, result):
    build =  "./Build-Release.ps1 " + gitFolder + " " + result +" -Deploy;"
    print build

Upvotes: 1

Related Questions