如何优雅地解决pylint(Too-Many-Return Statements)?
太多的返回陈述的例子如上所述,但我的情况如下:如何使功能更美丽?
def func():
# do something1
ret1 = do_something1()
if ret1 != 0:
return ret1
# do something2
ret2 = do_something2()
if ret2 != 0:
return ret2
# ......
return 0
The example of too-many-return-statements is as above, but my scenario is as follows, how to make the function more beautiful?
def func():
# do something1
ret1 = do_something1()
if ret1 != 0:
return ret1
# do something2
ret2 = do_something2()
if ret2 != 0:
return ret2
# ......
return 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以尝试这样的事情:
解决您的示例。您可以这样解决您的方案:
You could try something like this:
to solve your example. And you could solve your scenario like this:
查看此示例。
它转换为:
to:
只是为了使其沉默,另一个选择是:
您也可以在
settings.json
文件中静音。Check out this example.
It converted:
to:
Just to silence it another option is:
You can also silence it in
settings.json
file if you think it's too strict rule which I think it is:我建议这样做
I recommend doing it this way
使用某种形式的查找是处理此问题的方法。词典是一个很好的通用想法。当查找“键”是整数时,列表很有用。
但是,
当使用查找技术时,您必须考虑您的“键”可能不可用。如果您的字典(例如)具有7个整数键(1-> 7包含),并且您的函数的值为8,那么您将要做什么?您可以允许异常并分别处理该例外,或者您需要避免异常并返回一些默认值,也许是隐式的。
Using some form of lookup is the way to handle this. A dictionary is a good general purpose idea. A list is useful when the lookup 'key' is an integer.
HOWEVER
When using a lookup technique you have to consider that your 'key' may not be available. If your dictionary (for example) has 7 integer keys (1->7 inclusive) and your function is passed a value of 8, what are you going to do? You could allow the exception and deal with that separately or you need to avoid an exception and return some default value, perhaps implicitly.
通常,您可以通过Pylint文档使用拟议的解决方案:
https:> https:https:https:///pylint.pycqa。 org/en/最新/user_guide/messages/rebactor/too-ny-return-statements.html
但是,在某种程度上,恕我直言,这是不可能使用的。
我不为您的特定情况进行夸大,但是您可以使用这样的评论在特定的代码行中禁用孔。
In general you can use the proposed solution by pylint documentation:
https://pylint.pycqa.org/en/latest/user_guide/messages/refactor/too-many-return-statements.html
But IMHO in some case it's impossible to use.
I don't kwonw your specific case, but you can disable pylint in a specific line of code using a comment like this.
由于python 3.10,您可以使用匹配其他编程语言的能力。
您的代码可以转换为这样的东西:
Since python 3.10 you can use match which is very similar to switch/case capability in other programming languages.
Your code can be converted to something like this: