Skip to main content

To avoid NoneType AttributeError exception on chained attributes

Project description

When accessing an object with chained attributes,

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

naïvely this will fail as soon as one of the intermediate attributes returns None:

>>> obj.a

>>> obj.a.b.c.
AttributeError: 'NoneType' object has no attribute 'b'

NoAttr gives you a way around this in cases where a series of None checks would be too much effort and result in complex code. Instead of returning None, you want to return an instance of NoAttr, which will caused hierarchical attribute accesses to keep returning NoAttr until the end of the chain

>>> from noattr import NoAttr
>>> obj = NoAttr

>>> obj.a

>>> obj.a.b.c.d

NoAttr behaves as a “falsy” value, meaning that it can stand for None, False, 0, '', [] or {}, depending on context. Here are some examples:

>>> obj.a

>>> obj.a.b.c.d or 'Unknown'  # behaves like a falsy value

>>> for i in obj.a.b.c.d:  # behaves like an enumerable that does not yield a value
...     print(i)
(no output)

>>> len(obj.a.b.c.d)  # behaves like an empty collection

>>> obj.a.b.c.d + 1  # behaves like a 0

>>> obj.a.b.c.d.anyfunc()  # behaves like a callable

However, for ljust(), rjust(), rfind(), find(), rindex(), index(), and count(), NoAttr is seen as a single whitespace character (' ') to preserve the expected behavior of these methods:

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


$ pip install noattr


0.0.8 (2018-08-24)

__iter__() now returns an empty iter

0.0.7 (2018-08-21)

Update code for python3 compatibility

0.0.6 (2016-03-11)

remove __or__ and __rshift__ definition for python_textops

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.

Files for noattr, version 0.0.9
Filename, size File type Python version Upload date Hashes
Filename, size noattr-0.0.9-py3-none-any.whl (4.8 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size noattr-0.0.9.tar.gz (3.3 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page