user1687891
user1687891

Reputation: 864

How to get the data from function inside one file to another file

I have to import some value from one file to another file. I have a function name myFunc in second.py where i have a variable name 'a'. Now I want to display this value in first.py file inside main function.

first.py
-------
import os
import second.py import *

def main():
    //here i need to print from another file


if __name__ == '__main__':
    main()

second.py
---------
import os

def myFunc(var1, var2):
    a = 'test user'

Upvotes: 0

Views: 73

Answers (3)

juancarlos
juancarlos

Reputation: 631

when you define a function the variables that were inside it are outside the global scope therefore they are only accessible within that function, if you want to obtain a value of that function you return it a solution to your problem could be the following

second.py

import os
def myFunc(var1, var2):
    a = 'test user';
    return a

Upvotes: 0

Strik3r
Strik3r

Reputation: 1057

Below is an example of what i suggested in the comments.

first.py

import os
from second import first_class

def main():
    obj = first_class()
    print(obj.a)


if __name__ == '__main__':
    main()

second.py

import os

class first_class:
    def __init__(self):
        self.a = 'test user'

Hope it helps !!

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71570

Try returning a in second.py:

import os

def myFunc(var1, var2):
    a = 'test user'
    return a

Then try the below code in first.py

import os
import second

def main():
    print(second.myFunc(something,something))


if __name__ == '__main__':
    main()

Note: something is where you should fill in the argument (meaning the var1 and var2)

Upvotes: 1

Related Questions