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

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

def uppercase(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return fn(*args, **kwargs).upper()
    return wrapped

# Order matters. You can't call .upper() on a list
@split
@uppercase 
def CallFunction():
    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:

def uppercase(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        result = fn(*args, **kwargs)
        if isinstance(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"