Skip to content

Instantly share code, notes, and snippets.

@IQAndreas
Created November 19, 2013 04:24
Show Gist options
  • Select an option

  • Save IQAndreas/7540305 to your computer and use it in GitHub Desktop.

Select an option

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");
@wolever

wolever commented Nov 19, 2013

Copy link
Copy Markdown

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.

@wolever

wolever commented Nov 19, 2013

Copy link
Copy Markdown

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment