PyCon: Evangelizing Python
Posted Mar 30, 2013 14:26 UTC (Sat) by
intgr (subscriber, #39733)
In reply to:
PyCon: Evangelizing Python by dpquigl
Parent article:
PyCon: Evangelizing Python
> I needed to validate the types of data coming in from a json string and to do this I checked if the values I got back matched certain data types which apparently is a big no no in the world of python. Instead I'm supposed to use them as if they were those data types and wait for the world to explode when they aren't and pick up the pieces.
I believe there's a misunderstanding there. You shouldn't do type-checking of data passed in internal APIs; if your function accepts a string parameter, you don't check that it's string every time -- just assume that the caller got it right.
However, if you're decoding JSON received from untrusted sources, then that kind of type checking makes sense and is often required to prevent some kinds of security bugs.
Case in point with Python 2:
def check_age(data):
d = json.loads(data)
if d['age'] < 18:
print "You must be 18 or older to continue."
else:
print "OK!"
>>> check_age('{"age": 13}')
You must be 18 or older to continue.
>>> check_age('{"age": "13"}')
OK!
This hole is fixed in Python 3, but in general there are still surprises you can run into if you allow arbitrary types from untrusted input.
(
Log in to post comments)