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

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed. Languages in the Abject-Oriented space have been borrowing ideas from another paradigm entirely—and then everyone realized that languages like Python, Ruby, and JavaScript had been doing it for years and just hadn't noticed (because these languages do not require you to declare what you're doing, or even to know what you're doing). Meanwhile, new hybrid languages borrow freely from both paradigms.

This other paradigm—which is actually older, but was largely constrained to university basements until recent years—is called Functional Addiction.
5

I haven't posted anything new in a couple years (partly because I attempted to move to a different blogging platform where I could write everything in markdown instead of HTML but got frustrated—which I may attempt again), but I've had a few private comments and emails on some of the old posts, so I decided to do some followups.

A couple years ago, I wrote a blog post on greenlets, threads, and processes.
6

Looking before you leap

Python is a duck-typed language, and one where you usually trust EAFP ("Easier to Ask Forgiveness than Permission") over LBYL ("Look Before You Leap"). In Java or C#, you need "interfaces" all over the place; you can't pass something to a function unless it's an instance of a type that implements that interface; in Python, as long as your object has the methods and other attributes that the function needs, no matter what type it is, everything is good.
1

Background

Currently, CPython’s internal bytecode format stores instructions with no args as 1 byte, instructions with small args as 3 bytes, and instructions with large args as 6 bytes (actually, a 3-byte EXTENDED_ARG followed by a 3-byte real instruction). While bytecode is implementation-specific, many other implementations (PyPy, MicroPython, …) use CPython’s bytecode format, or variations on it.

Python exposes as much of this as possible to user code.
6

If you want to skip all the tl;dr and cut to the chase, jump to Concrete Proposal.

Why can’t we write list.len()? Dunder methods C++ Python Locals What raises on failure? Method objects What about set and delete? Data members Namespaces Bytecode details Lookup overrides Introspection C API Concrete proposal CPython Analysis

Why can’t we write list.len()?

Python is an OO language. To reverse a list, you call lst.reverse(); to search a list for an element, you call lst.index().
8

Many people, when they first discover the heapq module, have two questions:

Why does it define a bunch of functions instead of a container type? Why don't those functions take a key or reverse parameter, like all the other sorting-related stuff in Python? Why not a type?

At the abstract level, it's often easier to think of heaps as an algorithm rather than a data structure.
1

Currently, in CPython, if you want to process bytecode, either in C or in Python, it’s pretty complicated.

The built-in peephole optimizer has to do extra work fixing up jump targets and the line-number table, and just punts on many cases because they’re too hard to deal with. PEP 511 proposes a mechanism for registering third-party (or possibly stdlib) optimizers, and they’ll all have to do the same kind of work.
3

One common "advanced question" on places like StackOverflow and python-list is "how do I dynamically create a function/method/class/whatever"? The standard answer is: first, some caveats about why you probably don't want to do that, and then an explanation of the various ways to do it when you really do need to.

But really, creating functions, methods, classes, etc. in Python is always already dynamic.

Some cases of "I need a dynamic function" are just "Yeah? And you've already got one".
1

A few years ago, Cesare di Mauro created a project called WPython, a fork of CPython 2.6.4 that “brings many optimizations and refactorings”. The starting point of the project was replacing the bytecode with “wordcode”. However, there were a number of other changes on top of it.

I believe it’s possible that replacing the bytecode with wordcode would be useful on its own.
1

Many languages have a for-each loop. In some, like Python, it’s the only kind of for loop:

for i in range(10): print(i) In most languages, the loop variable is only in scope within the code controlled by the for loop,[1] except in languages that don’t have granular scopes at all, like Python.[2]

So, is that i a variable that gets updated each time through the loop or is it a new constant that gets defined each time through the loop?

Almost every language treats it as a reused variable.
4
Blog Archive
Loading