Welcome, guest | Sign In | My Account | Store | Cart

This string Formatter works exactly as the default string.Formatter one (i.e., as str.format), with the exception that None values are rendered as empty strings instead of "None". Moreover, any attempt to access attributes or items of None values is rendered as an empty string as well, instead of raising an exception.
E.g. fmt.format('{a}{a.foo}{a[0]}', a=None) == ''

This is useful e.g. when filling a template with values that are fetched from a DB, where usually None means empty.

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from string import Formatter

class EmptyNoneType(object):

    def __nonzero__(self):
        return False

    def __str__(self):
        return ''

    def __getattr__(self, name):
        return EmptyNone

    def __getitem__(self, idx):
        return EmptyNone
    

EmptyNone = EmptyNoneType()

class EmptyNoneFormatter(Formatter):

    def get_value(self, field_name, args, kwds):
        v = Formatter.get_value(self, field_name, args, kwds)
        if v is None:
            return EmptyNone
        return v

def test_getattr_on_None():
    fmt = EmptyNoneFormatter()
    assert fmt.format('{0}', None) == ''
    assert fmt.format('{0.foo}', None) == ''
    assert fmt.format('{0[0]}', None) == ''

    assert fmt.format('{bar}', bar=None) == ''
    assert fmt.format('{bar.foo}', bar=None) == ''
    assert fmt.format('{bar[0]}', bar=None) == ''