简体   繁体   English

Python - if如果使用了什么:?

[英]Python - What's the use of if True:?

I just came accross the following code in an existent project, which I'm working on: 我刚刚在一个现有的项目中遇到以下代码,我正在研究:

if True:
    x = 5
    y = 6
    return x+y
else:
    return 'Something

Inside the if True are lots of conditions and some will also return the function already. if if中有很多条件,有些也会返回函数。 Why would somebody write in that way? 为什么有人会这样写? The code contained some other bugs also, but was just wondering about the if True: statement as it didn't make any sense to me. 代码还包含一些其他错误,但只是想知道if True:语句,因为它对我没有任何意义。 Probably also pretty stupid to ask it, but was wondering hehe. 可能也很愚蠢地问它,但是想知道嘿嘿。

It might be a remnant of debugging or refactoring. 它可能是调试或重构的残余。 It may be that instead of True , there was orginally a condition or variable there but it has now been replaced by True . 可能是,而不是True ,有一个条件或变量,但它现在已经被True取代。 The developer perhaps left it there without refactoring or cleaning it up all the way. 开发人员可能会将其留在那里,而无需重构或清理它。

If you're free to edit the code as you wish and you're sure that the else is no longer needed, then you can remove it. 如果您可以根据需要自由编辑代码,并且确定不再需要其他代码,则可以将其删除。 It indeed makes no sense to have code in your codebase that will never run. 在您的代码库中拥有永远不会运行的代码确实没有意义。

True doesn't necessarily mean True True并不一定意味着True

True = False
if not True :
    print "True is false" # This prints ok

Honestly, I don't think anyone would code like this. 老实说,我认为没有人会像这样编码。

Does not make any sense to me, my guess is that someone wanted to have two distinct code paths that he could alternate between a'la using #if 1 .. #else -> #if 0 ... for debugging or such purposes. 对我来说没有任何意义,我的猜测是有人想要有两个不同的代码路径,他可以在'a使用#if 1 .. #else - > #if 0 ...之间交替进行调试或此类目的。

Other possibility was that, as @SimeonVisser suggested, the original developer was refactoring or cleaning up the code (and did not have an emulator that allows one to easily remove 1 step of indentation from a block of code) 其他可能性是,正如@SimeonVisser所建议的那样,原始开发人员正在重构或清理代码(并且没有一个模拟器允许人们轻松地从代码块中删除1步缩进)

它可以是用于调试的标志。

It's simply used to ensure that the else: block is never executed. 它只是用于确保从不执行else:块。
I have used if True: for some blocks to ensure that my code really does what I want. 我使用if True:对于某些块来确保我的代码真正做到我想要的。 Usage for debugging or refactoring. 用于调试或重构。
All in all it makes no real sense to use this in an application but for testing or debugging it's somehow acceptable. 总而言之,在应用程序中使用它并没有任何意义,但对于测试或调试它在某种程度上是可以接受的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM