0

Consider the following code:

req = { "foo": True }
if req.get("bar").get("baz") != "qux":
    print("Not Found")

I expect this to print Not Found, because there is no bar containing a baz containing qux. Instead, it fails with an exception:

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

How can this be avoided?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Deepak N V
  • 23
  • 1

4 Answers4

2

If you want to be able to chain .get()s, pass {} as the default for all but the last:

if req.get("result", {}).get("action") != "music.play":

That way if req has no result, the first get() returns {}, which does in turn have a .get() method.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
2

req.get("bar").get("baz") only works if the first get returns a dictionary with the right key

In [182]: req = {'bar': {'baz': 'foo'}}
In [183]: req.get('bar')
Out[183]: {'baz': 'foo'}
In [184]: req.get('bar').get('baz')
Out[184]: 'foo'

That is the second get applies to the object returned by the first.

In [185]: req = { "foo": True }
In [186]: req.get('bar')
# returned None

Another way to write this would be:

req['bar']['baz']    # req must be a nested dictionary

get takes a default, which could be another dictionary. In fact it could return the dictionary itself - repeatedly:

In [187]: req.get('bar', req)
Out[187]: {'foo': True}
In [188]: req.get('bar', req).get('baz')
In [189]: req.get('bar', req).get('baz', req)
Out[189]: {'foo': True}
In [190]: req.get('bar', req).get('baz', req).get('foo')
Out[190]: True

This would return your NotFound:

In [193]: req.get('bar', {}).get('baz', 'fppbar')
Out[193]: 'fppbar'
hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

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.

Please refer this answer : https://stackoverflow.com/a/8949265/6332980

0

This error means that your call to the req.get() function returned None, which means a null reference. Therefore, in that case, you are trying to access the get property of a null reference, which cannot be done.

Gaboik1
  • 353
  • 3
  • 15