Emmanu
Emmanu

Reputation: 797

How to call a variable inside main function from another program in python?

I have two python files first.py and second.py

first.py looks like

def main():
  #some computation
  first_variable=computation_result

second.py looks like

import first
def main():
  b=getattr(first, first_variable)
  #computation

but I am getting No Attribute error. Is there any way to access a variable inside main() method in first.py through second.py?

Upvotes: 0

Views: 2416

Answers (2)

wwii
wwii

Reputation: 23753

You will want to read 9.1 and 9.2 in the Tutorial and Naming and Binding in the Language Reference.

In your example first_variable only exists within first.main()'s local scope - while it is executing. It isn't accessible to anything outside of that scope.


You need to get first_variable into first's global scope - then in second you can use it with first.first_variable.

One way would be to return something from first.main() and assign it to first_variable.

def main():
    return 2

first_variable = main()

Then in second you can use it:

import first
times_3 = first.first_variable * 3

Upvotes: 1

nempat
nempat

Reputation: 456

You should use function calls and return values instead of this.

Return the computation_result from the function in the first file, and then store the result in the b variable in the second file.

first.py

def main():
    # computation
    return computation_result

second.py

import first
def main():
    b = first.main()

Other option is to use a global variable in the first file where you will store the value and later reference it.

Upvotes: 4

Related Questions