nobreak as a keyword¶
Somewhat similar to the function keyword example except
that we keep track of the indentation level and
replace our new keyword (
nobreak) only if
some conditions are met.
while loop include an
whose meaning is not immediately obvious:
while condition: # some # code # here else: # will be executed only if no # break statement occurred above
When I first understood this, I thought wouldn’t it be nice if, instead
else:, one could write something like
if not break: which
uses only existing Python keywords.
For this example, I decided instead that a suggestion made by Raymond Hettinger
nobreak as a keyword made the most sense.
It can be used instead of
else in the above example:
while condition: # some # code # here nobreak: # will be executed only if no # break statement occurred above
nobreak instead of
else keyword has a very different meaning when used as part
if statement. In this situation,
nobreak, or its
translation in some other language would make no sense.
As a result, if one attempts to write the following:
if condition: # some # code # here nobreak: # more code
nobreak will not be replaced by
the code will raise a
What about try/except?¶
else keyword can also be used in a
From Python’s documentation:
The optional else clause is executed if the control flow leaves the try suite, no exception was raised, and no
breakstatement was executed.
Since multiple causes can prevent the
else clause from being executed,
it makes little sense in this case to use a different keyword such as
nobreak, that would point to a specific cause which would likely be wrong.
From the following API generated by Sphinx, you can get access to the actual code which, by now, should be fairly straightforward to understand.
- This module enables someone to use
nobreakas a keyword
add_hook(show_original=False, show_transformed=False, verbose_finder=False)¶
Creates and automatically adds the import hook in sys.meta_path
nobreakis replaced by
elseonly if it is the first non-space token on a line and if its indentation matches that of a
transform_source(source, callback_params=None, **kwargs)¶
This function is called by the import hook loader with the named keyword that we specified when we created the import hook.
It gives us the option to compare the original source and the transformed one. This type of additional option can be useful when debugging a source transformer. Furthermore, if we wish to define a source transformation that combines the effect of multiple existing transformations, we can combine the existing “inner” functions to create our new transformation.