Skip to main content

forcibly inline python functions to their call site

Project description

This is a Python hack to let you specify functions as “inline” in much the same way you’d do in C. You save the cost of a function call by inlining the code of the function right at the call site. Of course, being Python, the inlining is done at runtime.

WARNING: Don’t use this in any real code. Seriously. It’s just a fun hack.

Now then, suppose you have some code like this:

def calculate(x):
    return 3*x*x - 2*x + (1/x)

def aggregate(items):
    total = 0
    for item in items:
        total += calculate(item)
    return total

This code pays the overhead of a function call for every item in the collection. You can get substantial speedups by inlining the calculate function like so:

def aggregate(items):
    total = 0
    for x in items:
        total += 3*x*x - 2*x + (1/x)
    return total

But now you’re paying the costs in terms of code quality and re-use. To get the best of both worlds simply declare that the calculate function should be inlined:

from atinline import inline

@inline
def calculate(x):
    return 3*x*x - 2*x + (1/x)

def aggregate(items):
    total = 0
    for item in items:
        total += calculate(item)
    return total

Now the first time the aggregate() function runs, it will detect that the calculate() function should be inlined, make the necessary bytecode hacks to do so, then continue on its way. Any subsequent calls to aggregate() will avoid the overhead of many function calls.

Currently only plain calls of top-level functions are supported; things won’t work correctly if you try to inline methods, functions looked up in a dict, or other stuff like this. It also doesn’t work with keyword arguments. These limitations might go away in future.

The heavy-lifting of bytecode regeneration is done by the fantastic “byteplay” module, which is atinline’s only dependency.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

atinline-0.1.0.tar.gz (6.1 kB view details)

Uploaded Source

File details

Details for the file atinline-0.1.0.tar.gz.

File metadata

  • Download URL: atinline-0.1.0.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for atinline-0.1.0.tar.gz
Algorithm Hash digest
SHA256 5477bfcf1becae424e22cd9a4e5053fd8d1ce3d33b228eddfa529c0d27b323b2
MD5 5f526e901108fe6f4ae20575c1d3011a
BLAKE2b-256 ad24d385312b4a0447529e32eeb4ee12e0db4915dd3a919080dca9a972798a1c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page