Most control structures in most most programming languages, including Python, are subordinating conjunctions, like "if", "while", and "except", although "with" is a preposition, and "for" is a preposition used strangely (although not as strangely as in C…).

But there's a whole spectrum of subordinating conjunctions that Python hasn't found a use for.

Negative subordinators

Some languages, most famously Perl, provide "unless" and "until".

While people do regularly propose these be added to Python, they don't really add much. Anything that could be written "unless condition: body" can just as readably be written "if not condition: body", so there's no real need to use up these keywords or make the grammar harder to fit into people's heads.

Besides, if we're going to have "unless" and "until", why not also negate the others, which are much harder to simulate in such a trivial way?

"without context: body" ensures that the context is exited before the body, instead of after. The security benefits of this should be obvious—you can't accidentally overwrite critical system files if you can be sure they're closed before you try to write them.

"try: body1 including E: body2" is hard to read directly as English—but then the same is true of "try: body1 except E: body 2". The best you can do is "try to body1, except if E happens somewhere, in which case body2 instead." Similarly, "try to body1, including if E happens somewhere, in which case body2 as well." Just as with "except", describing the semantics of "including" concretely is easier than trying to make it intuitive: it's a continuable exception handler, just like in the Common Lisp Condition System. And yes, this means that the exception handler runs in the scope that raised, not in the scope where it's defined, so it can be (ab)used for dynamic scoping. Have fun!

Finally, if the "for" statement runs the body once with each element of the iterable; the "butfor" statement obviously runs the body exactly once, with all of the elements that aren't in the iterable. Note that this provides a syntactic rather than library-driven way to force collection in non-refcounted implementations of Python.

Where or given

In mathematical proofs, and in even more abstract domains like Haskell programming, "where" is used to bind a variable for the duration of a single expression. Of course "let" does the same thing, but it's generally more readable to use "let" before the main expression for binding first-order values and "where" after the expression for binding function values, or occasionally very complicated first-order values whose expression isn't central to the main point.

PEP 3150 proposed adding this syntax to Python. However, because code written for NumPy, many SQL expression libraries, etc. tends to make extensive use of functions named "where", the PEP was changed to suggest the preposition "given" instead of "where".

Before and after

The most common use proposed for "before" and "after" is as prepositions (sometimes along with "around"), to add code that's executed before or after some function's body (e.g., to check pre- and post-conditions).

But as conjunctions, they could be used differently: whenever any assignment or other mutation would make the condition true, first any "before" bodies are executed, then the assignment is performed, then any "after" bodies are executed. If, after any of those bodies, the condition is no longer true (or going to be true, for mulitple "before" bodies), the rest aren't executed.

For example:

    before letter == 'k':
        letter = 'a'

    letter = 'a'
    for _ in range(26):
        letter = chr(ord(letter) + 1)
        print(letter, end='')

This would print out "abcdefghijabcdefghijabcdef".

This could even be used for cross-thread or -process synchronization. This is effectively like attaching callbacks to futures, but allowing you to treat any expression as a future.

This makes sense for dataflow languages, Make, maybe even Prolog-style languages… but does it make sense for Python?

Well, we do have similar features in many GUI libraries. For example, Tkinter allows you to attach a validation function that gets run before any change to an Entry widget, which can reject the change. Cocoa has spamWillFry: and spamDidFry: notifications. And so on.

The big problem with such features is that they're always implemented in an ad-hoc way. The API is radically different in each GUI library, and often not even complete. For example, Tkinter only has a "before", not an "after" (although attaching a variable and adding a trace callback can simulate that); its "before" only works on Entry widgets (and not, say, Text); and it has a bizarre interface.

Another problem is that you can only really watch a simple variable, not a complex expression. For example, if I wanted to do something after a+b > 10, I'd have to ask for notifications on both a and b and check their sum each time. Why can't the language do that for me?

And finally, a library has to be able to identify all the places that it might change whatever someone might be watching and remember to notify whoever is watching. Again, why can't the language do that for me?

Well, the obvious answer is that the language would have to monitor every single change to anything and check it against every registered "before" or "after" condition. In fact, most debuggers provide a simplified version of this, called "watchpoints", and, even with hardware support, it's often too slow to run your whole program with any watchpoints enabled.

But computers are getting faster all the time. Or at least more parallel. And this is one case where the very things that usually make parallelism more painful might instead be beneficial. The code could be triggered by cache coherence discipline, and CPU manufacturers already have no choice but to make cache coherence controllers very complicated and highly optimized or they'll break every C program ever written.

Whenever

There are two possible meanings to a "whenever" statement—but fortunately, they are not syntactically ambiguous.

"whenever condition: body" is similar to an "after" statement, except that rather than only executing its body the first time the condition becomes true, it executes its body every time the condition becomes true after having been false. It is well known that edge-triggered notifications are the most efficient way to implement reactor-type code, and that non-self-resetting notifications are easier to deal with than one-shot notifications, so this would almost certainly have uses in highly performant network code.

