Giter Site home page Giter Site logo

saurabh0719 / constable Goto Github PK

View Code? Open in Web Editor NEW
90.0 1.0 1.0 69 KB

Constable lets you be lazy by inserting prints directly into your AST for stateful debugging :man_juggling:

Home Page: https://pypi.org/project/constable

License: MIT License

Python 100.00%
debug debugging-tool decorators python

constable's Introduction


📝 This is an experimental project that tweaks the AST. Use at your own risk in mission-critical environments, or with unknown agents, as compiling and executing code during runtime can cause unwanted side effects. For all use cases that matter, use pdb instead.


If you find yourself aimlessly adding ✨ print ✨ statements while debugging your code, this is for you. 🤝

Constable inserts print statements directly into the AST at runtime to print variable assignments and other details.

It turns this 🔽 ....

@constable.trace('a', 'b')
def do_something(a, b):
    a = a + b

.... into this 🔽 during runtime

# During runtime, print statements will be added for every assignment on 'a' & 'b'.
# Resulting in something like -
def do_something(a, b):
    a = a + b
    print(f"wowww i wonder who put this print here! a = {a}")

See the examples below

$ pip install constable

How does it work?

The constable.trace decorator uses Python's Abstract Syntax Tree (AST) in much the same way we add print(s) to debug states. During runtime, it prepares and inserts print statements into the function's AST after every assignment operation (ast.Assign, ast.AugAssign and ast.AnnAssign), and then executes the modified code in a separate namespace with exec.

Print variable assignments and execution info.

Monitor the state of specified variables at each assignment operation with a step-by-step view of variable changes!

import constable

@constable.trace('a', 'b')
def example(a, b):
    a = a + b
    c = a
    a = "Experimenting with the AST"
    b = c + b
    a = c + b
    return a

example(5, 6)

Output -

constable: example: line 5
    a = a + b
    a = 11
    type(a) = <class 'int'>

constable: example: line 7
    a = "Experimenting with the AST"
    a = Experimenting with the AST
    type(a) = <class 'str'>

constable: example: line 8
    b = c + b
    b = 17
    type(b) = <class 'int'>

constable: example: line 9
    a = c + b
    a = 28
    type(a) = <class 'int'>

constable: example: line 3 to 10
    args: (5, 6)
    kwargs: {}
    returned: 28
    execution time: 0.00018480 seconds

You can also use it on its own to track function execution info.

import constable

@constable.trace()
def add(a, b):
    return a + b

add(5, 6)

Output -

constable: add: line 3 to 5
    args: (5, 6)
    kwargs: {}
    returned: 11
    execution time: 0.00004312 seconds

@trace

The trace function is the decorator to add print statements into the AST.

def trace(
    *variables,
    exec_info=True,
    verbose=True,
    use_spaces=True,
    max_len=None,
):
    """
    An experimental decorator for tracing function execution using AST.

    Args:
        variables (list): List of variable names to trace.
        exec_info (bool, optional): Whether to print execution info.
        verbose (bool, optional): Whether to print detailed trace info.
        use_spaces (bool, optional): Whether to add empty lines for readability.
        max_len (int, optional): Max length of printed values. Truncates if exceeded.

    Returns:
        function: Decorator for function tracing.
    """

constable's People

Contributors

saurabh0719 avatar

Stargazers

Jagrit Thapar avatar Gabriel avatar  avatar  avatar Paul Rignall avatar Josh Cook avatar Andreas Jung avatar Likianta Me avatar Becky Sweger avatar Shoumik Chowdhury avatar  avatar MCanavarros avatar Allainclair Flausino dos Santos avatar Anton Alekseev avatar Latin avatar Billy Rowell avatar Josh Thomas avatar Jeff Triplett avatar Daniel Andrlik avatar Roman avatar Dennis McGregor avatar elucida avatar Serlus avatar Murage avatar William Jamir Silva avatar Larry Ogrodnek avatar José Diaz Seng avatar Wei Lee avatar  avatar Connor Ferster avatar Joshua Luckey avatar Jagannath A avatar Michael Prather avatar Bobo Jamson avatar Josix avatar Greg Sheppard avatar Farbod Parvin avatar  avatar Ryan Seeley avatar Jerry Wu avatar  avatar Andy Shapiro avatar Tom Faulkner avatar Martin Collado avatar Gregory M. Kapfhammer avatar Harald Nezbeda avatar Gaël Écorchard avatar Jackie avatar Vincent avatar Sena avatar 修昊 avatar Zoom.Quiet avatar Yakov Till avatar Antoine Perrin--Delort avatar Rob Hulley avatar Vincent Besançon avatar August Masquelier avatar Arryn Pidwell avatar  avatar  avatar Piero Viscone avatar devdanzin avatar Tim Vergenz avatar Kian Bay avatar  avatar  avatar Jacob Chapman avatar  avatar Perry Bhandal avatar Jan Parzydło avatar  avatar  avatar Bruno Rocha avatar Ron Green avatar Christian Scheer avatar Greesb avatar Vijay Vammi avatar Emily Hunt avatar Adam Dekan avatar Kevin avatar  avatar Dhruvajyoti Sarma avatar Janrey Licas avatar David Rosenberg avatar  avatar  avatar Harsh Vardhan Gautam avatar Akhil Anil avatar Abhishek Singh Dhadwal avatar Aditya Kotwal avatar

Watchers

 avatar

Forkers

adityakotwal100

constable's Issues

Exception with static method

Started using constable and loving it so far.

I have however noticed that constable seems to have issues with static methods. The following sample code produces an exception:

import constable


class Test:

    @staticmethod
    @constable.trace("a", "b", "c")
    def add(a: int, b: int) -> int:
        c = a + b
        return c


d = Test.add(a=1, b=2)
print(f"{d=}")

Following is the traceback when running the above code:

/home/mark/wip/feed2fedi/.venv/bin/python /home/mark/.config/JetBrains/PyCharmCE2024.1/scratches/constable_scratch.py 
Traceback (most recent call last):
  File "/home/mark/.config/JetBrains/PyCharmCE2024.1/scratches/constable_scratch.py", line 11, in <module>
    d = Test.add(a=1, b=2)
        ^^^^^^^^^^^^^^^^^^
  File "/home/mark/wip/feed2fedi/.venv/lib/python3.12/site-packages/constable/__init__.py", line 228, in wrapper
    ret = executor.execute()
          ^^^^^^^^^^^^^^^^^^
  File "/home/mark/wip/feed2fedi/.venv/lib/python3.12/site-packages/constable/__init__.py", line 190, in execute
    result = fn(*self.fn_wrapper.args, **self.fn_wrapper.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/mark/wip/feed2fedi/.venv/lib/python3.12/site-packages/constable/__init__.py", line 225, in wrapper
    fn_wrapper = FunctionWrapper(func, args, kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/mark/wip/feed2fedi/.venv/lib/python3.12/site-packages/constable/__init__.py", line 43, in __init__
    self.source_code_lines = inspect.getsource(func).splitlines()
                             ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/mark/.rye/py/[email protected]/install/lib/python3.12/inspect.py", line 1282, in getsource
    lines, lnum = getsourcelines(object)
                  ^^^^^^^^^^^^^^^^^^^^^^
  File "/home/mark/.rye/py/[email protected]/install/lib/python3.12/inspect.py", line 1264, in getsourcelines
    lines, lnum = findsource(object)
                  ^^^^^^^^^^^^^^^^^^
  File "/home/mark/.rye/py/[email protected]/install/lib/python3.12/inspect.py", line 1093, in findsource
    raise OSError('could not get source code')
OSError: could not get source code

Process finished with exit code 1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.