python - PEP8 是否建议从方法返回变量或函数调用?

标签 python pep8

根据 PEP8,从方法返回值的推荐方式是什么?为什么?我尝试在 PEP8 中查找关于此的文档,但找不到任何内容。

方法一

def method():
    a = meth2()
    return a

方法二

def method():
    return meth2()

最佳答案

PEP8没有指定您是否应该返回变量还是函数。

但是,它确实说你应该保持一致:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None , and an explicit return statement should be present at the end of the function (if reachable).

# Yes
def myfunction(a: int, b: int) -> int:
    if a % 2 == 0:
        return int(a ** b)
    else:
        return 0

# No
def my_bad_function(a: int, b: int) -> int:
    if a % 2 == 0:
        return int(a ** b)
    # Implicitly returns None when the above if statement evaluates False

返回相同类型的变量也是一个好主意(尽管未在 PEP8 中涵盖)。
您会看到我在上述函数中添加了可选的类型提示。第二个函数偶尔会返回 None
如果另一个使用此函数的代码块期望返回值具有与 int 相同的属性,例如 int.bit_length()

,这可能会导致问题

会导致异常的代码示例:

for n in range(1, 10):
    nlen = my_bad_function(n * 5, n).bit_length()

关于python - PEP8 是否建议从方法返回变量或函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631822/

相关文章:

git 预提交钩子(Hook) : trigger only to actual to be commited code?

python - 如何修复 flake 8 错误 "E712 comparison to False should be ' 如果 cond 为 False :' or ' 如果不是 cond :'"在 pandas dataframe

python - 惯用的 Python - 检查零

python - 长返回类型提示和 pep8

python - 导入行 : E501 line too long 中的 PEP8 错误

python - 如何每 2 分钟给一个数字加 1?

python - Pandas:与 nan 的操作

python - Django 覆盖 ModuleNotFoundError : No module named 'django_extensions'

python - Python 中的链式字符串格式化

python - python中将数据缩放到特定范围