以下两种风格 Python 写法,请问大家倾向哪种:)

2018 年 12 月 10 日
 lucat

看到不同的同事代码,表达同一个意思,主要 if 部分以下哪种写法比较好些:)

第一种写法

def xxxx(ph, sin_id):
    """
    
    """
    
    with OracleConnect(xxxx) as db_oracle:
    	
        sql = u"xxxxx"
        has_data, sql_data = db_oracle.get_one(sql)
        
        # 第一种写法
        if has_data:
            calculate_func = "rollback"
            task_id = sql_data.get("task_id", "")
        else:
            calculate_func = "calculate"
            task_id = sin_id
            
	return task_id, calculate_func

第二种写法

def xxxx(ph, sin_id):
    """
    
    """
    
    with OracleConnect(xxxx) as db_oracle:
    	
        sql = u"xxxxx"
        has_data, sql_data = db_oracle.get_one(sql)
        
        # 第二种写法
        calculate_func = "rollback" if has_data else "calculate"
        task_id = sql_data.get("task_id", "") if has_data else sin_id   
        
   	return task_id, calculate_func

第一种写法,比较直接,清晰明了,但有同事说不够 pythonic

第二种写法比较 pythonic,但是类似写法,对于刚接手别人代码的同事,就要稍微绕一下才能读懂。

由此拓展,想到在写业务逻辑中,经常会有 if 语句的判断,请问大家是怎么选择代码风格的:)

10777 次点击
所在节点    Python
107 条回复
menc
2018 年 12 月 12 日
@congeec 都无所谓,hashable type 就可以这么用,list 不行,list 改成 tuple 行,但是数据库返回结果应该是 tuple 不是 list
menc
2018 年 12 月 12 日
@congeec 都无所谓,hashable type 就可以这么用,list 不行,list 改成 tuple 行,但是数据库返回结果应该是 tuple 不是 list。
onice
2018 年 12 月 12 日
毫无疑问是第一种。如果代码是写给自己看,可以用第二种。
mili8908
2018 年 12 月 13 日
简单的 if 判断当然第二种 你不觉得很美吗=。=
JacketPC
2018 年 12 月 13 日
自己写无所谓,但写给别人的,不觉得第一个好方便检查吗?
Qzier
2018 年 12 月 14 日
第一种写法,因为 The Zen of Python 中已经阐明:Explicit is better than implicit。
iorilu
2018 年 12 月 23 日
基于同一个变量判断的, 肯定放一起好

基于这个例子是 1 好, 如果单独变量可以考虑 2

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

https://study.congcong.us/t/516296

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

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

© 2021 V2EX