Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
    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?

share|improve this question

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.

share|improve this answer

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.

share|improve this answer
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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.