Code Explanation:
Line 1: def string_only(f):
Defines a decorator function called string_only.
It accepts a function f as an argument (this will be the function we want to "wrap").
Line 2: Define Inner Function wrap(x)
def wrap(x): return f(x) if isinstance(x, str) else "Invalid"
Defines a new function wrap(x) inside string_only.
This function:
Checks if the input x is a string using isinstance(x, str)
If x is a string → calls f(x)
If not → returns "Invalid"
Line 3: Return the Wrapped Function
return wrap
The string_only function returns the wrap function.
This means any function decorated with @string_only will now use this logic.
Line 4–5: Using the Decorator @string_only
@string_only
def echo(s): return s + s
This applies the string_only decorator to the echo function.
So this is equivalent to:
def echo(s): return s + s
echo = string_only(echo)
Now echo is not the original anymore — it’s the wrap function that does a type check first.
Line 6: Calling the Function with Non-String
print(echo(5))
5 is an int, not a string.
So inside wrap(x):
isinstance(5, str) is False
So it returns "Invalid"
Final Output:
Invalid
.png)

0 Comments:
Post a Comment