Rob
Rob

Reputation: 3459

Presentation of sys.argv for conditional statement

I have a function set up like:

args = sys.argv[1:]
if args:
    if args[0] in Constants.envs.keys():
        environment = Constants.envs[args[0]]

but I feel this isn't very clean looking. Is there a better way to check for an argument and if valid, set a variable to it?

Upvotes: 0

Views: 222

Answers (1)

Benjamin Hodgson
Benjamin Hodgson

Reputation: 44634

Why not just combine the two if statements?

args = sys.argv[1:]
if args and args[0] in Constants.envs:
    environment = Constants.envs[args[0]]

You could also use the dict's get method, which returns a default value if the key is missing. This means you don't have to check args[0] in Constants.envs.keys().

args = sys.argv[1:]
if args:
    environment = Constants.envs.get(args[0])  # will return None if the key is missing

Upvotes: 2

Related Questions