Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement tracing #170

Closed
abrichr opened this issue May 25, 2023 · 1 comment
Closed

Implement tracing #170

abrichr opened this issue May 25, 2023 · 1 comment
Assignees

Comments

@abrichr
Copy link
Member

abrichr commented May 25, 2023

Simplify debugging: https://blog.koehntopp.info/2023/03/14/tracing-python.html

@abrichr
Copy link
Member Author

abrichr commented May 27, 2023

From https://blog.koehntopp.info/2023/03/14/tracing-python.html :

import functools


def args_to_str(*args):
    return ", ".join(map(str, args))


def kwargs_to_str(**kwargs):
    ret = ""
    for k, v in kwargs.items():
        ret += f"{k}={v},"

    return ret[:-1]


def logging(func):
    func.__indent__ = 0

    @functools.wraps(func)
    def wrapper_logging(*args, **kwargs):
        func_indent = " " * func.__indent__
        func.__indent__ += 2

        func_name = func.__qualname__
        func_args = args_to_str(*args)
        func_kwargs = kwargs_to_str(**kwargs)

        print(f"{func_indent} -> Enter: {func_name}({func_args}", end="")
        if func_kwargs != "":
            print(f", {func_kwargs}", end="")
        print(")")

        result = func(*args, **kwargs)

        print(f"{func_indent} <- Leave: {func_name}({result})")
        return result

    return wrapper_logging


@logging
def fac(n: int) -> int:
    if n == 1:
        return 1
    else:
        return n * fac(n - 1)


if __name__ == '__main__':
    result = fac(3)
    print(f"{result=}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants