Skip to content

obj

Object base class with dict-like attribute access and recursive serialization.

The Obj class provides a convenient container where attributes can be set via keyword arguments and accessed like dictionary keys. It supports recursive conversion to plain dicts via as_dict(), shallow cloning, and equality comparison based on attribute contents.

Classes:

Name Description
Obj

A flexible object container with dict-like attribute access.

Functions:

Name Description
str_value

Formats a value for string representation, escaping strings.

Obj

A flexible object container with dict-like attribute access.

Attributes set via keyword arguments are stored in __dict__ and can be accessed normally. Supports recursive conversion to plain dicts, shallow cloning with overrides, and equality comparison based on attribute contents.

Example
from py_misc_utils import obj as objm

o = objm.Obj(a=1, b='x', nested=objm.Obj(c=2))

assert o.as_dict() == {'a': 1, 'b': 'x', 'nested': {'c': 2}}

c = o.clone(b='y')
assert c.b == 'y' and c.a == 1

assert o == objm.Obj(a=1, b='x', nested=objm.Obj(c=2))
Source code in py_misc_utils/obj.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
class Obj:
  """A flexible object container with dict-like attribute access.

  Attributes set via keyword arguments are stored in ``__dict__`` and can be
  accessed normally. Supports recursive conversion to plain dicts, shallow
  cloning with overrides, and equality comparison based on attribute contents.

  Example:
    from py_misc_utils import obj as objm

    o = objm.Obj(a=1, b='x', nested=objm.Obj(c=2))

    assert o.as_dict() == {'a': 1, 'b': 'x', 'nested': {'c': 2}}

    c = o.clone(b='y')
    assert c.b == 'y' and c.a == 1

    assert o == objm.Obj(a=1, b='x', nested=objm.Obj(c=2))
  """

  def __init__(self, **kwargs):
    """Initializes an Obj with the given keyword attributes.

    Args:
      **kwargs: Attribute names and values to set on the instance.
    """
    self.update(**kwargs)

  def update(self, **kwargs):
    """Updates the object's attributes from keyword arguments.

    Args:
      **kwargs: Attribute names and values to set or override.

    Returns:
      ``self`` for chaining.
    """
    vars(self).update(kwargs)

    return self

  def update_from(self, obj):
    """Copies all attributes from another object into this one.

    Args:
      obj: An object whose ``__dict__`` contents will be copied.

    Returns:
      ``self`` for chaining.
    """
    vars(self).update(vars(obj))

    return self

  def clone(self, **kwargs):
    """Returns a shallow copy of this object with optional attribute overrides.

    Args:
      **kwargs: Attribute names and values to override on the copy.

    Returns:
      A new ``Obj`` instance that is a shallow copy of this object with the
      specified attributes updated.
    """
    nobj = copy.copy(self)
    nobj.update(**kwargs)

    return nobj

  def as_dict(self):
    """Recursively converts this object and nested Obj instances to a plain dict.

    Nested Obj instances, lists/tuples containing Obj instances, and dicts
    containing Obj instances are all recursively converted.

    Returns:
      A plain dictionary representation of this object's attributes.
    """
    ad = dict()
    for k, v in vars(self).items():
      if isinstance(v, Obj):
        v = v.as_dict()
      elif isinstance(v, (list, tuple)):
        vals = []
        for x in v:
          if isinstance(x, Obj):
            x = x.as_dict()
          vals.append(x)

        v = type(v)(vals)
      elif cu.isdict(v):
        vd = type(v)()
        for z, x in v.items():
          if isinstance(x, Obj):
            x = x.as_dict()
          vd[z] = x

        v = vd

      ad[k] = v

    return ad

  def __eq__(self, other):
    """Compares this Obj with another for equality based on attributes.

    Two Obj instances are equal if they have the same set of attributes with
    equal values.

    Args:
      other: The object to compare against.

    Returns:
      True if ``other`` has the same attributes with equal values, False
      otherwise.
    """
    missing = object()
    for k, v in vars(self).items():
      ov = getattr(other, k, missing)
      if ov is missing or v != ov:
        return False
    for k in vars(other):
      if not hasattr(self, k):
        return False

    return True

  def __repr__(self):
    """Returns a string representation of the object.

    Returns:
      A string like ``ClassName(key1=value1, key2=value2)`` with string values
      quoted and escaped.
    """
    values = ', '.join(f'{k}={str_value(v)}' for k, v in vars(self).items())

    return f'{type(self).__name__}({values})'

