extending the break statement

M

Michele Simionato

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.
(e-mail address removed)
http://www.phyast.pitt.edu/~micheles/
---- Currently looking for a job ----
 
A

anton muhin

Michele said:
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.
(e-mail address removed)
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.
 
A

anton muhin

anton said:
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.
 
D

Daniel Dittmar

Michele said:
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'
[snipped part about not wanting to indent/dedent etc.)

Put the whole module into an if:

if 1:
print 'something here'
# want to break here
print 'you should not get here'

You can then insert
if 0:
anywhere in the module to skip the rest without having to indent anything.

You can even insert another
if 1:
later to exclude only part of the module.

The same works in classes, where you also wanted a break statement.

Daniel
 
B

Bengt Richter

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 ;-)
I wonder if one couldn't get more bang for the change-buck by breaking the
1:1 module:file relationship. I.e., if there were a way to delimit multiple
modules in a single file, then you could use that mechanism to make a dummy module
segment that would be ignored unless specifically imported one way or another.

E.g.,
====< some_module.py >========================
"""Normal module source in this section works as usual"""
....
....

# the next line here creates a package style textually nested/embedded module definition
module embedded_module: <long-delimiter-string-a-la-mime>

def this(): pass
class That(object): pass

<long-delimiter-string-a-la-mime>
# the previous line ended the embedded module definition, and here
# it's optionally possible to continue with the normal outermost module source
================================================


Thus to do what you wanted to do, just define a dummy embedded module like

#...
#... (your clean code in progress here)
#...

module dummy: some-unique-delimiter-string

#XXX# get to this later ...
Any unfinished scraps etc that might have errors or whatever
can go here
So you could use this to "comment out" the tail of

some-unique-delimiter-string

This would solve your problem (I think) and might make a new package format possible.
E.g., you could import file_level_module.textually_nested_module etc. something like
importing from a zip file. I might be a handy way to structure mini-packages.

How a module might best refer to its own embedded modules (imported or not) I don't know...
though they ought to be visible via sys.modules through its own name.

BTW, I had the notion that importing ought to be generalized to create a usable module by
any means whatever, including compiling a foreign language source and creating an extension
DLL from and importing that, etc., of course caching as usual via sys.modules.

Such a generalized importing mechanism would logically also cover ordinary Python, but then
I see an opportunity to control it with optimization and/or debugging control parameters passed
to the import. Also possibly version-specific directives. IOW, import would become a general
dynamic way of getting current-version-compatible modules into the current run time environment
using any sources and translations etc. one could conceive. Adapting to embedded-module style
files via this would be a simple variant of the general idea.

Regards,
Bengt Richter
 
T

Terry Reedy

Michele Simionato said:
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'
"""

This assuming that you do not use both types of triple quotes in the
part you want to comment out. Compiler dumps bare string literals.

Terry J. Reedy
 
J

Jeremy Fincher

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'

# mod.py
print 'something here'
'''
print 'you should not get here'
'''

Just use triple-quote strings to "comment it out."

Jeremy
 
M

Michele Simionato

# mod.py
print 'something here'
'''
print 'you should not get here'
'''

Just use triple-quote strings to "comment it out."

Jeremy

I am unhappy with this solution. Very often (and especially in the
case of experimental blocks of code) I use triple quoted docstrings
as comments, saying what the code should do and where is the problem,
so hopefully when I will go back to this code I will be able to fix
it. So my typical situation is


"""A block of working code"""

def working_function_with__limited_functionality:
...

### <<=== I would like a good "break here!"

def experimental_function_which_will_be_better_once_finished:


"""This does not work because...."""


def helper_function1:
...


def helper_function2:

....


"""remember to refactor helper_function1,
improve helper_function2, etc. etc.
"""

As you see, not ideal for the triple quoted string idea. Besides, I
don't like it. A ``break`` could be conditionally enabled according to
some condition and would be much nicer. Moreover, I don't see why 'break'
must be so limited; for instance, sometimes it would come handy to
exit from and if..elif.. block with a 'break'.
I don't think there would be any real difficulty in making 'break'
a general escaping construct, with the ability to escape at the end
of the current block of code (therefore ending the program when used
in the main script). Am I correct or I am missing some technicality?

One could argue that the use case is not so common, but it comes handy
sometime and it does not clutter at all the language (actually we
could avoid questions from newbies asking why 'break' does not
work in certain cases). I also remember somebody here
advicing a newbie to use 'break' in an 'if' statement! This was
corrected, of course, but it is a trap one can easily fall in.


Michele
 
H

Hung Jung Lu

I am unhappy with this solution. Very often (and especially in the
case of experimental blocks of code) I use triple quoted docstrings
as comments, ...

"""A block of working code"""
...
As you see, not ideal for the triple quoted string idea.

??? You mean you have not tried '''...''' ???

Hung Jung

PS- The triple question marks are not from Python: they are from me.
:) In Spanish I'd use the upside ones to make a perfect enclosure.
:)
 
D

Derrick 'dman' Hudson

Michele Simionato said:
(e-mail address removed) (Jeremy Fincher) wrote in message
[...]
Just use triple-quote strings to "comment it out."

I am unhappy with this solution. Very often (and especially in the
case of experimental blocks of code) I use triple quoted docstrings

You should use docstrings, and triple-quoting them is fine. Just
change which quote character you use. Both """foo""" and '''foo'''
are equivalent strings.

Alternatively, use a good editor and putting real comment markers in
is not a hassle in the least. For example, if you want to use vim,
press 'v' to switch from command to visual mode. Move to the end of
the section you want to comment out and type
:%s/^/#/
and the whole section will be commented out. To undo this at a later
date, use visual mode to reselect the area and type
:%s/^#//

Any decent editor (such as emacs, for example) has this feature,
though the exact keystrokes to achieve it may differ.

(Notice: this is a tool problem, not a language problem!)

-D

--
Micros~1 :
For when quality, reliability
and security just aren't
that important!

http://dman13.dyndns.org/~dman/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top