gaogaotiantian / objprint

A library that can print Python objects in human readable format
Apache License 2.0
519 stars 43 forks source link

Add argname feature #50

Closed gaogaotiantian closed 2 years ago

codecov-commenter commented 2 years ago

:warning: Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 100.00%. Comparing base (792603a) to head (1c6fad7). Report is 23 commits behind head on master.

:exclamation: Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #50 +/- ## ========================================= Coverage 100.00% 100.00% ========================================= Files 4 5 +1 Lines 229 297 +68 ========================================= + Hits 229 297 +68 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

liqimai commented 2 years ago

I found that we could get the first argument by node.args[0], which is quite convenient.

Minimal example:

import inspect
import executing
# from objprint import op
import ast

def print_first_arg(*args,**kwargs):
    call_frame = inspect.currentframe().f_back
    Executing = executing.Source.executing(call_frame)
    # op(call_frame)
    # op(Executing.source, depth=2)
    # op(Executing.node, depth=2)
    # op(inspect.getsource(inspect.getmodule(call_frame)), depth=1)

    first_arg = ast.get_source_segment(
        Executing.source.text, 
        Executing.node.args[0]
    )

    print(f"{first_arg = }")

print_first_arg([1, 2, 3], 2,3)