Enable ++x and --x expressions in Python

Overview

plusplus

PyPI version CI status Codecov

Enable ++x and --x expressions in Python

What's this?

By default, Python supports neither pre-increments (like ++x) nor post-increments (like x++). However, the first ones are syntactically correct since Python parses them as two subsequent +x operations, where + is the unary plus operator (same with --x and the unary minus). They both have no effect, since in practice -(-x) == +(+x) == x.

This module turns the ++x-like expressions into x += 1 at the bytecode level. Increments and decrements of collection items and object attributes are supported as well, for example:

dictionary = {'key': 42}
++dictionary['key']
assert dictionary['key'] == 43

Unlike x += 1, ++x is still an expression, so the increments work fine inside other expressions, if/while conditions, lambda functions, and list/dict comprehensions:

array[++index] = new_value

if --connection.num_users == 0:
    connection.close()

button.add_click_callback(lambda: ++counter)

index = 0
indexed_cells = {++index: cell for row in table for cell in row}

See tests for more sophisticated examples.

[How it works] [Installation]

Why?

This module is made for fun, as a demonstration of Python flexibility and bytecode manipulation techniques. Note that enabling increments in real projects may be risky: such code may confuse new developers and behave differently if copied to environments without the plusplus module. Also, this feature gives more opportunities to write unreadable code in general.

Nevertheless, there are situations where increments (if used with care) may allow to avoid repetitions or make code more readable. Some of them are listed here with the examples from the source code of the Python standard library.

Also, having the increment expressions seems consistent with PEP 572 "Assignment Expressions" that introduced the x := value expressions in Python 3.8+. They can be used inside if/while conditions and lambda functions as well.

How it works?

Patching bytecode

Python compiles all source code to a low-level bytecode executed on the Python's stack-based virtual machine. Each bytecode instruction consumes a few items from the stack, does something with them, and pushes the results back to the stack.

The ++x expressions are compiled into two consecutive UNARY_POSITIVE instructions that do not save the intermediate result in between (same with --x and two UNARY_NEGATIVE instructions). No other expressions produce a similar bytecode pattern.

plusplus replaces these patterns with the bytecode for x += 1, then adds the bytecode for storing the resulting value to the place where the initial value was taken.

This is what happens for the y = ++x line:

A similar but more complex transformation happens for the code with subscription expressions like value = ++dictionary['key']. We need the instructions from the yellow boxes to save the initial location and recall it when the increment is done (see the explanation below):

This bytecode is similar to what the string dictionary['key'] += 1 compiles to. The only difference is that it keeps an extra copy of the incremented value, so we can return it from the expression and assign it to the value variable.

Arguably, the least clear part here is the second yellow box. Actually, it is only needed to reorder the top 4 items of the stack. If we need to reorder the top 2 or 3 items of the stack, we can just use the ROT_TWO and ROT_THREE instructions (they do a circular shift of the specified number of items of the stack). If we had a ROT_FOUR instruction, we would be able to just replace the second yellow box with two ROT_FOURs to achieve the desired order.

However, ROT_FOUR was removed in Python 3.2 (since it was rarely used by the compiler) and recovered back only in Python 3.8. If we want to support Python 3.3 - 3.7, we need to use a workaround, e.g. the BUILD_TUPLE and UNPACK_SEQUENCE instructions. The first one replaces the top N items of the stack with a tuple made of these N items. The second unpacks the tuple putting the values on the stack right-to-left, i.e. in reverse order. We use them to reverse the top 4 items, then swap the top two to achieve the desired order.

[Source code]

The @enable_increments decorator

The first way to enable the increments is to use a decorator that would patch the bytecode of a given function.

The decorator disassembles the bytecode, patches the patterns described above, and recursively calls itself for any nested bytecode objects (this way, the nested function and class definitions are also patched).

The bytecode is disassembled and assembled back using the MatthieuDartiailh/bytecode library.

[Source code]

Enabling increments in the whole package

The Python import system allows loading modules not only from files but from any reasonable place (e.g. there was a module that enables importing code from Stack Overflow answers). The only thing you need is to provide module contents, including its bytecode.

We can leverage this to implement a wrapping loader that imports the module as usual but patching its bytecode as described above. To do this, we can create a new MetaPathFinder and install it to sys.meta_path.

[Source code]

Why not just override unary plus operator?

  • This way, it would be impossible to distinguish applying two unary operators consequently (like ++x) from applying them in separate places of a program (like in the snippet below). It is important to not change behavior in the latter case.

    x = -value
    y = -x
  • Overriding operators via magic methods (such as __pos__() and __neg__()) do not work for built-in Python types like int, float, etc. In contrast, plusplus works with all built-in and user-defined types.

Caveats

  • pytest does its own bytecode modifications in tests, adding the code to save intermediate expression results to the assert statements. This is necessary to show these results if the test fails (see pytest docs).

    By default, this breaks the plusplus patcher because the two UNARY_POSITIVE instructions become separated by the code saving the result of the first UNARY_POSITIVE.

    We fix that by removing the code saving some of the intermediate results, which does not break the pytest introspection.

    [Source code]

How to use it?

You can install this module with pip:

pip install plusplus

For a particular function or method

Add a decorator:

from plusplus import enable_increments

@enable_increments
def increment_and_return(x):
    return ++x

This enables increments for all code inside the function, including nested function and class definitions.

For all code in your package

In package/__init__.py, make this call before you import submodules:

from plusplus import enable_increments

enable_increments(__name__)

# Import submodules here
...

This enables increments in the submodules, but not in the package/__init__.py code itself.

