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:
- Replace
json_response
direct call with composition. - Code should not become a message from Sirius: everybody should still be able to understand it just without any efforts.
- It should be robust (composition type safety) yet easy extensible.
Any ideas?
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.
I'm not sure I'm directly responding to your points, since I don't think I get what you're aiming for, but:
assert
s 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.loads
ed object (or the return value of your first function) passed in.