While working with Python tuple, you may encounter this error: AttributeError 'tuple' object has no attribute 'get'
This is a common mistake we all do in the beginning of python learning.
The root cause of this error is the get() method/function you used in the python code.
The get() method is used to get elements from the collection, and Python allows this to get dictionary elements, not the tuple.
and that's why whenever you call this method with a tuple you get this error.
# Creating a tuple
color = ("GREEN", "RED", "BLUE")
# Accessing element
print(color.get(1))
Output:
Traceback (most recent call last):
File "<string>", line 6, in <module>
AttributeError: 'tuple' object has no attribute 'get'
So to get elements from the tuple use the indexing rather than the get() method.
# Creating a tuple
color = ("GREEN", "RED", "BLUE")
# Accessing element
print(color[0])
print(color[1])
print(color[2])
Output:
GREEN
RED
BLUE
Python tuple is a sequence-type data structure like list and range. So, use indexing only to access its elements.
One more scenario is if you are working with the Django framework where you are returning a tuple from the views.py file. For example,
if retailer_pk:
return (request, 'page-retailer-single.html', {
"products": products,
"sorting": filt["sorting"],
"filtering": filt["filtering"],
"retailer": retailer,
})
Here, you need to use the render() method whenever you are returning a tuple.
So, add the render() method to prevent the AttributeError tuple object has no attribute get error. See the solution code.
// views.py
if retailer_pk:
return render(request, 'page-retailer-single.html', {
"products": products,
"sorting": filt["sorting"],
"filtering": filt["filtering"],
"retailer": retailer,
})
The "AttributeError tuple object has no attribute get" error is common while working with the tuple. Since tuple does not allow this get() method so you must use indexing to access the elements. Even in Django, you must use the render() method to avoid any such error.