Search code examples
pythonfunctionvariableslocalizationreturn

Accessing local variables from another function another function without returning Python


Is there a way to access the contents of function_.py's func() functions local variables a,b,c...s from main.py wikthout having to return the function on main, being like a,b...s = main(). If so how would I be able to do it.

function_.py:

func():

   a = 5
   b = 4
   c = 11
   k = 55
   d = 99
   s = 66

Main.py

import function_

def main():
   func()
   print(a, b, c, d, k, d, s)
main()

Solution

  • There's no way to do what you're pretending to. I suggest to create a class instead a function, this way:

    File 2:

    class SecondFile(object):
        def __init__(self):
            self.a = 1
            self.b = 2
            self.c = 3
            self.d = 4
            self.e = 5
    

    File 1:

    from second import SecondFile
    
    def main():
        x = SecondFile()
        print(x.a, x.b, x.c, x.d, x.e)
            
    main()
    

    Output:

    1 2 3 4 5