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.

A Functional Addict is someone who regularly gets higher-order—sometimes they may even exhibit dependent types—but still manages to retain a job.

Retaining a job is of course the goal of all programming. This is why some of these new hybrid languages, like Rust, check all borrowing, from both paradigms, so extensively that you can make regular progress for months without ever successfully compiling your code, and your managers will appreciate that progress. After all, once it does compile, it will definitely work.

Closures

It's long been known that Closures are dual to Encapsulation.

As Abject-Oriented Programming explained, Encapsulation involves making all of your variables public, and ideally global, to let the rest of the code decide what should and shouldn't be private.

Closures, by contrast, are a way of referring to variables from outer scopes. And there is no scope more outer than global.

Immutability

One of the reasons Functional Addiction has become popular in recent years is that to truly take advantage of multi-core systems, you need immutable data, sometimes also called persistent data.

Instead of mutating a function to fix a bug, you should always make a new copy of that function. For example:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

When you discover that you actually wanted fields 2 and 3 rather than 1 and 2, it might be tempting to mutate the state of this function. But doing so is dangerous. The right answer is to make a copy, and then try to remember to use the copy instead of the original:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

function getCustName2(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[2] + ' ' + custRec[3];
    return fullname;
}

This means anyone still using the original function can continue to reference the old code, but as soon as it's no longer needed, it will be automatically garbage collected. (Automatic garbage collection isn't free, but it can be outsourced cheaply.)

Higher-Order Functions

In traditional Abject-Oriented Programming, you are required to give each function a name. But over time, the name of the function may drift away from what it actually does, making it as misleading as comments. Experience has shown that people will only keep once copy of their information up to date, and the CHANGES.TXT file is the right place for that.

Higher-Order Functions can solve this problem:

function []Functions = [
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[1] + ' ' + custRec[2];
        return fullname;
    },
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[2] + ' ' + custRec[3];
        return fullname;
    },
]

Now you can refer to this functions by order, so there's no need for names.

Parametric Polymorphism

Traditional languages offer Abject-Oriented Polymorphism and Ad-Hoc Polymorphism (also known as Overloading), but better languages also offer Parametric Polymorphism.

The key to Parametric Polymorphism is that the type of the output can be determined from the type of the inputs via Algebra. For example:

function getCustData(custId, x)
{
    if (x == int(x)) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return int(fullname);
    } else if (x.real == 0) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return double(fullname);
    } else {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return complex(fullname);
    }
}

Notice that we've called the variable x. This is how you know you're using Algebraic Data Types. The names y, z, and sometimes w are also Algebraic.

Type Inference

Languages that enable Functional Addiction often feature Type Inference. This means that the compiler can infer your typing without you having to be explicit:


function getCustName(custID)
{
    // WARNING: Make sure the DB is locked here or
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

We didn't specify what will happen if the DB is not locked. And that's fine, because the compiler will figure it out and insert code that corrupts the data, without us needing to tell it to!

By contrast, most Abject-Oriented languages are either nominally typed—meaning that you give names to all of your types instead of meanings—or dynamically typed—meaning that your variables are all unique individuals that can accomplish anything if they try.

Memoization

Memoization means caching the results of a function call:

function getCustName(custID)
{
    if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Non-Strictness

Non-Strictness is often confused with Laziness, but in fact Laziness is just one kind of Non-Strictness. Here's an example that compares two different forms of Non-Strictness:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRate(custId) {}

function callByNameTextRate(custId)
{
    /****************************************
    *
    * TO DO:
    *
    * get tax rate for the customer state
    * eventually from some table
    *
    ****************************************/
}

Both are Non-Strict, but the second one forces the compiler to actually compile the function just so we can Call it By Name. This causes code bloat. The Lazy version will be smaller and faster. Plus, Lazy programming allows us to create infinite recursion without making the program hang:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRateRecursive(custId) { lazyTaxRateRecursive(custId); }

Laziness is often combined with Memoization:

function getCustName(custID)
{
    // if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Outside the world of Functional Addicts, this same technique is often called Test-Driven Development. If enough tests can be embedded in the code to achieve 100% coverage, or at least a decent amount, your code is guaranteed to be safe. But because the tests are not compiled and executed in the normal run, or indeed ever, they don't affect performance or correctness.

Conclusion

Many people claim that the days of Abject-Oriented Programming are over. But this is pure hype. Functional Addiction and Abject Orientation are not actually at odds with each other, but instead complement each other.
5

View comments

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.