Why does Python log a SyntaxWarning saying "object is not subscriptable"?2020-06-17
Take this code:
If we import its containing module in Python 3.8+, we’ll see a warning message on line 4:
This is a new warning added in Python 3.8. From the release notes:
When a comma is missed in code such as
[(10, 20) (30, 40)], the compiler displays a
SyntaxWarningwith a helpful suggestion. This improves on just having a
TypeErrorindicating that the first tuple was not callable. (Contributed by Serhiy Storchaka in bpo-15248.)
I covered the described case of a missing comma previously in its own post. The “object is not subscriptable” case is a bit of a bonus for this change, added in the same pull request.
Indeed, if we run the function, it raises a
Python emits the
SyntaxWarning at import time because it can predict that the code will raise this
So why does the error occur?
Some objects in Python are subscriptable, such as lists.
You normally “subscript” them with the syntax:
This will fetch a single element if you use a number as an index, such as
some_object, or a range of elements if you use a slice, such as
get_first_flavour() function uses this syntax incorrectly - it has the index and subscriptable object in the wrong positions.
We can fix the function by swapping them:
Then the function works as expected:
The “perhaps you missed a comma?” hint did not apply in the above example. It would apply in other cases, such as function call arguments. For example, if we had this code:
We meant to call
pick_some_flavours() with two arguments, an int and a list, but the comma between them is missing.
If we run this in the console, we see the syntax warning:
Here, the solution is to insert the comma between the two arguments:
Python raises this
SyntaxWarning for more types than just integers.
It also raises them for many built-in literal types:
- The ellipsis syntax
- Numbers -
- Set types -
frozent, and set comprehensions
- Generator expressions
You can see this on the console, for example with a set:
I hope this helps you understand and fix this error,
Are your Django project's tests slow? Read Speed Up Your Django Tests now!
One summary email a week, no spam, I pinky promise.
- Why does Python log a SyntaxWarning saying "object is not callable"?
- Why does Python log a SyntaxWarning for 'is' with literals?
- Why does Python log a SyntaxWarning saying "assertion is always true"?
- Why does Python log a SyntaxWarning saying "list indices must be integers or slices"?
© 2020 All rights reserved.