Other ideas

The same approach could be used to implement the assignment expressions for the Python versions that don't support them. For example, we could replace the x <-- value expressions (two unary minuses + one comparison) with actual assignments (setting x to value).

See also

  • cpmoptimize — a module that optimizes a Python code calculating linear recurrences, reducing the time complexity from O(n) to O(log n).
  • dontasq — a module that adds functional-style methods (such as .where(), .group_by(), .order_by()) to built-in Python collections.

Authors

Copyright © 2021 Alexander Borzunov

Owner
Alexander Borzunov
Building hivemind for @learning-at-home // ex⁠-⁠research engineer at Yandex Self-Driving, ex⁠-⁠intern at Facebook
Alexander Borzunov
Format Norminette Output!

Format Norminette Output!

7 Apr 19, 2022
Python bytecode manipulation and import process customization to do evil stuff with format strings. Nasty!

formathack Python bytecode manipulation and import process customization to do evil stuff with format strings. Nasty! This is an answer to a StackOver

Michiel Van den Berghe 5 Jan 18, 2022
Tool to produce system call tables from Linux source code.

Syscalls Tool to generate system call tables from the linux source tree. Example The following will produce a markdown (.md) file containing the table

7 Jul 30, 2022
Standard implementations of FedLab and its provided benchmarks.

FedLab-benchmarks This repo contains standard implementations of FedLab and its provided benchmarks. Currently, following algorithms or benchrmarks ar

SMILELab-FL 104 Dec 05, 2022
[P]ython [w]rited [B]inary [C]onverter

pwbinaryc [P]ython [w]rited [Binary] [C]onverter You have rights to: Modify the code and use it private (friends are allowed too) Make a page and redi

0 Jun 21, 2022
Extract XML from the OS X dictionaries.

Extract XML from the OS X dictionaries.

Joshua Olson 13 Dec 11, 2022
Python utility for discovering interesting CFPreferences values on iDevices

Description Simple utility to search for interesting preferences in iDevices. Installation python3 -m pip install -U --user cfprefsmon Example In this

12 Aug 19, 2022
Animation retargeting tool for Autodesk Maya. Retargets mocap to a custom rig with a few clicks.

Animation Retargeting Tool for Maya A tool for transferring animation data and mocap from a skeleton to a custom rig in Autodesk Maya. Installation: A

Joaen 63 Jan 06, 2023
PyResToolbox - A collection of Reservoir Engineering Utilities

pyrestoolbox A collection of Reservoir Engineering Utilities This set of functio

Mark W. Burgoyne 39 Oct 17, 2022
A fancy and practical functional tools

Funcy A collection of fancy functional tools focused on practicality. Inspired by clojure, underscore and my own abstractions. Keep reading to get an

Alexander Schepanovski 2.9k Jan 07, 2023
🌲 A simple BST (Binary Search Tree) generator written in python

Tree-Traversals (BST) 🌲 A simple BST (Binary Search Tree) generator written in python Installation Use the package manager pip to install BST. Usage

Jan Kupczyk 1 Dec 12, 2021
A simple tool to move and rename Nvidia Share recordings to a more sensible format.

A simple tool to move and rename Nvidia Share recordings to a more sensible format.

Jasper Rebane 8 Dec 23, 2022
✨ Un bot Twitter totalement fait en Python par moi, et en français.

Twitter Bot ❗ Un bot Twitter totalement fait en Python par moi, et en français. Il faut remplacer auth = tweepy.OAuthHandler(consumer_key, consumer_se

MrGabin 3 Jun 06, 2021
Course-parsing - Parsing Course Info for NIT Kurukshetra

Parsing Course Info for NIT Kurukshetra Overview This repository houses code for

Saksham Mittal 3 Feb 03, 2022
🚧Useful shortcuts for simple task on windows

Windows Manager A tool containg useful utilities for performing simple shortcut tasks on Windows 10 OS. Features Lit Up - Turns up screen brightness t

Olawale Oyeyipo 0 Mar 24, 2022
A simple gpsd client and python library.

gpsdclient A small and simple gpsd client and library Installation Needs Python 3 (no other dependencies). If you want to use the library, use pip: pi

Thomas Feldmann 33 Nov 24, 2022
💉 코로나 잔여백신 예약 매크로 커스텀 빌드 (속도 향상 버전)

Korea-Covid-19-Vaccine-Reservation 코로나 잔여 백신 예약 매크로를 기반으로 한 커스텀 빌드입니다. 더 빠른 백신 예약을 목표로 하며, 속도를 우선하기 때문에 사용자는 이에 대처가 가능해야 합니다. 지정한 좌표 내 대기중인 병원에서 잔여 백신

Queue.ri 21 Aug 15, 2022
A small python tool to get relevant values from SRI invoices

SriInvoiceProcessing A small python tool to get relevant values from SRI invoices Some useful info to run the tool Login into your SRI account and ret

Wladymir Brborich 2 Jan 07, 2022
Parse URLs for DOIs, PubMed identifiers, PMC identifiers, arXiv identifiers, etc.

citation-url Parse URLs for DOIs, PubMed identifiers, PMC identifiers, arXiv identifiers, etc. This module has a single parse() function that takes in

Charles Tapley Hoyt 2 Feb 12, 2022
osqueryIR is an artifact collection tool for Linux systems.

osqueryIR osqueryIR is an artifact collection tool for Linux systems. It provides the following capabilities: Execute osquery SQL queries Collect file

AbdulRhman Alfaifi 7 Nov 02, 2022