Search code examples
pythonglom

Glom: How to include field-specific defaults


How can one include field-specific defaults in glom's output?

For example, I can include "constants" like this:

from glom import Spec, Literal
extract = Spec({'A': 'a', 'B': Literal(42)}).glom
assert extract({'a': 'life'}) == {'A': 'life', 'B': 42}

But how do I specify that 'B' should point to 42 only if 'B' is not in the input? Stepping out of glom I can do this:

from glom import Spec
extract = lambda d: dict(Spec({'A': 'a'}).glom(d), B=d.get('B', 42))
assert extract({'a': 'life'}) == {'A': 'life', 'B': 42}
assert extract({'a': 'life', 'B': 'is short'}) == {'A': 'life', 'B': 'is short'}

Surely, there a glommier way to do this.


Solution

  • (I guess I'll get the glory (and shame for not having known this earlier).)

    The answer is: Use glom.Coalesce with the default argument therein.

    The glom-equivalent of the my lambda-using code above:

    from glom import Spec, Coalesce
    extract = Spec({'A': 'a', 'B': Coalesce('B', default=42)}).glom  # the solution
    assert extract({'a': 'life'}) == {'A': 'life', 'B': 42}
    assert extract({'a': 'life', 'B': 'is short'}) == {'A': 'life', 'B': 'is short'}