-2

I have two files File1 and File2. In File1 I have a function detect() defined as:

def detect():
    s = // some operations

I need to access this variable s in File2.

I have tried declaring the variable as global but it has not worked.

How can I access the variable without creating a class as in this post or by using __main__ as in this post ??

7
  • 2
    how about having the detect() function return the variable? Commented Feb 26, 2018 at 13:58
  • 1
    One way would be to have the detect function return the s value. Then you can call detect from anywhere. Commented Feb 26, 2018 at 13:58
  • I cannot call the function as it performs may other operations but I need to only access that variable. I'll need to call the function in order to access the variable which I don't want to. Commented Feb 26, 2018 at 14:00
  • 1
    Accessing a function's local variable without calling it doesn't make any sense. What's the X in this XY problem? Commented Feb 26, 2018 at 14:02
  • s doesn't have a value until detect() is actually evaluated, so what you're asking for doesn't make sense. Commented Feb 26, 2018 at 14:26

1 Answer 1

1

function detect must be run to init its local variables.

def detect():
    detect.tmp = 1

def b():
    print(detect.tmp)

detect()
b()

of course you can import one python file as python module and call its functions like

from File1 import detect
print(detect.tmp)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.