-2

I am having difficulty in understand some code in python and would really appreciate any help on it.

condition = "{field}::{cast} {operator} {value}".format(**{
    'field': field_exp(field),
    'cast': cast,
    'value': json.dumps(parameter).replace('"', "'"),
    'operator': operator})

I cannot understand what's really happening in this statement. what does the "double colon" do? And what does format(**... mean?

Further in the code there is another line:

condition = "jsonb_typeof({field}::jsonb) is {not} null".format(**{
    'field': field_exp(field),
    'not': 'not' if parameter else ''})

This statement again follows similar pattern. I will really appreciate if someone could explain what's going on here.

Thank you, Asanas

asanas
  • 3,782
  • 11
  • 43
  • 72
  • 1
    Did you try running it? – msw Feb 18 '16 at 14:29
  • The double colon doesn't do anything special. It just means the resulting string will have two colons in it, the same way your second string will have "jsonb_typeof" and "is" and "null" in it. – Kevin Feb 18 '16 at 14:30

1 Answers1

0

The double colon doesn't do anything. It's just a fixed part of the format string.

The ** notation allows keyword arguments to be specified from a dict. Here's a simple, similar example that should make this clear. I assigned the dict to a variable rather than using it in-line to make it more obvious what's happening:

>>> vals = {"a":"w", "b":"x", "c":"y", "d":"z"}
>>> "{a}::{b} {c} {d}".format(**vals)
'w::x y z'
>>>

As you can see, format is just substituting the values from its keyword arguments, which are given by vals.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41