How to access a variable from a function which is in another file in python

Question:

I am new to python. As part of my project, I am working with python2.7. I am dealing with multiple files in python. Here I am facing a problem to use a variable of particular function from another file which was I already imported in my current file.
Please help me to achieve this.

file1.py
class connect():
    # Contains different definitions
    def output():
        a = "Hello"
        data = // some operations
        return data

file2.py
from file1 import *
# Here I need to access both 'a' and 'data' variable from output()
Asked By: sowji

||

Answers:

One option you have is to return all the data you need from the function:

file1.py

class connect():
    # Contains different definitions
    def output():
        a = "Hello"
        data = // some operations
        return a,data   # Return all the variables as a tuple

file2.py

from file1 import connect
c = connect()
a,data = c.output()
# Now you have local variables 'a' and 'data' from output()
Answered By: quamrana

So you have edited it quite a bit since I started writing about conventions so I have started again.

First, your return statement is out of indentation, it should be indented into the output method.

def output():
    a = "Hello"
    data = // some operations
    return data

Second, the convention in Python regarding class names is CamelCase, which means your class should be called “Connect”. There is also no need to add the round brackets when your class doesn’t inherit anything.

Third, right now you can only use “data” since only data is returned. What you can do is return both a and data by replacing your return statement to this:

return a, data

Then in your second file, all you have to do is write a_received, data_received = connect.output()

Full code example:

file1.py

class Connect:

    def output():
        a = "Hello"
        data = "abc"
        return a, data

file2.py

from file1 import Connect

a_received, data_received = Connect.output()

# Print results
print(a_received)
print(data_received)

Fourth, there are other ways to combat this, like create instance variables for example and then there is no need for return.

file1.py

class Connect:

    def output(self):
        self.a = "Hello"
        self.data = "abc"

file2.py

from file1 import Connect

connection = Connect()
connection.output()

print(connection.a)
print(connection.data)

There is also the class variable version.

file1.py

class Connect:

    def output():
        Connect.a = "Hello"
        Connect.data = "abc"

file2.py

from file1 import Connect

Connect.output()

print(Connect.a)
print(Connect.data)

Eventually, the “right” way to do it depends on the use.

Answered By: BoobyTrap
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.