# Flexible multiple string comparision to determine variable value

I've a web form that allows users to create clusters of three sizes: small, medium and large. The form is sending a string of small, medium or large to a message queue, were job dispatcher determines how many jobs (cluster elements) it should build for a given cluster, like that:

# determine required cluster size
if cluster['size'] == 'small':
jobs = 3
elif cluster['size'] == 'medium':
jobs = 5
elif cluster['size'] == 'large':
jobs = 8
else:
raise ConfigError()


While it works, its very ugly and non flexible way of doing it - in case I'd want to have more gradual sizes, I'd increase number of elif's. I could send a number instead of string straight from the form, but I dont want to place the application logic in the web app. Is there a nicer and more flexible way of doing something like that?

-

You could keep an array of jobs, and the web application would send index instead of word 'small', 'medium', 'large'.

So you could have an array [3, 5, 8] and instead of "small" you send 0, instead of "medium" you send 1, and instead of "large" you send 2. You only need to check if the index received does not exceed the table size.

-

I'd write:

jobs_by_cluster_size = {"small": 3, "medium": 5, "large": 8}
jobs = jobs_by_cluster_size.get(cluster["size"]) or raise_exception(ConfigError())


raise_exception is just a wrapper over raise (statement) so it can be used in expressions.

-
I'm afraid that's not valid python –  Winston Ewert Feb 2 '13 at 14:16
@WinstonEwert: Oops, I had completely forgotten raise is an statement in Python and not a function/expression (too much Ruby lately, I am afraid). Fixed (kind of). –  tokland Feb 2 '13 at 14:25

how about using a dictionary whose keys are the different cluster types i.e. small, medium, large and the value is the actual cluster size i.e. 3,5,8

Then when you get the POST request from the web form you just get the value from the dictionary. If no key exists then it's a validation error and you handle that appropriately.

You can keep the dictionary in a static class so that it can be used throughout your app.

-