How create a decorator to get output information about the input and output arguments in python?

I have this function with the decorator validate_numeric to validate if the input arguments of a function are numeric (types int or float).

If any of the arguments passed to the function are not numeric, it should return a message: The input arguments must be numeric and stop execution. Otherwise, it should execute the decorated function normally.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
def validate_numeric(func): # Decorator
def wrapper(*args, **kwargs):
for arg in args:
if not isinstance(arg, (int, float)):
return "The input arguments must be numeric."
for key, value in kwargs.items():
if not isinstance(value, (int, float)):
return "The input arguments must be numeric."
return func(*args, **kwargs)
return wrapper
@validate_numeric
def sum(a, b): # Return the sum of two numbers
return a + b
print(sum(1, 2))
print(sum(1, "2"))
print(sum(a=1, b="a"))
print(sum(a=1, b=3.4))
</code>
<code> def validate_numeric(func): # Decorator def wrapper(*args, **kwargs): for arg in args: if not isinstance(arg, (int, float)): return "The input arguments must be numeric." for key, value in kwargs.items(): if not isinstance(value, (int, float)): return "The input arguments must be numeric." return func(*args, **kwargs) return wrapper @validate_numeric def sum(a, b): # Return the sum of two numbers return a + b print(sum(1, 2)) print(sum(1, "2")) print(sum(a=1, b="a")) print(sum(a=1, b=3.4)) </code>

def validate_numeric(func): # Decorator
    def wrapper(*args, **kwargs):
        for arg in args:
            if not isinstance(arg, (int, float)):
                return "The input arguments must be numeric."
        for key, value in kwargs.items():
            if not isinstance(value, (int, float)):
                return "The input arguments must be numeric."
        return func(*args, **kwargs)
    return wrapper

@validate_numeric
def sum(a, b): # Return the sum of two numbers
    return a + b


print(sum(1, 2))
print(sum(1, "2"))
print(sum(a=1, b="a"))
print(sum(a=1, b=3.4))

it is working fine, this is the output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>3
The input arguments must be numeric.
The input arguments must be numeric.
4.4
</code>
<code>3 The input arguments must be numeric. The input arguments must be numeric. 4.4 </code>
3
The input arguments must be numeric.
The input arguments must be numeric.
4.4

now, i need Keep the previous code and create an additional decorator named debug.

This will let us get some information on the execution of the function without having to add print all over the body of the function.

This decorator should simply output information about the input and output arguments. It should indicate both the positional and keyword arguments passed to the function and the output before returning it.

Use the following test cases:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@debug
def sum(a, b):
"""Return the sum of two numbers."""
return a + b
sum(1, 2)
sum(a=1, b=2)
sum(1, "a")
</code>
<code>@debug def sum(a, b): """Return the sum of two numbers.""" return a + b sum(1, 2) sum(a=1, b=2) sum(1, "a") </code>
@debug
def sum(a, b):
    """Return the sum of two numbers."""
    return a + b

sum(1, 2)
sum(a=1, b=2)
sum(1, "a")

Your result should look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>**********
Positional arguments: 1,2
There are no keyword arguments
Result: 3
**********
There are no positional arguments
Keyword arguments: a=1,b=2
Result: 3
**********
Positional arguments: 1,a
There are no keyword arguments
Result: The input arguments must be numeric
</code>
<code>********** Positional arguments: 1,2 There are no keyword arguments Result: 3 ********** There are no positional arguments Keyword arguments: a=1,b=2 Result: 3 ********** Positional arguments: 1,a There are no keyword arguments Result: The input arguments must be numeric </code>
**********
Positional arguments: 1,2
There are no keyword arguments
Result: 3
**********
There are no positional arguments
Keyword arguments: a=1,b=2
Result: 3
**********
Positional arguments: 1,a
There are no keyword arguments
Result: The input arguments must be numeric

