Introduction:
In Python, sometimes while running a code we might encounter an error, AttributeError: 'str' object has no attribute 'sort'. AttributeError exception may occur if we try to access a non-existent attribute or call a method that doesn't exist for a particular object. To avoid getting such attribute errors , we must use correct methods pertaining to each datatype and also access only existing properties.
Python, Object-Oriented Programming and Attributes
In this article, we will dig deep into the error. We will first try to understand some fundamentals briefly related to this error like Object Oriented Programming, and Attributes of Objects in the context of Python
Python and Object Oriented Programming
Python being an Object-Oriented Programming language, almost everything is an “Object” in Python.
Let us try to understand this by running a simple Python code.
print(type("apple"))
print(type(12))
print(type(True))
print(type(str))
print(type(type))
print(type(None))
print(type(print))
Output
<class 'str'>
<class 'int'>
<class 'bool'>
<class 'type'>
<class 'type'>
<class 'NoneType'>
<class 'builtin_function_or_method'>
As we can figure out by now integers, strings, Booleans (True, False), classes (int, str, bool etc.), None, and functions (print etc.) are all Objects which belong to classes in Python.
Understanding Attributes:
Classes and instances both have attributes.
In python both the methods of a class/instance as well as the properties associated with them are considered attributes.
Let us now explore the Attributes of an example class and its instance in Python. This can be done by using the dir() function:
Let us first define a class
class Theme:
def __init__(self, name, pattern):
self.name = name
self.pattern = pattern
def print_theme_name(self):
print("The theme of this design is " + self.name)
Let us now create an instance of this class:
flowerPattern = Theme("Sunflower", "floral")
Now let us explore the attributes of the class "Theme"
dir(Theme)
Output:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'print_theme_name']
As we can see, the method 'print_theme_name' is an attribute of the class "Themes". But also note that, 'name' and 'pattern' being declared inside the __init__() function are not attributes of the class.
Similarly lets explore the attributes of the Instance (flowerPattern ) of class(Theme)
dir(flowerPattern)
Output:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'name',
'pattern',
'print_theme_name']
'name', 'pattern' and 'print_theme_name' are all attributes of the instance 'flowerPattern'
Attributes can be accessed by using the Dot notation.
For example we can access the value of flowerPattern attributes using the dot notation
flowerPattern.name
Output:
'Sunflower'
Another attribute __dict__ when accessed returns the attributes created for that specific class or instance .
`__dict__` does not list down the inherited attributes.
flowerPattern.__dict__
Output
{'name': 'Sunflower', 'pattern': 'floral'}
Given the understanding of the above concepts , we are now ready to decipher the error.
What is the cause of this error?
AttributeError is one of the many exceptions that can be raised by Python. According to the Python documentation AttributeError is Raised when an attribute reference or assignment fails. As we see further in the article, this specific error AttributeError: 'str' object has no attribute 'sort' is related to the incorrect usage of method sort() on strings.
Let us first look at the attributes of the class 'str ', using the dir() function
dir(str)
Did you find 'sort' in the list of attributes ?
The answer is No.
String does not have a method or a property by the name of 'sort'
Hence, this error will occur when we try to access the attribute “sort” for any instance of type : str.
Let us examine certain examples to demonstrate the error:
Example 1: sort() attempted on "string" datatype
alphastring = "avcdesnmoqb"
alphastring.sort()
Output:
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15728/1586940030.py in <module>
1 ##Solution
2 alphastring = "avcdesnmoqb"
----> 3 alphastring.sort()
AttributeError: 'str' object has no attribute 'sort'
'alphastring' is a string and string object does not have a method by the name of sort that can be executed
Example 2: sort() attempted on the return value of a function that returns "string" datatype
random_list = input("enter a random list of names")
enter a random list of names["aa", "bb", "cc"]
random_list.sort()
We ask the user to input a list. We then try sorting the list. But we get an error:
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15728/655224613.py in <module>
----> 1 random_list.sort()
AttributeError: 'str' object has no attribute 'sort'
input() is a function which returns the value entered by the user in the form of a string. Hence this error
Always check the spelling as well as the case of letters in the spelling of the attribute or method name. Python is case-sensitive, so even the wrong case can cause an AttributeError.
Solution
So, what do we do in a scenario when we wish to sort a string.
Let's see two ways of achieving the same.
Solution 1: Converting to list using list() function
List objects have the method sort() which can be used to sort the list. The list can then be converted back to a string using the join() method.
alphastring = "avcdesnmoqb"
my_sorted_list = list(alphastring)
my_sorted_list.sort()
sorted_alphastring = "".join(my_sorted_list)
sorted_alphastring
Output:
'abcdemnoqsv'
Solution 2: Using sorted() function
sorted() function can be used on the string itself, reconverting the sorted list back to string using the join() method
alphastring = "avcdesnmoqb"
sorted_alphastring = "".join(sorted(alphastring))
sorted_alphastring
Output:
'abcdemnoqsv'
Conclusion:
Encountering an Attribute error like 'str' object has no attribute 'sort' signifies that we have incorrectly used an attribute which does not belong to the datatype. So the next time we ever run into such an error, it will always be beneficial to explore the attributes associated with the datatype using the dir() function. I hope this article helps you understand as well as troubleshoot the error.
Additional Exercise
With this understanding, we all are definitely equipped with the tools to debug similar errors like :
my_list = ["a","b","c","d"]
my_list.isalpha()
Output:
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15728/3537005621.py in <module>
1 my_list = ["a","b","c","d"]
----> 2 my_list.isalpha()
AttributeError: 'list' object has no attribute 'isalpha'
Let's try debugging the same on our own.