I have a function
def compute_daily_quantities():
# compute some quantities, one of which is the variable, value
After the first call to compute_daily_quantities, we need to add a constant, c to value.
How can I check if it's the first or a subsequent call to compute_daily_quantities?
I come from a C++ background, and in C++, we can introduce a static variable within the function to check. I know you can do something similar in Python, but are there other ways in which this can be done in Python?
The solution I was envisioning is:
def compute_daily_quantities():
# compute some quantities, one of which is the variable, value
if not hasattr(compute_daily_quantities, "is_first_call"):
compute_daily_quantities.is_first_call = True
else:
value += c
compute_daily_quantities.is_first_call = False
Rather than using a function, you might want to keep the attribute in a separate class, like this:
You would then need to make sure that you only instantiated a single instance of the class, otherwise your newer classes would be instantiated with the 'first value' flag as
FalseYou might be able to use a singleton pattern, or a class attribute (rather than an instance attribute) to do this in a safer way depending on how exactly you planned to use it.