python – Why do I get AttributeError: NoneType object has no attribute something?
python – Why do I get AttributeError: NoneType object has no attribute something?
NoneType means that instead of an instance of whatever Class or Object you think youre working with, youve actually got None
. That usually means that an assignment or function call up above failed or returned an unexpected result.
You have a variable that is equal to None and youre attempting to access an attribute of it called something.
foo = None
foo.something = 1
or
foo = None
print(foo.something)
Both will yield an AttributeError: NoneType
python – Why do I get AttributeError: NoneType object has no attribute something?
Others have explained what NoneType
is and a common way of ending up with it (i.e., failure to return a value from a function).
Another common reason you have None
where you dont expect it is assignment of an in-place operation on a mutable object. For example:
mylist = mylist.sort()
The sort()
method of a list sorts the list in-place, that is, mylist
is modified. But the actual return value of the method is None
and not the list sorted. So youve just assigned None
to mylist
. If you next try to do, say, mylist.append(1)
Python will give you this error.