這個問題的由來是燒瓶教程http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask。在閱讀本教程中,我碰到這個功能來:檢查字符串是否爲unicode時,何時使用值比較而不是識別比較更好?
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods = ['PUT'])
def update_task(task_id):
task = filter(lambda t: t['id'] == task_id, tasks)
if len(task) == 0:
abort(404)
if not request.json:
abort(400)
if 'title' in request.json and type(request.json['title']) != unicode:
abort(400)
if 'description' in request.json and type(request.json['description']) is not unicode:
abort(400)
if 'done' in request.json and type(request.json['done']) is not bool:
abort(400)
task[0]['title'] = request.json.get('title', task[0]['title'])
task[0]['description'] = request.json.get('description', task[0]['description'])
task[0]['done'] = request.json.get('done', task[0]['done'])
return jsonify({ 'task': task[0] })
該行使用值進行比較:
if 'title' in request.json and type(request.json['title']) != unicode:
但這一行使用的身份比較:
if 'description' in request.json and type(request.json['description']) is not unicode:
是否有一個原因,作者不一致?這兩個版本是否會提供相同級別的安全性?如果是這樣,pythonic方法是什麼?
如果您在談論「!=」和「不是」,在最新版本中不推薦使用值比較「!=」,所以習慣使用「!=」的人有時會繼續使用 – user2753523