Skip to content Skip to sidebar Skip to footer

Nameerror Says Variable Is Not Defined, But Only In Some Places

I am trying to implement a keep-alive that sends some data every 30 seconds to keep a telnet connection open. My code calls reinitScore every second. This function will sometimes

Solution 1:

In response to your updated code... The error message is still correct, because although you have defined stelnet at the module level, you've defined it too late. It's definition occurs after its use in the calculateWinner function.

Stripping your code down to a ridiculously minimal example, you are doing something like this:

def calculateWinner():
    # A leap of faith...  There is no `stelnet` defined
    # in this function.
    stelnet.send(results[0])

def reinitScore():
    # Indirectly depends on `stelnet` too.
    calculateWinner()

# But we haven't defined `stelnet` yet...
reinitScore() # Kaboom!

# These lines will never run, because the NameError has
# already happened.
if __name__ == '__main__':
    stelnet = ...  # Too late.

calculateWinner depends on a name that does not exist when the function is compiled. Whether it works or crashes will depend on whether some other code has defined stelnet 1) where calculateWinner can get at it, and 2) before calculateWinner is executed.

Suggestions

Functions that depend on global mutable state are hard to follow, let alone code correctly. It's not easy to tell what depends on which variables, or what's modifying them, or when. Also, coming up with an MCVE is more trouble than it should be, because functions that appear independent might not be.

Stuff as much of your module-level code as you can into a main function, and call it (and nothing else) from the body of if __name__ == '__main__': (since even that is actually at module level).

Consider something like this:

def reinit_score(output_socket, shared_scores):
    # Ensuring safe concurrent access to the `shared_scores`
    # dictionary is left as an exercise for the reader.
    winner = ...  # Determined from `shared_scores`.
    output_socket.send(winner)
    for key in shared_scores:
        shared_scores[key] = 0
    threading.Timer(
      interval=1,
      function=reinit_score,
      args=[output_socket, shared_scores],
      ).start()

def main():
    output_socket = ...  # This was `stelnet`.
    shared_scores = {...}  # A dictionary with 4 keys: L/R/U/D.
    reinit_score(output_socket, shared_scores)
    while True:
        play_game(shared_scores)
        # `play_game` mutates the `shared_scores` dictionary...

if __name__ == '__main__':
    main()

These functions are still connected by the shared dictionary that they pass around, but only functions that are explicitly passed that dictionary can change its contents.

Solution 2:

Your code is not working because you are not passing stelnet to your function.

Post a Comment for "Nameerror Says Variable Is Not Defined, But Only In Some Places"