update(**kwargs)

Updates the object's attributes from keyword arguments.

Parameters:

Name Type Description Default
**kwargs

Attribute names and values to set or override.

{}

Returns:

Type Description

self for chaining.

Source code in py_misc_utils/obj.py
48
49
50
51
52
53
54
55
56
57
58
59
def update(self, **kwargs):
  """Updates the object's attributes from keyword arguments.

  Args:
    **kwargs: Attribute names and values to set or override.

  Returns:
    ``self`` for chaining.
  """
  vars(self).update(kwargs)

  return self

update_from(obj)

Copies all attributes from another object into this one.

Parameters:

Name Type Description Default
obj

An object whose __dict__ contents will be copied.

required

Returns:

Type Description

self for chaining.

Source code in py_misc_utils/obj.py
61
62
63
64
65
66
67
68
69
70
71
72
def update_from(self, obj):
  """Copies all attributes from another object into this one.

  Args:
    obj: An object whose ``__dict__`` contents will be copied.

  Returns:
    ``self`` for chaining.
  """
  vars(self).update(vars(obj))

  return self

clone(**kwargs)

Returns a shallow copy of this object with optional attribute overrides.

Parameters:

Name Type Description Default
**kwargs

Attribute names and values to override on the copy.

{}

Returns:

Type Description

A new Obj instance that is a shallow copy of this object with the

specified attributes updated.

Source code in py_misc_utils/obj.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def clone(self, **kwargs):
  """Returns a shallow copy of this object with optional attribute overrides.

  Args:
    **kwargs: Attribute names and values to override on the copy.

  Returns:
    A new ``Obj`` instance that is a shallow copy of this object with the
    specified attributes updated.
  """
  nobj = copy.copy(self)
  nobj.update(**kwargs)

  return nobj

as_dict()

Recursively converts this object and nested Obj instances to a plain dict.

Nested Obj instances, lists/tuples containing Obj instances, and dicts containing Obj instances are all recursively converted.

Returns:

Type Description

A plain dictionary representation of this object's attributes.

Source code in py_misc_utils/obj.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def as_dict(self):
  """Recursively converts this object and nested Obj instances to a plain dict.

  Nested Obj instances, lists/tuples containing Obj instances, and dicts
  containing Obj instances are all recursively converted.

  Returns:
    A plain dictionary representation of this object's attributes.
  """
  ad = dict()
  for k, v in vars(self).items():
    if isinstance(v, Obj):
      v = v.as_dict()
    elif isinstance(v, (list, tuple)):
      vals = []
      for x in v:
        if isinstance(x, Obj):
          x = x.as_dict()
        vals.append(x)

      v = type(v)(vals)
    elif cu.isdict(v):
      vd = type(v)()
      for z, x in v.items():
        if isinstance(x, Obj):
          x = x.as_dict()
        vd[z] = x

      v = vd

    ad[k] = v

  return ad

str_value(v)

Formats a value for string representation.

String values are quoted and have internal quotes escaped. Non-string values are converted via str().

Parameters:

Name Type Description Default
v

The value to format.

required

Returns:

Type Description

A string representation of v.

Source code in py_misc_utils/obj.py
159
160
161
162
163
164
165
166
167
168
169
170
171
def str_value(v):
  """Formats a value for string representation.

  String values are quoted and have internal quotes escaped. Non-string values
  are converted via ``str()``.

  Args:
    v: The value to format.

  Returns:
    A string representation of ``v``.
  """
  return '"' + v.replace('"', '\\"') + '"' if isinstance(v, str) else str(v)