The typeerror: function object is not subscriptable error generates because of using indexes while invoking functional object. Generally, Functions are callable object but not subscriptible. In this article, we will see the best ways to fix this error. We will also try to understand the situations where usually this error occurs. So Lets go !!
typeerror: function object is not subscriptable ( Root Cause ) –
Lets practically understand the context for this error.
def print_name(name): print(name) return name + " Data Science Learner " var=print_name
Here print_name is callable function. But we are not invoking it as function with parameter. IN the place of it we used index print_name. Hence when we run this code , we get function object is not subscriptable python error.
typeerror: function object is not subscriptable ( Solution ) –
The fix for this error is simple to avoid calling function using indexes. But you already know about it. So what next ? See lets simplify this for us with scenarios.-
Case 1: name ambiguity in function and iterable object –
This is one of the very common scenario for this error. Here we use the same name for function and iterable objects like ( list , dict, str etc) . If we declare the iterable object first and then function, so function will overwrite the iterable object type and throughs the same error.
print_name=[1,2,3] def print_name(name): print(name) return name + " Data Science Learner " var=print_name
Hence we should always provide unique name to each identifiers. If we follow this best practice, we will never get this kind of error.
Case 2 : avoiding functions returns with local assignment-
If any function is returning any iterable object but we are not assigning it into any local variable. Wile directly accessing it with indexes it throws the same type error. Lets see how –
To avoid this we can follow the the below way –
def fun(): data=[1,2,3] return data temp=fun() var=temp print(var)
Similar Errors :
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.