The Python Oracle

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
00:31 Accepted answer (Score 421)
00:55 Answer 2 (Score 136)
01:18 Answer 3 (Score 66)
02:01 Answer 4 (Score 17)
02:26 Thank you

--

Full question
https://stackoverflow.com/questions/8949...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #attributeerror #nonetype

#avk47



ACCEPTED ANSWER

Score 455


NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result.




ANSWER 2

Score 143


You have a variable that is equal to None and you're 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'




ANSWER 3

Score 17


The NoneType is the type of the value None. In this case, the variable lifetime has a value of None.

A common way to have this happen is to call a function missing a return.

There are an infinite number of other ways to set a variable to None, however.




ANSWER 4

Score 15


Consider the code below.

def return_something(someint):
 if  someint > 5:
    return someint

y = return_something(2)
y.real()

This is going to give you the error

AttributeError: 'NoneType' object has no attribute 'real'

So points are as below.

  1. In the code, a function or class method is not returning anything or returning the None
  2. Then you try to access an attribute of that returned object(which is None), causing the error message.