I try to create this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def debug(func):
def wrapper(*args, **kwargs):
print(f"Function name: {func.__name__}")
print(f"Arguments: {args}")
print(f"Keyword arguments: {kwargs}")
return func(*args, **kwargs)
return wrapper
def validate_numeric(func):
def wrapper(*args, **kwargs):
for arg in args:
if not isinstance(arg, (int, float)):
return "The input arguments must be numeric."
for key, value in kwargs.items():
if not isinstance(value, (int, float)):
return "The input arguments must be numeric."
return func(*args, **kwargs)
return wrapper
@debug
def sum(a, b): #Return the sum of two numbers
return a + b
#1st case
print(sum(1, 2))
#2nd case
print(sum(a=1, b=2))
#3rd case
print(sum(1,"a"))
</code>
<code>def debug(func): def wrapper(*args, **kwargs): print(f"Function name: {func.__name__}") print(f"Arguments: {args}") print(f"Keyword arguments: {kwargs}") return func(*args, **kwargs) return wrapper def validate_numeric(func): def wrapper(*args, **kwargs): for arg in args: if not isinstance(arg, (int, float)): return "The input arguments must be numeric." for key, value in kwargs.items(): if not isinstance(value, (int, float)): return "The input arguments must be numeric." return func(*args, **kwargs) return wrapper @debug def sum(a, b): #Return the sum of two numbers return a + b #1st case print(sum(1, 2)) #2nd case print(sum(a=1, b=2)) #3rd case print(sum(1,"a")) </code>
def debug(func):
    def wrapper(*args, **kwargs):
        print(f"Function name: {func.__name__}")
        print(f"Arguments: {args}")
        print(f"Keyword arguments: {kwargs}")
        return func(*args, **kwargs)
    return wrapper


def validate_numeric(func):
    def wrapper(*args, **kwargs):
        for arg in args:
            if not isinstance(arg, (int, float)):
                return "The input arguments must be numeric."
        for key, value in kwargs.items():
            if not isinstance(value, (int, float)):
                return "The input arguments must be numeric."
        return func(*args, **kwargs)
    return wrapper


@debug
def sum(a, b): #Return the sum of two numbers
    return a + b

#1st case
print(sum(1,  2))
#2nd case
print(sum(a=1, b=2))
#3rd case
print(sum(1,"a"))

but i got and error with the 3rd case, i got this error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
Decorator @debug
********************************************************************************
Function name: sum
Arguments: (1, 2)
Keyword arguments: {}
3
********************************************************************************
Function name: sum
Arguments: ()
Keyword arguments: {'a': 1, 'b': 2}
3
********************************************************************************
Function name: sum
Arguments: (1, 'a')
Keyword arguments: {}
Traceback (most recent call last):
File ".../task-2.py", line 40, in <module>
print(sum(1,"a"))
File ".../task-2.py", line 14, in wrapper
return func(*args, **kwargs)
File ".../task-2.py", line 32, in sum
return a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>
<code> Decorator @debug ******************************************************************************** Function name: sum Arguments: (1, 2) Keyword arguments: {} 3 ******************************************************************************** Function name: sum Arguments: () Keyword arguments: {'a': 1, 'b': 2} 3 ******************************************************************************** Function name: sum Arguments: (1, 'a') Keyword arguments: {} Traceback (most recent call last): File ".../task-2.py", line 40, in <module> print(sum(1,"a")) File ".../task-2.py", line 14, in wrapper return func(*args, **kwargs) File ".../task-2.py", line 32, in sum return a + b TypeError: unsupported operand type(s) for +: 'int' and 'str' </code>

Decorator @debug
********************************************************************************
Function name: sum
Arguments: (1, 2)
Keyword arguments: {}
3
********************************************************************************
Function name: sum
Arguments: ()
Keyword arguments: {'a': 1, 'b': 2}
3
********************************************************************************
Function name: sum
Arguments: (1, 'a')
Keyword arguments: {}
Traceback (most recent call last):
  File ".../task-2.py", line 40, in <module>
    print(sum(1,"a"))
  File ".../task-2.py", line 14, in wrapper
    return func(*args, **kwargs)
  File ".../task-2.py", line 32, in sum
    return a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The output must be like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
**********
Positional arguments: 1,2
There are no keyword arguments
Result: 3
**********
There are no positional arguments
Keyword arguments: a=1,b=2
Result: 3
**********
Positional arguments: 1,a
There are no keyword arguments
Result: The input arguments must be numeric
</code>
<code> ********** Positional arguments: 1,2 There are no keyword arguments Result: 3 ********** There are no positional arguments Keyword arguments: a=1,b=2 Result: 3 ********** Positional arguments: 1,a There are no keyword arguments Result: The input arguments must be numeric </code>

**********
Positional arguments: 1,2
There are no keyword arguments
Result: 3
**********
There are no positional arguments
Keyword arguments: a=1,b=2
Result: 3
**********
Positional arguments: 1,a
There are no keyword arguments
Result: The input arguments must be numeric

New contributor

Julio Arana Jr. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật