Sam Stoelinga
Sam Stoelinga

Reputation: 5021

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. 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. Probably also pretty stupid to ask it, but was wondering hehe.

Upvotes: 2

Views: 2840

Answers (5)

Kien Truong
Kien Truong

Reputation: 11381

True doesn't necessarily mean True

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

Honestly, I don't think anyone would code like this.

Upvotes: 5

mas-designs
mas-designs

Reputation: 7536

It's simply used to ensure that the else: block is never executed.
I have used if True: for some blocks to ensure that my code really does what I want. 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.

Upvotes: 0

Kimvais
Kimvais

Reputation: 39548

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.

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)

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122376

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. 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.

Upvotes: 10

sulabh
sulabh

Reputation: 1117

It could be a flag used for debugging.

Upvotes: 0

Related Questions