Skip to content
Advertisement

Fixing the value of a variable that changes in terms of another

Suppose I have a global variable time that is incremented by 1 unit with every update of the window according to some FPS (for example in Pygame). Then suppose I have another variable defined in terms of time, like this:

def function():
    global time

    t = time // 3
    final = t + 100
    
    if t < final:
        pass
    else:
        pass

The behavior I want is that the variable final stores the value of t just when the function is first called and then final becomes a constant, while t keeps running together with time. So, final would not always be 100 ahead of t, which is what happens, but would be 100 ahead of t just when the function first captures t and then would keep that number unchanged. How can that be done?

Advertisement

Answer

You can make final global and check if it has been set.

final = None
def function():
    global time, final

    t = time // 3
    if not final: final = t + 100  # update once
    
    if t < final:
        pass
    else:
        pass

You can also create an attribute on the function itself.

def func():
    global time

    t = time // 3
    if not 'final' in dir(func): func.final = t + 100  # update once
    
    print(func.final)
    
    if t < func.final:
        pass
    else:
        pass

time=10
func()
time=20
func()
time=30
func()

Output

103
103
103
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement