Cheesecake
Cheesecake

Reputation: 11

How to check if a function ran without generating any errors

I want to check to see if a message() function ran correctly and managed to send the message, the user could be out of reach for a certain time so I want to script to skip over his name it didn't manage to message him, and to mark the name of people it send a message to

I tried to set a bool value That changes after the function runs but it doesn't seem to work, i'm using a modular to send the message I recive error on the modular not the script itself

user_was_messaged = False

def message_user()
    user_was_messaged = True

Upvotes: 1

Views: 1536

Answers (2)

Shuvam Paul
Shuvam Paul

Reputation: 138

As you have the variable user_was_messaged before the function, you must declare the variable as global in the function as in like:

user_was_messaged = False

def message_user()
    global user_was_messaged
    user_was_messaged = True

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993461

If your user_was_messaged variable is global, then you need to use the global Python statement to change the value from within your function:

user_was_messaged = False

def message_user():
    global user_was_messaged
    user_was_messaged = True

However, using a global variable for this purpose would be highly discouraged. Instead, use the return value of the function:

def message_user():
    # do things to try to send a message
    if cannot send:
        return False
    # maybe do more things
    return True

if message_user():
    print("successful")
else:
    print("failed")

Upvotes: 1

Related Questions