-
-
Save IQAndreas/7540305 to your computer and use it in GitHub Desktop.
| try: | |
| state = "initializing" | |
| read_configs() | |
| state = "downloading" | |
| files = get_files() | |
| state = "importing" | |
| import_files(files) | |
| state = "complete" | |
| exception: | |
| if (state == "importing"): | |
| print("WARNING: The script quit before it finished importing. You may have incomplete files stored on the server") | |
| else: | |
| print("Script quit unexpectedly. Please notify the developer"); | |
While legal, it's considered bad form to put parens around
ifandwhileloops;
Really? It's like Python developers have a morbid fear of extra characters (they really seem to hate people who use semicolons).
Thanks for the information regarding exceptions (it was actually mainly for KeyboardInterrupt that I was planning to use the state system). I will take that information into account.
On that topic, is it better to wrap the entire script in a try: or use sys.excepthook for cases like this?
Looks just fine! I'd personally use strings to make debugging easier (ie, so that I can just print state.current to see "initializing" instead of 1).
It would also be a good idea to get used to typing class foo(object):, because if you leave out the (object), you'll hit a few strange edge cases (see also: http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python )
And it's not so much a fear of extra characters as it is a strong preference for having One Way To Do Things… the idea is that, for any problem, there should be one obvious way to do it; if two equally experienced developers are solving a specific problem, the code they write should be fairly similar… and this extends to syntax, too.
I've never seen sys.excepthook used. Generally I'll stick all the code in a top-level function, then wrap the call to that function in try/except:
def main():
args = parse_args()
try:
run(args)
except MyException:
print "oh no"And sometimes I'll have something like:
def run(args):
try:
return _run(args)
except MyException:
return "oh no there was an error"So that I don't need to have an entire function indented inside a try block.
Thanks for the help!
It was for such a small script, that I ended going with the class-based system just to avoid forcing users to have python 3.4+ (I myself only have 3.3 on my system despite automatic updates), or having to install the extra modules.
I'll likely change those to strings later, or even implement some sort of "sub-state/state-category" system, but unless you see anything wrong with the current way, it should do for now.