0

So I have two files: test.py and test2.py

Let's say I want to access the local variable of a function that belongs to another .py file, and have it display on the .py file I am working on. For example: I want my file test2.py to only display the variable three which belongs to the secondmain() function inside the program test.py Assuming that the variable three is a fixed local variable for test.py (meaning that making it global variable by putting it outside its function might break the code) ehat should I do to make it happen? Is it even a possibility?

test.py file:

import test2

def main(): <-- able to access
    two = '2'
    print("the letter " + two)

def secondmain():
    three = '3' <-- wants to access
    print("toying")
    print("dancing")
    print("testing")

print(main())

test2.py file:

import test

print('testing something')

test.main() # accessing the main() function of test.py

# accessing second main but wants to JUST access its variable three.
# test.secondmain().three???
Ross Chris
  • 95
  • 2
  • 7
  • Why would you want to do this? What are you trying to accomplish? – Scott Hunter Aug 03 '18 at 22:38
  • In the program I am writing (which isn't this one btw, that's an example test. The real one is complex), when I attempt to make the variable in the other program global so that I can use it, it breaks the code. Additionally, I could make another copy of the same variable I am using in the other program, but that why would I repeat the code in another file, consuming program memory – Ross Chris Aug 03 '18 at 22:54
  • If you want something to be global, make it global, and fix the code accordingly. – Scott Hunter Aug 03 '18 at 23:34
  • It's not that easy. The variable in question is a jSON file request and it is fixed in the program that I need my other .py file to get access to. If there is any other solutions to access the variable that I need, I would appreciate it. Otherwise in my case, making it global seem impossible and adds more to the work – Ross Chris Aug 03 '18 at 23:51
  • 1
    Why not use a class and import the class into your other file? See this [SO question](https://stackoverflow.com/questions/10139866/calling-variable-defined-inside-one-function-from-another-function) for a simple example. – benvc Aug 04 '18 at 02:26

0 Answers0