Skip to main content

To avoid NoneType AttributeError exception on chained attributes

Project description

When you access an object with chained attributes

info = obj.a.b.c.d or 'Unknown'

Usually, it will failed when one intermediate attribute return ‘None‘

if obj.a returns None
obj.a.b.c.d will fail with that exception :
AttributeError: 'NoneType' object has no attribute 'b'

To avoid that, instead of returning a ‘None‘ value, one should return ‘NoAttr‘, by this way, even next chained attribute will return ‘NoAttr‘

if obj.a returns NoAttr
obj.a.b.c.d will not fail and will return NoAttr

‘NoAttr‘ can be seen as False, 0, ‘’, [] or {} depending on the context, so

if obj.a returns NoAttr

obj.a.b.c.d or 'Unknown' will return 'Unknown'

for i in obj.a.b.c.d:
    print i
prints nothing

obj.a.b.c.d + 1 returns 1

obj.a.b.c.d.anyfunc() returns NoAttr

but for ljust(), rjust(), rfind(), find(), rindex(), index(), count()
NoAttr is seen as '' :

obj.a.b.c.d.ljust(3) returns '   '

News

0.0.5 (2015-10-13)

add as_list property

0.0.4 (2015-08-19)

add __setattr__ to avoid any modification

0.0.3 (2015-07-27)

First official version

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

noattr-0.0.5.tar.gz (2.8 kB view details)

Uploaded Source

File details

Details for the file noattr-0.0.5.tar.gz.

File metadata

  • Download URL: noattr-0.0.5.tar.gz
  • Upload date:
  • Size: 2.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for noattr-0.0.5.tar.gz
Algorithm Hash digest
SHA256 11e6243bde0b8efb006513aa130ec6151138d12e307a7e12d5b1b70378c8fdf3
MD5 59bff5e63bb1f668ab33f57bcb8eec21
BLAKE2b-256 029f3a9b28e66cba6d259b52589e6f5b646bc7b6248cef6219dbcce48ffbaf04

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page