pg.diff

Accessible via pg.diff, pg.symbolic.diff.

diff(left, right, flatten=False, collapse='same_type', mode='diff')[source]

Inspect the symbolic diff between two objects.

For example:

@pg.members([
  ('x', pg.Any()),
  ('y', pg.Any())
])
class A(pg.Object):
  pass

@pg.members([
  ('z', pg.Any().noneable())
])
class B(A):
  pass


# Diff the same object.
pg.diff(A(1, 2), A(1, 2))

>> No diff

# Diff the same object with mode 'same'.
pg.diff(A(1, 2), A(1, 2), mode='same')

>> A(1, 2)

# Diff different objects of the same type.
pg.diff(A(1, 2), A(1, 3))

>> A(
>>   y = Diff(
>>     left=2,
>>     right=3
>>   )
>>  )

# Diff objects of different type.
pg.diff(A(1, 2), B(1, 3))

>> Diff(
>>    left = A(
>>      x = 1,
>>      y = 2
>>    ),
>>    right = B(
>>      x = 1,
>>      y = 3,
>>      z = None
>>    )

# Diff objects of different type with collapse.
pg.diff(A(1, 2), B(1, 3), collapse=True)

>> A|B (
>>   y = Diff(
>>     left = 2,
>>     right = 3,
>>   ),
>>   z = Diff(
>>     left = MISSING,
>>     right = None
>>   )
>> )

# Diff objects of different type with collapse and flatten.
# Object type is included in key '_type'.
pg.diff(A(1, pg.Dict(a=1)), B(1, pg.Dict(a=2)), collapse=True, flatten=True)

>> {
>>    'y.a': Diff(1, 2),
>>    'z', Diff(MISSING, None),
>>    '_type': Diff(A, B)
>> }
Return type:

Union[Any, pg.Diff]

Parameters:
  • left – The left object to compare.

  • right – The right object to compare.

  • flatten – If True, returns a level-1 dict with diff keys flattened. Otherwise preserve the hierarchy of the diff result.

  • collapse – One of a boolean value, string or a callable object that indicates whether to collapse two different values. The default value ‘same_type’ means only collapse when the two values are of the same type.

  • mode – Diff mode, should be one of [‘diff’, ‘same’, ‘both’]. For ‘diff’ mode (the default), the return value contains only different values. For ‘same’ mode, the return value contains only same values. For ‘both’, the return value contains both different and same values.

Returns:

A Diff object when flatten is False. Otherwise a dict of string (key path) to Diff.