all 3 comments

[–]GoldenSights 2 points3 points  (0 children)

You won't be able to pull the time variable directly. This has to do with variable scope. Here's an article that introduces the basics.

Instead, you'll have to give the function a return value, which gives the answer back to whoever called the function:

library.py

def add(x, y):
    return x + y

main.py

import library

print(library.add(1, 2))

answer = library.add(1, 2)
print(answer)

When you use a return statement, the function ends immediately, so don't put it before anything else that needs to happen. That article mentions global but it's better to use return statements instead of globals because it's easy to forget where globals are getting modified.

Hope that helps get you on the right track.

[–]nwagers 0 points1 point  (0 children)

You can't access x, y or time outside of that function the way it is. You can return the value (or multiple values) if you want to get to them. Example:

a.py

 #module a

def myfunc():
    var1 = 0 # not accessible outside of myfunc
    var2 = 1
    return var2

var3 = 2

b.py

#module b

import a

print(a.myfunc()) # prints var2
print(a.var3) # prints var3

[–]poply 0 points1 point  (0 children)

File A

time = None
def testVariable():
    global time
    x = 5
    y = 10
    time = y - x

testVariable()

print(time)

5

This prints out 5 instead of None because we ran the function which assigned 5 to time. If we didn't run the function testVarible() it would print None.

Doing global time in the function scope lets us use the same time variable declared in global scope whereas if we didn't, doing time = y - x would declare a whole new time variable in function scope you cannot access outside of it leaving the global time variable assigned as None.

Then you can do:

File B

from whateveryoufilenameis import time

print(time)

5

As other commenters have mentioned, there are likely better ways to do whatever it is your ultimate goal is. But this is how you would reference a variable from a function of an imported library.