Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
def json_response(response):
    assert response.code == 200, 'bad http response'
    return json.loads(response.body)

def custom_json_response(response):
    response = json_response(response)
    assert 'answer' in response, 'invalid custom json'
    return response['answer']

The code looks straightforward but I wonder if there any chance to rewrite it to achieve the following:

  1. Replace json_response direct call with composition.
  2. Code should not become a message from Sirius: everybody should still be able to understand it just without any efforts.
  3. It should be robust (composition type safety) yet easy extensible.

Any ideas?

share|improve this question

2 Answers 2

I would not rely on assert. If Python is started with the -O option, then assertions will be stripped out and not evaluated. Better to raise an Exception here.

share|improve this answer

I'm not sure I'm directly responding to your points, since I don't think I get what you're aiming for, but:

  • asserts shouldn't be used for these types of checks (I personally don't use them at all, but if you are going to use them, they're for checking invariants)

  • As for what I think you were going for with your composition point, I would just have your second function take an already json.loadsed object (or the return value of your first function) passed in.

share|improve this answer

Your Answer

 
discard

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.