Home > Enterprise >  How to pass all local variables to another function?
How to pass all local variables to another function?

Time:05-21

I have two functions: functionA and functionB and I would like to call functionB inside functionA and pass to it all local variables defined in functionA (and in the other way). For example I would like to make the below code works:

def functionA():
    localA = 20
    functionB()
    print(localB)

def functionB():
    print(localA)
    localB=10

functionA()

CodePudding user response:

Pass the local variables of functionA as parameters to functionB. Return the local variables of functionB to functionA:

def functionA():
    localA = 20
    localB = functionB(localA)
    print(localB)

def functionB(localA):
    print(localA)
    localB = 10
    return localB

CodePudding user response:

I'm not sure if what you want to do is the ideal solution, but perhaps you could try something like this:

def functionB(local_vars):
    print(local_vars["localA"])

def functionA():
    localA = 20
    local_vars = {k: v for k, v in locals().items() if not k.startswith('_')}
    functionB(local_vars)

CodePudding user response:

If there's much information that the two functions need to share, I would suggest encapsulating the what they're doing in combination into a class and making all the local variables that need to shared instance attributes prefixed with self..

Here's what I mean:

class ComboFuncs:
    def functionA(self):
        self.localA = 20
        self.functionB()
        print(self.localB)

    def functionB(self):
        print(self.localA)
        self.localB = 10


ComboFuncs().functionA()
  • Related