Skip to content Skip to sidebar Skip to footer

Why Typeerror: 'str' Object Is Not Callable Error Has Occurred In My Code

I am new to learning python, I know this kind questions asked before but i am not able to find any solutions for it. Please check my code and correct me about decorator's functiona

Solution 1:

Decorators are confusing and probably should be avoided till you are super experienced with python. That being said, chaining decorators is even more tricky:

from functools import wraps

defsplit(fn): # fn is the passed in function    @wraps(fn) # This means we can grabs its args and kwargsdefwrapped(*args, **kwargs): # This is the new function declarationreturn fn(*args, **kwargs).split()
    return wrapped

defuppercase(fn):
    @wraps(fn)defwrapped(*args, **kwargs):
        return fn(*args, **kwargs).upper()
    return wrapped

# Order matters. You can't call .upper() on a list@split@uppercase defCallFunction():
    return"my string was in lower case"

res = CallFunction()
print(res)

Alternatively if you don't want the order of these two decorators to matter than you need to handle the list case:

defuppercase(fn):
    @wraps(fn)defwrapped(*args, **kwargs):
        result = fn(*args, **kwargs)
        ifisinstance(result, list):
            return [x.upper() for x in result]
        return result.upper()
    return wrapped

Reference: How to make a chain of function decorators?

Post a Comment for "Why Typeerror: 'str' Object Is Not Callable Error Has Occurred In My Code"