Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I elegantly implement version checking in Python without throwing off indentation?

Tags:

python

I'd like to very elegantly integrate version checking in Python.

I don't want a version checking routine to throw off the indentation of all of my code, however.

I.e.

if old_version:
   print 'hey, upgrade.'
else:
  # main body of whole script

In the above implementation, the main body of the whole script would need to be indented one level and that's just messy.

Is there a better way?

like image 259
eastydude5 Avatar asked Dec 08 '25 10:12

eastydude5


1 Answers

You can do

import sys

if old_version:
    print 'hey, upgrade.'
    sys.exit(1)  # A non-zero code indicates failure, on Unix (sys.exit() exits too, but it returns a 0 [=success] exit code)

# main body of whole script

This exits the interpreter if the code needs to be upgraded.

The reason for returning a non-zero exit code is that if your program is called from a Unix shell script and an upgrade is necessary, the shell will detect that there was problem and the user will know about it (instead of your program failing silently).

PS: As suggested in an answer which is now deleted, you can also do sys.exit("hey, upgrade"), instead. This automatically returns an exit code of 1, as is appropriate.

like image 104
Eric O Lebigot Avatar answered Dec 10 '25 00:12

Eric O Lebigot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!