IT.dumb
IT.dumb

Reputation: 69

how to check for conditions

This might not be a programming logic question, but what could be the best to use type. I have following two way, which can be the best way to use. If there is other way, I will be more than happy to know.

Conditions/Values

permission = True
user = {"id": 1, "username": "it.dumb", "password": "", "locked": True}

First part

if not permission:
    return "Error, you are not permitted"

if not user:
    return "Error, user not found"

if not user["locked"]:
    return "Error, user is not locked"

user["locked"] = False
return user

Second part

if permission:
    if user:
        if user["locked"]:
            user["locked"] = False
            return user
        else:
            return "Error, user is not locked"
    else:
        return "Error, user not found"
else:
    return "Error, you are not permitted"

Assuming these two codes are inside a method ;)

Upvotes: 0

Views: 50

Answers (1)

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9704

A very pythonic answer - flat is better than nested, and better ask for forgiveness than ask for permission.

class AuthenticationError(Exception):
    pass

 ....

if not permission:
    raise AuthenticationError("Error, you are not permitted")

if not user:
    raise AuthenticationError("Error, user not found")

if not user["locked"]:
    raise AuthenticationError("Error, user is not locked")

user["locked"] = False
return user

Upvotes: 3

Related Questions