Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

Print function parameter names and values in Python

When a function is called, I would like to print the names and values of it's parameters. Something like:

>>> def foo(bar, baz):
>>>    magic_parameter_printing() 
bar=0, baz=None

Right now I use format:

print("bar={},baz={}".format(bar,baz))

But this is a pain as new parameters get added, and there's always the risk of missing something.

I found this answer which can work for single variables when you know what they are (and uses eval), but I'd really like to be able to do it for all parameters a function is passed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After you've add explanation how you want to apply this, I think best way will be to use decorator. It's more universal solution, because you can add it to any function in your code and it will print all debug info if debug mode is on.

Code:

from functools import wraps

DEBUG = True

def debug_log(function):
    @wraps(function)
    def wrapper(*args, **kwargs):
        if DEBUG:
            print(">> Called", function.__name__, "
",
                {**dict(zip(function.__code__.co_varnames, args)), **kwargs})
        result = function(*args, **kwargs)
        if DEBUG:
            print(">>", function.__name__, "return:
", result)
        return result
    return wrapper

@debug_log
def first_example(a, b, c):
    return 100

@debug_log
def second_example(d, e, f):
    return 200

first_example(10, 11, 12)
first_example(c=12, a=10, b=11)
second_example(13, 14, 15)
second_example(e=14, d=13, f=15)
DEBUG = False
first_example(0, 0, 0)
second_example(1, 1, 1)

Output:

>> Called first_example 
 {'a': 10, 'b': 11, 'c': 12}
>> first_example return:
 100
>> Called first_example 
 {'c': 12, 'a': 10, 'b': 11}
>> first_example return:
 100
>> Called second_example 
 {'d': 13, 'e': 14, 'f': 15}
>> second_example return:
 200
>> Called second_example 
 {'e': 14, 'd': 13, 'f': 15}
>> second_example return:
 200

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...