Last minute geek

last minute tech news from around the net

Friday, Oct 19th

Last update01:00:00 AM

You are here: English WTF CodeSOD: Assertive Programming

CodeSOD: Assertive Programming

User Rating: / 0
PoorBest 

Defensive programming is an important tool in any developer's toolbox. In strictly typed languages, types themselves provide a natural defense against certain classes of bugs, but in loosely typed languages, you may have to be more clear about your assumptions.

For example, in Python, you might choose to use the assert keyword to, well, assert that something is true. It's often used in debugging, but it's also a good way to ensure that the state of the parameters passed to a function, or some other state of your system is correct before doing anything else. If it's not, the code raises an exception.

Dima R found this "interesting" riff on that concept.

try: assert r.status_code == 201 except: print(r.text) pass

Here, the assertion is confirming that we get the expected HTTP status code from a request, but if we didn't, it doesn't bubble up the exception- it just prints the body of the response.

This code has been in production for some time. When Dima tracked down the culprit and asked what they were thinking, the developer admitted:

it was originally an assert just for sanity, but then I wanted to print the result if the assert failed and I wasn't paying very much attention lol

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

Read all
Comment Policy:
We pre-moderate any comments and welcome all kinds of thoughts, supportive, dissenting, critical or otherwise. We delete or censor comments that are:

* abusive
* off-topic
* contain personal attacks, or against any company or organization
* promote hate of any kind
* use excessively foul language
* is blatantly spam or advertising

We do not discriminate based on the person who is posting, and we never censor comments for political or ideological reasons. We never delete an appropriate comment because we disagree with its viewpoint or ideology, and we never publish an inappropriate comment because we agree with or support its viewpoint or ideology.


Attention spammers: we manually approve all comments. Spamming and blatant advertising will NOT be published on this site and is deleted immediately, you've been warned, do not waste your time here.

Add comment

Security code
Refresh