0

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.