Reputation: 418
I am new to Python and am using a method time_passed() for keeping track of how much time has passed.
I would prefer not to use a global variable. Is there a way to write this method so that it doesn't take any parameters and it doesn't use a global variable?
import time
start_time=time.time()
def time_passed():
return time.time() - start_time
What is the pythonic way to handle this?
Upvotes: 0
Views: 1178
Reputation: 3247
Generator should be used for functions that need to encapsulate state.
import time
def time_passed_generator():
start_time = time.time()
while True:
yield time.time() - start_time
time_passed = time_passed_generator()
#start
next(time_passed) # should be about 0.0
# ... later get the time passed
print(next(time_passed))
Upvotes: 1
Reputation: 48
The static variable equivalent in Python is similar to Javascript where assigning a variable under a particular object namespace gives it persistence outside of method scope it was assigned in. Just like in Javascript, Python functions are objects and can be assigned member variables.
So for this example you could write
import time
def timestamp():
timestamp.start_time=time.time()
return time.time() - timestamp.start_time
Edit: now looking at the code however, you clearly want to initialize once and this function will reinitialize start_time per call. I am not so experienced in Python but this may work
import time
def timestamp():
if timestamp.start_time is None:
timestamp.start_time=time.time()
return time.time() - timestamp.start_time
Upvotes: 2
Reputation: 94
You can write a simple class storing the start time:
import time
class Timer:
def __init__(self):
self.start = time.time()
def __call__(self):
return time.time() - self.start
Then use it like:
time_passed = Timer()
print time_passed()
This way you can easily use multiple timers as well.
Upvotes: 2