Borislav Hadzhiev
Wed Apr 20 2022·3 min read
Photo by Thought Catalog
The Python "AttributeError: 'NoneType' object has no attribute 'get'" occurs
when we try to call the get()
method on a None
value, e.g. assignment from
function that doesn't return anything. To solve the error, make sure to only
call get()
on dict objects.
Here is an example of how the error occurs.
my_dict = None # ⛔️ AttributeError: 'NoneType' object has no attribute 'get' my_dict.get('name') # ✅ if you need to check if not None before calling get if my_dict is not None: print('variable is NOT None') print(my_dict.get('hello')) else: print('variable is None')
Trying to call the get()
method on a None
value is what causes the error.
get()
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_dict(): print({'name': 'Alice', 'age': 30}) # 👇️ None my_dict = get_dict() # ⛔️ AttributeError: 'NoneType' object has no attribute 'get' my_dict.get('name')
Notice that our get_dict
function doesn't explicitly return a value, so it
implicitly returns None
.
get()
which caused the error.The "AttributeError: 'NoneType' object has no attribute 'get'" occurs for multiple reasons:
None
implicitly).None
.Some built-in methods mutate a data structure in place and don't return a value.
In other words, they implicitly return None
.
Make sure you aren't assigning the result of calling a method that returns
None
to a variable.
If a variable might sometimes store a dict and sometimes store None
, you can
explicitly check if the variable is not None
before you call get()
.
my_dict = {'name': 'Alice', 'age': 30} if my_dict is not None: print('variable is NOT None') print(my_dict.get('name')) # 👉️ "Alice" else: print('variable is None')
The if
block will run only if the my_dict
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_dict(a): if len(a) > 1: return a my_dict = get_dict({'name': 'Alice'}) print(my_dict) # 👉️ None
The if
statement in the get_dict
function is only ran if the passed in
dictionary has a length greater than 1
.
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_dict(a): if len(a) > 1: return a return {} my_dict = get_dict({'name': 'Alice'}) print(my_dict) # 👉️ {}
Now the function is guaranteed to return a dict regardless if the condition is met.