executing


Nameexecuting JSON
Version 2.1.0 PyPI version JSON
download
home_pagehttps://github.com/alexmojaki/executing
SummaryGet the currently executing AST node of a frame, and other information
upload_time2024-09-01 12:37:35
maintainerNone
docs_urlNone
authorAlex Hall
requires_python>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # executing

[![Build Status](https://github.com/alexmojaki/executing/workflows/Tests/badge.svg?branch=master)](https://github.com/alexmojaki/executing/actions) [![Coverage Status](https://coveralls.io/repos/github/alexmojaki/executing/badge.svg?branch=master)](https://coveralls.io/github/alexmojaki/executing?branch=master) [![Supports Python versions 3.5+, including PyPy](https://img.shields.io/pypi/pyversions/executing.svg)](https://pypi.python.org/pypi/executing)

This mini-package lets you get information about what a frame is currently doing, particularly the AST node being executed.

* [Usage](#usage)
    * [Getting the AST node](#getting-the-ast-node)
    * [Getting the source code of the node](#getting-the-source-code-of-the-node)
    * [Getting the `__qualname__` of the current function](#getting-the-__qualname__-of-the-current-function)
    * [The Source class](#the-source-class)
* [Installation](#installation)
* [How does it work?](#how-does-it-work)
* [Is it reliable?](#is-it-reliable)
* [Which nodes can it identify?](#which-nodes-can-it-identify)
* [Libraries that use this](#libraries-that-use-this)

## Usage

### Getting the AST node

```python
import executing

node = executing.Source.executing(frame).node
```

Then `node` will be an AST node (from the `ast` standard library module) or None if the node couldn't be identified (which may happen often and should always be checked).

`node` will always be the same instance for multiple calls with frames at the same point of execution.

If you have a traceback object, pass it directly to `Source.executing()` rather than the `tb_frame` attribute to get the correct node.

### Getting the source code of the node

For this you will need to separately install the [`asttokens`](https://github.com/gristlabs/asttokens) library, then obtain an `ASTTokens` object:

```python
executing.Source.executing(frame).source.asttokens()
```

or:

```python
executing.Source.for_frame(frame).asttokens()
```

or use one of the convenience methods:

```python
executing.Source.executing(frame).text()
executing.Source.executing(frame).text_range()
```

### Getting the `__qualname__` of the current function

```python
executing.Source.executing(frame).code_qualname()
```

or:

```python
executing.Source.for_frame(frame).code_qualname(frame.f_code)
```

### The `Source` class

Everything goes through the `Source` class. Only one instance of the class is created for each filename. Subclassing it to add more attributes on creation or methods is recommended. The classmethods such as `executing` will respect this. See the source code and docstrings for more detail.

## Installation

    pip install executing

If you don't like that you can just copy the file `executing.py`, there are no dependencies (but of course you won't get updates).

## How does it work?

Suppose the frame is executing this line:

```python
self.foo(bar.x)
```

and in particular it's currently obtaining the attribute `self.foo`. Looking at the bytecode, specifically `frame.f_code.co_code[frame.f_lasti]`, we can tell that it's loading an attribute, but it's not obvious which one. We can narrow down the statement being executed using `frame.f_lineno` and find the two `ast.Attribute` nodes representing `self.foo` and `bar.x`. How do we find out which one it is, without recreating the entire compiler in Python?

The trick is to modify the AST slightly for each candidate expression and observe the changes in the bytecode instructions. We change the AST to this:

```python
(self.foo ** 'longuniqueconstant')(bar.x)
```
    
and compile it, and the bytecode will be almost the same but there will be two new instructions:

    LOAD_CONST 'longuniqueconstant'
    BINARY_POWER

and just before that will be a `LOAD_ATTR` instruction corresponding to `self.foo`. Seeing that it's in the same position as the original instruction lets us know we've found our match.

## Is it reliable?

Yes - if it identifies a node, you can trust that it's identified the correct one. The tests are very thorough - in addition to unit tests which check various situations directly, there are property tests against a large number of files (see the filenames printed in [this build](https://travis-ci.org/alexmojaki/executing/jobs/557970457)) with real code. Specifically, for each file, the tests:
 
 1. Identify as many nodes as possible from all the bytecode instructions in the file, and assert that they are all distinct
 2. Find all the nodes that should be identifiable, and assert that they were indeed identified somewhere

In other words, it shows that there is a one-to-one mapping between the nodes and the instructions that can be handled. This leaves very little room for a bug to creep in.

Furthermore, `executing` checks that the instructions compiled from the modified AST exactly match the original code save for a few small known exceptions. This accounts for all the quirks and optimisations in the interpreter. 

## Which nodes can it identify?

Currently it works in almost all cases for the following `ast` nodes:
 
 - `Call`, e.g. `self.foo(bar)`
 - `Attribute`, e.g. `point.x`
 - `Subscript`, e.g. `lst[1]`
 - `BinOp`, e.g. `x + y` (doesn't include `and` and `or`)
 - `UnaryOp`, e.g. `-n` (includes `not` but only works sometimes)
 - `Compare` e.g. `a < b` (not for chains such as `0 < p < 1`)

The plan is to extend to more operations in the future.

## Projects that use this

### My Projects

- **[`stack_data`](https://github.com/alexmojaki/stack_data)**: Extracts data from stack frames and tracebacks, particularly to display more useful tracebacks than the default. Also uses another related library of mine: **[`pure_eval`](https://github.com/alexmojaki/pure_eval)**.
- **[`futurecoder`](https://futurecoder.io/)**: Highlights the executing node in tracebacks using `executing` via `stack_data`, and provides debugging with `snoop`.
- **[`snoop`](https://github.com/alexmojaki/snoop)**: A feature-rich and convenient debugging library. Uses `executing` to show the operation which caused an exception and to allow the `pp` function to display the source of its arguments.
- **[`heartrate`](https://github.com/alexmojaki/heartrate)**: A simple real time visualisation of the execution of a Python program. Uses `executing` to highlight currently executing operations, particularly in each frame of the stack trace.
- **[`sorcery`](https://github.com/alexmojaki/sorcery)**: Dark magic delights in Python. Uses `executing` to let special callables called spells know where they're being called from.

### Projects I've contributed to

- **[`IPython`](https://github.com/ipython/ipython/pull/12150)**: Highlights the executing node in tracebacks using `executing` via [`stack_data`](https://github.com/alexmojaki/stack_data).
- **[`icecream`](https://github.com/gruns/icecream)**: 🍦 Sweet and creamy print debugging. Uses `executing` to identify where `ic` is called and print its arguments.
- **[`friendly_traceback`](https://github.com/friendly-traceback/friendly-traceback)**: Uses `stack_data` and `executing` to pinpoint the cause of errors and provide helpful explanations.
- **[`python-devtools`](https://github.com/samuelcolvin/python-devtools)**: Uses `executing` for print debugging similar to `icecream`.
- **[`sentry_sdk`](https://github.com/getsentry/sentry-python)**: Add the integration `sentry_sdk.integrations.executingExecutingIntegration()` to show the function `__qualname__` in each frame in sentry events.
- **[`varname`](https://github.com/pwwang/python-varname)**: Dark magics about variable names in python. Uses `executing` to find where its various magical functions like `varname` and `nameof` are called from.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/alexmojaki/executing",
    "name": "executing",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Alex Hall",
    "author_email": "alex.mojaki@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/8c/e3/7d45f492c2c4a0e8e0fad57d081a7c8a0286cdd86372b070cca1ec0caa1e/executing-2.1.0.tar.gz",
    "platform": null,
    "description": "# executing\n\n[![Build Status](https://github.com/alexmojaki/executing/workflows/Tests/badge.svg?branch=master)](https://github.com/alexmojaki/executing/actions) [![Coverage Status](https://coveralls.io/repos/github/alexmojaki/executing/badge.svg?branch=master)](https://coveralls.io/github/alexmojaki/executing?branch=master) [![Supports Python versions 3.5+, including PyPy](https://img.shields.io/pypi/pyversions/executing.svg)](https://pypi.python.org/pypi/executing)\n\nThis mini-package lets you get information about what a frame is currently doing, particularly the AST node being executed.\n\n* [Usage](#usage)\n    * [Getting the AST node](#getting-the-ast-node)\n    * [Getting the source code of the node](#getting-the-source-code-of-the-node)\n    * [Getting the `__qualname__` of the current function](#getting-the-__qualname__-of-the-current-function)\n    * [The Source class](#the-source-class)\n* [Installation](#installation)\n* [How does it work?](#how-does-it-work)\n* [Is it reliable?](#is-it-reliable)\n* [Which nodes can it identify?](#which-nodes-can-it-identify)\n* [Libraries that use this](#libraries-that-use-this)\n\n## Usage\n\n### Getting the AST node\n\n```python\nimport executing\n\nnode = executing.Source.executing(frame).node\n```\n\nThen `node` will be an AST node (from the `ast` standard library module) or None if the node couldn't be identified (which may happen often and should always be checked).\n\n`node` will always be the same instance for multiple calls with frames at the same point of execution.\n\nIf you have a traceback object, pass it directly to `Source.executing()` rather than the `tb_frame` attribute to get the correct node.\n\n### Getting the source code of the node\n\nFor this you will need to separately install the [`asttokens`](https://github.com/gristlabs/asttokens) library, then obtain an `ASTTokens` object:\n\n```python\nexecuting.Source.executing(frame).source.asttokens()\n```\n\nor:\n\n```python\nexecuting.Source.for_frame(frame).asttokens()\n```\n\nor use one of the convenience methods:\n\n```python\nexecuting.Source.executing(frame).text()\nexecuting.Source.executing(frame).text_range()\n```\n\n### Getting the `__qualname__` of the current function\n\n```python\nexecuting.Source.executing(frame).code_qualname()\n```\n\nor:\n\n```python\nexecuting.Source.for_frame(frame).code_qualname(frame.f_code)\n```\n\n### The `Source` class\n\nEverything goes through the `Source` class. Only one instance of the class is created for each filename. Subclassing it to add more attributes on creation or methods is recommended. The classmethods such as `executing` will respect this. See the source code and docstrings for more detail.\n\n## Installation\n\n    pip install executing\n\nIf you don't like that you can just copy the file `executing.py`, there are no dependencies (but of course you won't get updates).\n\n## How does it work?\n\nSuppose the frame is executing this line:\n\n```python\nself.foo(bar.x)\n```\n\nand in particular it's currently obtaining the attribute `self.foo`. Looking at the bytecode, specifically `frame.f_code.co_code[frame.f_lasti]`, we can tell that it's loading an attribute, but it's not obvious which one. We can narrow down the statement being executed using `frame.f_lineno` and find the two `ast.Attribute` nodes representing `self.foo` and `bar.x`. How do we find out which one it is, without recreating the entire compiler in Python?\n\nThe trick is to modify the AST slightly for each candidate expression and observe the changes in the bytecode instructions. We change the AST to this:\n\n```python\n(self.foo ** 'longuniqueconstant')(bar.x)\n```\n    \nand compile it, and the bytecode will be almost the same but there will be two new instructions:\n\n    LOAD_CONST 'longuniqueconstant'\n    BINARY_POWER\n\nand just before that will be a `LOAD_ATTR` instruction corresponding to `self.foo`. Seeing that it's in the same position as the original instruction lets us know we've found our match.\n\n## Is it reliable?\n\nYes - if it identifies a node, you can trust that it's identified the correct one. The tests are very thorough - in addition to unit tests which check various situations directly, there are property tests against a large number of files (see the filenames printed in [this build](https://travis-ci.org/alexmojaki/executing/jobs/557970457)) with real code. Specifically, for each file, the tests:\n \n 1. Identify as many nodes as possible from all the bytecode instructions in the file, and assert that they are all distinct\n 2. Find all the nodes that should be identifiable, and assert that they were indeed identified somewhere\n\nIn other words, it shows that there is a one-to-one mapping between the nodes and the instructions that can be handled. This leaves very little room for a bug to creep in.\n\nFurthermore, `executing` checks that the instructions compiled from the modified AST exactly match the original code save for a few small known exceptions. This accounts for all the quirks and optimisations in the interpreter. \n\n## Which nodes can it identify?\n\nCurrently it works in almost all cases for the following `ast` nodes:\n \n - `Call`, e.g. `self.foo(bar)`\n - `Attribute`, e.g. `point.x`\n - `Subscript`, e.g. `lst[1]`\n - `BinOp`, e.g. `x + y` (doesn't include `and` and `or`)\n - `UnaryOp`, e.g. `-n` (includes `not` but only works sometimes)\n - `Compare` e.g. `a < b` (not for chains such as `0 < p < 1`)\n\nThe plan is to extend to more operations in the future.\n\n## Projects that use this\n\n### My Projects\n\n- **[`stack_data`](https://github.com/alexmojaki/stack_data)**: Extracts data from stack frames and tracebacks, particularly to display more useful tracebacks than the default. Also uses another related library of mine: **[`pure_eval`](https://github.com/alexmojaki/pure_eval)**.\n- **[`futurecoder`](https://futurecoder.io/)**: Highlights the executing node in tracebacks using `executing` via `stack_data`, and provides debugging with `snoop`.\n- **[`snoop`](https://github.com/alexmojaki/snoop)**: A feature-rich and convenient debugging library. Uses `executing` to show the operation which caused an exception and to allow the `pp` function to display the source of its arguments.\n- **[`heartrate`](https://github.com/alexmojaki/heartrate)**: A simple real time visualisation of the execution of a Python program. Uses `executing` to highlight currently executing operations, particularly in each frame of the stack trace.\n- **[`sorcery`](https://github.com/alexmojaki/sorcery)**: Dark magic delights in Python. Uses `executing` to let special callables called spells know where they're being called from.\n\n### Projects I've contributed to\n\n- **[`IPython`](https://github.com/ipython/ipython/pull/12150)**: Highlights the executing node in tracebacks using `executing` via [`stack_data`](https://github.com/alexmojaki/stack_data).\n- **[`icecream`](https://github.com/gruns/icecream)**: \ud83c\udf66 Sweet and creamy print debugging. Uses `executing` to identify where `ic` is called and print its arguments.\n- **[`friendly_traceback`](https://github.com/friendly-traceback/friendly-traceback)**: Uses `stack_data` and `executing` to pinpoint the cause of errors and provide helpful explanations.\n- **[`python-devtools`](https://github.com/samuelcolvin/python-devtools)**: Uses `executing` for print debugging similar to `icecream`.\n- **[`sentry_sdk`](https://github.com/getsentry/sentry-python)**: Add the integration `sentry_sdk.integrations.executingExecutingIntegration()` to show the function `__qualname__` in each frame in sentry events.\n- **[`varname`](https://github.com/pwwang/python-varname)**: Dark magics about variable names in python. Uses `executing` to find where its various magical functions like `varname` and `nameof` are called from.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Get the currently executing AST node of a frame, and other information",
    "version": "2.1.0",
    "project_urls": {
        "Homepage": "https://github.com/alexmojaki/executing"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b5fdafcd0496feca3276f509df3dbd5dae726fcc756f1a08d9e25abe1733f962",
                "md5": "99bcfdc77ecdd522bf2fee68c9d32f78",
                "sha256": "8d63781349375b5ebccc3142f4b30350c0cd9c79f921cde38be2be4637e98eaf"
            },
            "downloads": -1,
            "filename": "executing-2.1.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "99bcfdc77ecdd522bf2fee68c9d32f78",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": ">=3.8",
            "size": 25805,
            "upload_time": "2024-09-01T12:37:33",
            "upload_time_iso_8601": "2024-09-01T12:37:33.007621Z",
            "url": "https://files.pythonhosted.org/packages/b5/fd/afcd0496feca3276f509df3dbd5dae726fcc756f1a08d9e25abe1733f962/executing-2.1.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8ce37d45f492c2c4a0e8e0fad57d081a7c8a0286cdd86372b070cca1ec0caa1e",
                "md5": "e64dd9916bb0a6c89f88295f4867c1b6",
                "sha256": "8ea27ddd260da8150fa5a708269c4a10e76161e2496ec3e587da9e3c0fe4b9ab"
            },
            "downloads": -1,
            "filename": "executing-2.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "e64dd9916bb0a6c89f88295f4867c1b6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 977485,
            "upload_time": "2024-09-01T12:37:35",
            "upload_time_iso_8601": "2024-09-01T12:37:35.708584Z",
            "url": "https://files.pythonhosted.org/packages/8c/e3/7d45f492c2c4a0e8e0fad57d081a7c8a0286cdd86372b070cca1ec0caa1e/executing-2.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-01 12:37:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "alexmojaki",
    "github_project": "executing",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "executing"
}
        
Elapsed time: 0.32531s