extending the break statement

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Wed Oct 22 11:59:59 EDT 2003


anton muhin wrote:

> Michele Simionato wrote:
> 
>> Is there a way of "ending" a module? I would like something like this:
>>
>>   # mod.py
>>   print 'something here'
>>   end() # some mysterious function
>>   print 'you should not get here'
>>
>>   # main.py
>>   import mod
>>   print 'it works'
>>
>> I cannot use 'sys.exit' in place of ``end()``, since it would exit 
>> from the whole program and the line 'it works' would not be printed. I 
>> know that I can modify the main program to catch the SystemExit
>> exception:
>>
>>
>> # main.py
>> try:   import mod
>> except SystemExit:   pass
>> print 'it works'
>>
>> but I find it really ugly, since I am forced to change by hand all the 
>> scripts importing 'mod'. Moreover, I am abusing ``SystemExit``;
>> I should add instead a new built-in exception ``EndModule``, but this 
>> requires even more lines of code for something that should be trivial.
>>
>> On the other hand, I don't like the ``if 0:`` option, i.e. writing 
>> ``mod.py`` in the form
>>
>>   # mod.py
>>   print 'something here'
>>   end() # some mysterious function
>>   if 0:
>>       print 'you should not get here'
>>
>> since it requires re-indenting by hand the (potentially long) block
>> of code to be commented out. Yes, I know about C-c->, but honestly
>> it is a PITA. Typically, I would like to comment out portions of
>> experimental code during debugging; that code will enter in the final 
>> program at the end, so I must indent and re-indent it until it works 
>> (which means lots of times).
>>
>> More in general, one could think of an ``end()`` function with the 
>> ability of
>> stopping the execution of the current frame and going back to the 
>> previous
>> frame. One could even terminate classes in this way, i.e. skipping all 
>> the
>> methods defined after the ``end()``
>>
>> .... (some time passes) ...
>>
>> BTW, I have just realized that we don't need a new ``end()`` function: 
>> it would be enough to extend the ``break`` statement. Currently, it 
>> works only inside loops, why not to extend it to terminate classes and 
>> modules? IMHO, it would be
>> very useful during debugging and refactoring. What do you people 
>> think? Or is there already same magic which can do what I ask for?
>> If not, take it as a feature request ;-)
>>
>>
>> Michele Simionato, Ph. D.
>> MicheleSimionato at libero.it
>> http://www.phyast.pitt.edu/~micheles/
>> ---- Currently looking for a job ----
> 
> 
> As a hack:
> 
> for _ in "_":
>     print "here"
>     break
>     print "there"
> 
> Ugly, but it works.
> 
> hth,
> anton.
> 

And it might be better to do something like this (althoug more verbose):

if __name__ == "__main__":
    def stand_alone():
        print "here"
        return
        print "there"
    stand_alone()

hth,
anton.





More information about the Python-list mailing list