今天准备离职的同事交接工作,有一段代码,大家看看。

2019-10-09 21:36:34 +08:00
 CLANNADHH
今天准备离职的同事交接工作,有一段代码,大家看看。
django 写的接口,POST 请求,一共四个参数,下面用 a,b,c,d 代替

a = request.post.get("a")
b = request.post.get("b")
c = request.post.get("c")
d = request.post.get("d")

try:
a + b + c + d + "abcd"
except:
# 这里是错误的处理。

后来询问该同事,他说这是做类型检测,不是字符串就会报错。
我:!!! 哦~
13946 次点击
所在节点    Python
75 条回复
ClericPy
2019-10-09 23:18:15 +08:00
@CLANNADHH 好吧... 陈年佳酿般的屎山, 都这么过来的, 没有 code review
CLANNADHH
2019-10-09 23:21:32 +08:00
@Trim21 略略略~
wangyzj
2019-10-09 23:24:14 +08:00
@CLANNADHH 这不是经验问题了,这是意识问题
ila
2019-10-09 23:41:01 +08:00
类型检测不是应该 jsonschema 之类吗
hyserendipity
2019-10-10 00:00:27 +08:00
cr 的重要性可见一斑。然而,绝大多数人由于工作太多,疏于提交 cr/帮别人 cr。
Winrey
2019-10-10 00:28:13 +08:00
serializer 做错了什么,为什么放弃 serializer
no1xsyzy
2019-10-10 03:20:27 +08:00
@Trim21 看具体需求可以 .get("a", "") 然后 if a and b and c and d 或者说 all((a,b,c,d))
当然,其实 dataclass + dacite 能够解决大多数这种问题了。
mamahaha
2019-10-10 05:01:49 +08:00
我自己写代码也经常有很幼稚的 bug,我总感觉谁都有脑子短路的时候,所以看到别人代码有错都是提醒,心理上不敢去嘲笑。
是不是证明我还不太专业?专业人士不该出现幼稚的错误吧?
secsilm
2019-10-10 07:11:28 +08:00
这样写很机智啊,一起检查所有变量的类型。感觉离职的这位水平应该不错
sunulin
2019-10-10 07:27:09 +08:00
快,修改下,再来吐槽
ila
2019-10-10 07:38:40 +08:00
@secsilm 这还机智,网上那么多解决方法,为啥不抄一个好的呢
Allianzcortex
2019-10-10 08:50:42 +08:00
marshmallow 就是应对这种情况
JerryCha
2019-10-10 09:17:01 +08:00
学习了,真精巧
mskf
2019-10-10 09:20:59 +08:00
如果很多参数的话这么做确实不错。。
bakabie
2019-10-10 09:22:27 +08:00
有一说一,好歹是能用的(
tonnycao
2019-10-10 09:50:53 +08:00
为什么不用 isinstance 我是主攻 PHP 的
Eleflea
2019-10-10 10:28:31 +08:00
我觉得这样做没什么问题。Python 的 try...except 不仅是用来处理错误的。参见 fluent python P449.

In Python, try/except is commonly used for control flow, and not just for error han‐
dling. There’s even an acronym/slogan for that documented in the official Python glos‐
sary:
EAFP
Easier to ask for forgiveness than permission. This common Python coding style
assumes the existence of valid keys or attributes and catches exceptions if the as‐
sumption proves false. This clean and fast style is characterized by the presence of
many try and except statements. The technique contrasts with the LBYL style com‐
mon to many other languages such as C.
jinhao7773
2019-10-10 10:37:00 +08:00
参考 https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.QueryDict.get

如果没有传过来对应的参数,是会有 None 的,人家一行代码就检查了 4 个参数是否都有传值,挺厉害的技巧啊。
hanxiaomeng
2019-10-10 10:42:01 +08:00
精巧,思路瞬间开阔了
lihongjie0209
2019-10-10 10:43:18 +08:00
就不能这么写吗?
try:
a = request.post.getAsString("a")
b = request.post.getAsString("b")
c = request.post.getAsString("c")
d = request.post.getAsString("d")

catch:
// 异常逻辑

自己扩展一下或者是写一个工具类都可以啊。


没看懂这种表意不明的写法有什么好推荐的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/607625

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX