Fixing AttributeError: ‘module’ object has no attribute ‘setdefaultencoding’

AttributeError: ‘module’ object has no attribute ‘setdefaultencoding’ is an error which occurs when you use sys.setdefaultencoding() function in python 3 which should not be done.

In the blog post I attempt to explain why this error takes place and how you can solve it, I will also add other solutions that could solve the error if possible.

Exploring the AttributeError: ‘module’ object has no attribute ‘setdefaultencoding’

This is an error which occurs when you use sys.setdefaultencoding() function in python 3 which should not be done.

Please make sure the error message looks like the error message bellow after double checking. Do not mix between errors.

                                                                       #
sys.setdefaultencoding("utf-8")
AttributeError: 'module' object has no attribute 'setdefaultencoding'
                                                                       #

Bellow is a number of tested solutions that I have tried and worked for me.

Solution : patch the external library to work with python 2 or remove reload(sys) and sys.setdefaultencoding() from your code

As I explained in the beginning of this blog post, you should not use setdefaultencoding in python 3. using it is useless in python 3, the function doe not even exist in python like it does in python 2.

Sometimes, you do not pay attention and you use this function in python 3 and you get the error.

The error can also occur if you use a third party library which was written for python 2 and was not rewritten to work with python 3.

The solution is presented in two options.

First option, in case you get this error after using an external library, the solution is to patch the file by adding this block of code to the end of your script.

                                                                       #
if sys.version[0] == '2':
#  reinstating sys.setdefaultencoding
reload(sys)
sys.setdefaultencoding("utf-8")
                                                                       #

The second option, the second option is easy. Just remove reload(sys) and sys.setdefaultencoding() from your code, you do not even need to replace them with anything. Since python 3 uses UTF-8 by default.

If the solutions above helped you, consider supporting us on Kofi, any help is appreciated.

Summing-up

I hope you found a solution in our article, keep creating and keep coding, cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/