Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Nathan McBride
The Python "AttributeError: 'NoneType' object has no attribute 'encode'"
occurs when we try to call the encode()
method on a None
value, e.g.
assignment from function that doesn't return anything. To solve the error, make
sure to only call encode()
on strings.
Here is a very simple example of how the error occurs.
my_string = None # ⛔️ AttributeError: 'NoneType' object has no attribute 'encode' result = my_string.encode('utf-8') # ✅ if you need to check if not None before calling encode() if my_string is not None: print('Variable is not None') print(my_string.encode('utf-8')) else: print('Variable is None')
Trying to call the encode()
method on a None
value is what causes the error.
encode()
on, it will be None
, so you have to track down where the variable gets assigned a None
value and correct or remove the assignment.The most common source of a None
value (other than an explicit assignment) is
a function that doesn't return anything.
# 👇️ this function returns None def get_string(): print('hello world') # 👇️ None my_string = get_string() # ⛔️ AttributeError: 'NoneType' object has no attribute 'encode' result = my_string.encode('utf-8')
Notice that our get_string
function doesn't explicitly return a value, so it
implicitly returns None
.
encode
which caused the error.The "AttributeError: 'NoneType' object has no attribute 'encode'" occurs for multiple reasons:
None
implicitly).None
.If a variable might sometimes store a string and sometimes store None
, you can
explicitly check if the variable is not None
before you call encode()
.
my_string = 'hello world' if my_string is not None: print('Variable is not None') result = my_string.encode('utf-8') print(result) # 👉️ b'hello world' else: print('Variable is None')
The if
block will run only if the my_string
variable does not store a None
value, otherwise the else
block runs.
Another common cause of the error is having a function that returns a value only if a condition is met.
def get_string(a): if len(a) > 3: return a my_string = get_string('hi') print(my_string) # 👉️ None
The if
statement in the get_string
function is only ran if the passed in
string has a length greater than 3
.
None
.To solve the error in this scenario, you either have to check if the function
didn't return None
or return a default value if the condition is not met.
def get_string(a): if len(a) > 3: return a return '' my_string = get_string('hi') print(my_string) # 👉️ ""
Now the function is guaranteed to return a string regardless if the condition is met.