On the other hand, "whenever: body" with no condition simply asks that body be executed at some point. Presumably this would happen at the next "await" or "yield from", or, if for some reason someone has written a program that never uses either of those feature (maybe legacy code from Python 2.x), as an atexit handler.

Lest

While "lest" isn't used as commonly in modern English as it could be, there's really no good alternative synonym.

"lest condition: body" speculatively executes the body, then, only if that would make the condition true, commits it.

One of the problems with STM (software transactional management) is that most languages don't have very good syntax to press into service. While constructs like Python's "with" statement (or, in C++, a bare clause and an RAII constructor) can be used to represent a transaction, it's more than a little misleading, because normally a "with" statement's context manager cannot control the execution of the statement's body. A "lest" statement, on the other hand, is a perfect way to represent STM syntactically.

As If

Adding a two-keyword statement would probably be a little more controversial than some of the other proposals contained herein, but it has the advantage that both are already keywords. (If a single keyword were desired, "though" could be an option, though it's an archaic meaning, and likely to be confused with the more common meaning used in this very sentence.)

This is similar to the PEP 3150 "while"/"given" statement, but far more powerful: rather than just creating a temporary binding, this creates whatever changes are needed to temporarily make the condition true, then executed the body with those changes in effect, then reverts the changes.

For example, many students are assigned to create a Caesar cipher program, and they get as far as "letter = chr(ord(letter) + 1)", but then don't know how to prevent "z" from mapping to "{". This addition would make that task trivial:

    as if letter <= 'z':
        print(letter)

Of course in this case, it would be a matter of implementation quality whether a given Python interpreter printed "a", "z", or even a NUL character.

Because

In normal execution, "because condition: body" is similar to "if", except that it raises an exception if the condition is false instead of just skipping the body.

However, this can be used as a hook for semantic profilers. Instead of just blaming execution time on function calls, a semantic profiler can blame specific conditions. If the program spends 80% of its time executing code "because spam", then clearly the way to optimize it is to either make "spam" less likely, or, if that's not possible, to handle it more efficiently.

A because statement can also provide useful hints to a JIT compiler. The compiler can assume that the condition is true when deciding which code path to optimize, knowing that if it's not true an exception will be thrown.

It could also be useful to add a "whereas" statement, that has the same effect as "because" in normal execution, but has the opposite meaning to a semantic profiler.

Whenever

A "whenever" statement is similar to a "before" or "after" statement

 combined with a "while" statement. As soon as the condition becomes true, the body begins executing in a loop, in a new thread. until the condition becomes false.

So

"so condition: body" has elements of both "lest" and "whenever", but is potentially much more powerful.

At any point, if any condition (the same as "condition" or otherwise) is being checked for any statement, and "condition" is false, and "condition" being true would change the truth value of the condition being checked, "body" is run. If "condition" still remains false, an exception is raised.

Of course using a "so" statement in any program that also uses "before" and "after" is liable to cause severe performance problems, which would be hard to diagnose without judicious use of "because" statements. But surely that falls under "consenting adults", and anyone who cares about performance should be using Fortran anyway.

Implementation notes

Although I haven't yet tried creating patches for any of these new syntactic forms, it's worth considering that they are already handled in two languages closely related to Python (pseudocode and English), so there should be little trouble.
0

Add a comment

Hybrid Programming
Hybrid Programming
5
Greenlets vs. explicit coroutines
Greenlets vs. explicit coroutines
6
ABCs: What are they good for?
ABCs: What are they good for?
1
A standard assembly format for Python bytecode
A standard assembly format for Python bytecode
6
Unified call syntax
Unified call syntax
8
Why heapq isn't a type
Why heapq isn't a type
1
Unpacked Bytecode
Unpacked Bytecode
3
Everything is dynamic
Everything is dynamic
1
Wordcode
Wordcode
1
For-each loops should define a new variable
For-each loops should define a new variable
4
Views instead of iterators
Views instead of iterators
2
How lookup _could_ work
How lookup _could_ work
2
How lookup works
How lookup works
7
How functions work
How functions work
2
Why you can't have exact decimal math
Why you can't have exact decimal math
2
Can you customize method resolution order?
Can you customize method resolution order?
1
Prototype inheritance is inheritance
Prototype inheritance is inheritance
1
Pattern matching again
Pattern matching again
The best collections library design?
The best collections library design?
1
Leaks into the Enclosing Scope
Leaks into the Enclosing Scope
2
Iterable Terminology
Iterable Terminology
8
Creating a new sequence type is easy
Creating a new sequence type is easy
2
Going faster with NumPy
Going faster with NumPy
2
Why isn't asyncio too slow?
Why isn't asyncio too slow?
Hacking Python without hacking Python
Hacking Python without hacking Python
1
How to detect a valid integer literal
How to detect a valid integer literal
2
Operator sectioning for Python
Operator sectioning for Python
1
If you don't like exceptions, you don't like Python
If you don't like exceptions, you don't like Python
2
Spam, spam, spam, gouda, spam, and tulips
Spam, spam, spam, gouda, spam, and tulips
And now for something completely stupid…
And now for something completely stupid…
How not to overuse lambda
How not to overuse lambda
1
Why following idioms matters
Why following idioms matters
1
Cloning generators
Cloning generators
5
What belongs in the stdlib?
What belongs in the stdlib?
3
Augmented Assignments (a += b)
Augmented Assignments (a += b)
11
Statements and Expressions
Statements and Expressions
3
An Abbreviated Table of binary64 Values
An Abbreviated Table of binary64 Values
1
IEEE Floats and Python
IEEE Floats and Python
Subtyping and Ducks
Subtyping and Ducks
1
Greenlets, threads, and processes
Greenlets, threads, and processes
6
Why don't you want getters and setters?
Why don't you want getters and setters?
8
The (Updated) Truth About Unicode in Python
The (Updated) Truth About Unicode in Python
1
How do I make a recursive function iterative?
How do I make a recursive function iterative?
1
Sockets and multiprocessing
Sockets and multiprocessing
Micro-optimization and Python
Micro-optimization and Python
3
Why does my 100MB file take 1GB of memory?
Why does my 100MB file take 1GB of memory?
1
How to edit a file in-place
How to edit a file in-place
ADTs for Python
ADTs for Python
5
A pattern-matching case statement for Python
A pattern-matching case statement for Python
2
How strongly typed is Python?
How strongly typed is Python?
How do comprehensions work?
How do comprehensions work?
1
Reverse dictionary lookup and more, on beyond z
Reverse dictionary lookup and more, on beyond z
2
How to handle exceptions
How to handle exceptions
2
Three ways to read files
Three ways to read files
2
Lazy Python lists
Lazy Python lists
2
Lazy cons lists
Lazy cons lists
1
Lazy tuple unpacking
Lazy tuple unpacking
3
Getting atomic writes right
Getting atomic writes right
Suites, scopes, and lifetimes
Suites, scopes, and lifetimes
1
Swift-style map and filter views
Swift-style map and filter views
1
Inline (bytecode) assembly
Inline (bytecode) assembly
Why Python (or any decent language) doesn't need blocks
Why Python (or any decent language) doesn't need blocks
18
SortedContainers
SortedContainers
1
Fixing lambda
Fixing lambda
2
Arguments and parameters, under the covers
Arguments and parameters, under the covers
pip, extension modules, and distro packages
pip, extension modules, and distro packages
Python doesn't have encapsulation?
Python doesn't have encapsulation?
3
Grouping into runs of adjacent values
Grouping into runs of adjacent values
dbm: not just for Unix
dbm: not just for Unix
How to use your self
How to use your self
1
Tkinter validation
Tkinter validation
7
What's the deal with ttk.Frame.__init__(self, parent)
What's the deal with ttk.Frame.__init__(self, parent)
1
Does Python pass by value, or by reference?
Does Python pass by value, or by reference?
9
"if not exists" definitions
"if not exists" definitions
repr + eval = bad idea
repr + eval = bad idea
1
Solving callbacks for Python GUIs
Solving callbacks for Python GUIs
Why your GUI app freezes
Why your GUI app freezes
21
Using python.org binary installations with Xcode 5
Using python.org binary installations with Xcode 5
defaultdict vs. setdefault
defaultdict vs. setdefault
1
Lazy restartable iteration
Lazy restartable iteration
2
Arguments and parameters
Arguments and parameters
3
How grouper works
How grouper works
1
Comprehensions vs. map
Comprehensions vs. map
2
Basic thread pools
Basic thread pools
Sorted collections in the stdlib
Sorted collections in the stdlib
4
Mac environment variables
Mac environment variables
Syntactic takewhile?
Syntactic takewhile?
4
Can you optimize list(genexp)
Can you optimize list(genexp)
MISRA-C and Python
MISRA-C and Python
1
How to split your program in two
How to split your program in two
How methods work
How methods work
3
readlines considered silly
readlines considered silly
6
Comprehensions for dummies
Comprehensions for dummies
Sockets are byte streams, not message streams
Sockets are byte streams, not message streams
9
Why you don't want to dynamically create variables
Why you don't want to dynamically create variables
7
Why eval/exec is bad
Why eval/exec is bad
Iterator Pipelines
Iterator Pipelines
2
Why are non-mutating algorithms simpler to write in Python?
Why are non-mutating algorithms simpler to write in Python?
2
Sticking with Apple's Python 2.7
Sticking with Apple's Python 2.7
Blog Archive
About Me
About Me
Loading