-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 ??

Suraj Donthi
  • 1
  • 1
  • 3
  • 2
    how about having the `detect()` function return the variable? – FlyingTeller Feb 26 '18 at 13:58
  • 1
    One way would be to have the detect function return the s value. Then you can call detect from anywhere. – John Gordon Feb 26 '18 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. – Suraj Donthi Feb 26 '18 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](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? – Aran-Fey Feb 26 '18 at 14:02
  • `s` doesn't have a value until `detect()` is actually evaluated, so what you're asking for doesn't make sense. – cowbert Feb 26 '18 at 14:26
  • @Aran-Fey I think I fell into the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Thanks for post. Brought a lot of clarity for asking question! – Suraj Donthi Feb 27 '18 at 05:23
  • Actually, I wanted to pass the value of `TimeElapsed` to run the function `detect()` to a function in another file.Previously, the variable `TimeElapsed` was calculated inside `detect()` and the problem was that the File Structure was huge and finding the two function calls was confusing. Apparently, I realized that both these functions were actually called by the `__main__` function and not within separate files. Hence, I resolved it by tracking the time of execution of `detect()` in the `__main__` function and passing the `TimeElapsed` to the other function which is defined in `File2` – Suraj Donthi Feb 27 '18 at 05:30

1 Answers1

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)
sahama
  • 669
  • 8
  • 16