Search code examples
google-cloud-datalab

What is the best way to stop execution of a cell on a Google Datalab notebook?


I would like to halt the execution of a cell executing python commands on a Google Datalab notebook if certain conditions are met.

What is the preferred method to do this that doesn't affect the rest of the notebook?

if x:
   quit()

Will crash the notebook.


Solution

  • One potential solution is to wrap your code in a function and use return to exit early.

    def do_work():
      stopExecution = True
      if stopExecution:
         return
    
      print 'do not print'
    
    do_work()
    

    Another solution is to raise an exception:

    stopExecution = True
    if stopExecution:
       raise Exception('Done')
    
    print 'do not print'
    

    A better solution is to use the if statement to allow code execution, rather than block it. For example,

    if ShouldIContinueWorking():
       doWork()
    else:
       print 'Done' # do nothing (preferred) or return from function