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()
CodePudding user response:
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
CodePudding user response:
Local variables are alive only inside the function where you create them. One of ways is setting global variables in function_.py
function_.py
a = 0
b = 0
# ...
func():
global a, b
a = 5
b = 4
main.py
from function_ import a, b
x = a
y = b
