#you could do something like that but i
1 messages · Page 1 of 1 (latest)
last_fired = getattr(cls, "exampleFunc1LastFiredTime", 0)
This line does not make sense to me, can you break it down to it's arguments? I'm struggling with the ,0, specifically
it's like the dict get(), the last argument is a default value
>>> a = {}
>>> a["hello"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: hello
>>> a.get("hello", 1515)
1515
same with getattr
so it attempts to pull the value examplefunc1LastFiredTime from the class attributes, and if that fails it sets it to 0?
it returns 0, it doesn't set the value
the value gets set in the last line
so that next time it doesn't return the default
you could do that too, but I like that the default value skips the need to set the attribute in advance
if not hasattr(cls, "exampleFunc1LastFiredTime"):
cls.exampleFunc1LastFiredTime = 0
but I like to encapsulate the timing logic in a function as I showed with the its_time example, which also has the "token" (which replaces the variable name) being only in one place, less prone to typos
but again, this might not require more memory, due to the use of less code:
class example:
exampleFunc1LastFiredTime = 0
@classmethod
def exampleFunc1(cls):
if time.monotonic() >= cls.exampleFunc1LastFiredTime + TIMEOUT:
print("exampleFunc1 Fired", time.monotonic())
cls.exampleFunc1LastFiredTime = time.monotonic()
exampleFunc2LastFiredTime = 0
@classmethod
def exampleFunc2(cls):
if time.monotonic() >= cls.exampleFunc2LastFiredTime + TIMEOUT:
print("exampleFunc2 Fired", time.monotonic())
cls.exampleFunc2LastFiredTime = time.monotonic()