break in a module

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jun 16 20:48:01 EDT 2011


On Thu, 16 Jun 2011 15:07:23 -0700, Erik Max Francis wrote:

> Eric Snow wrote:
>>
>> The only ways that I know of to accomplish this currently is either by
>> putting everything inside if-else blocks, or raise some kind of
>> ImportBreak exception and catch it in an import hook.
> 
> You're still not elucidating a very clear use case here.  You want to do
> some tests and then break out of the top-level execution of the module
> if they happen.  Just use `sys.exit`.
> 
> It's still not clear _why_ this is useful.  As I said, the typical
> behavior of a module is to define a lot of things, perhaps building up
> some needed data structures, and then do the `__name__ == "__main__"`
> test to see if it's being executed as a script, and then _do_ something.


I'm not entirely sure that this is a *good* use case, but I think the use 
case that Eric Snow has in mind is something like this pseudo-code:

# === in module other.py which is not the main module ===

def spam(): pass

if some_condition: stop processing

def ham(): pass
def cheese(): pass
def salad(): pass


# === in the main module ===

import other

other.spam()  # always defined

try:
    other.ham
except AttributeError:
    print "there is no ham"



sys.exit would be inappropriate, because the intention is not to exit the 
entire application, but just to halt processing of the module. You could 
wrap the def cheese inside an if block, but if there's a lot of 
conditional code, then the majority of your module might be indented, 
which seems silly.

If Python had GOTOs this would be a perfect use-case for jumping to a 
label at the end of the file :)

Perhaps the most sensible alternative is conditional importing:

# === module extras.py ===

def ham(): pass
def cheese(): pass
def salad(): pass


# === module other.py ===

def spam(): pass

if not some_condition: from extras import *



-- 
Steven



More information about the Python-list mailing list