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(
Solution 1:
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 = Truedefdebug_log(function):
@wraps(function)defwrapper(*args, **kwargs):
if DEBUG:
print(">> Called", function.__name__, "\n",
{**dict(zip(function.__code__.co_varnames, args)), **kwargs})
result = function(*args, **kwargs)
if DEBUG:
print(">>", function.__name__, "return:\n", result)
return result
return wrapper
@debug_logdeffirst_example(a, b, c):
return100@debug_logdefsecond_example(d, e, f):
return200
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
Solution 2:
You could try to use func.__code__.co_varnames
like this:
def foo(bar, baz):
magic_parameter_printing()
bar=0
baz=None
forvarin foo.__code__.co_varnames:
print(var,'= ',eval(var))
Output:
bar=0baz=None
Post a Comment for "Print Function Parameter Names And Values In Python"