Skip to content

Commit

Permalink
pg.Formattable: Uses __str_format_kwargs__/`__repr_format_kwargs_…
Browse files Browse the repository at this point in the history
…_` to control the format of `__str__` and `__repr__`.

PiperOrigin-RevId: 568364421
  • Loading branch information
daiyip authored and pyglove authors committed Sep 26, 2023
1 parent fdded3d commit 7e0a98b
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 37 deletions.
24 changes: 12 additions & 12 deletions pyglove/core/geno/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@ class DNASpec(symbolic.Object):
method, it's aimed to be used within the same process, thus not required to
be serializable.
"""

# Override format kwargs for __str__.
__str_format_kwargs__ = dict(
compact=True,
verbose=False,
hide_default_values=True,
hide_missing_values=True
)

# NOTE(daiyip): we disable the symbolic comparison to allow hashing DNASpec
# by object ID, therefore we can use DNASpec objects as the keys for a dict.
# This is helpful when we want to align decision points using DNASpec as
Expand Down Expand Up @@ -332,14 +341,6 @@ def userdata(self) -> AttributeDict:
"""Gets user data."""
return self._userdata

def __str__(self):
"""Operator str."""
return self.format(
compact=True,
verbose=False,
hide_default_values=True,
hide_missing_values=True)

@classmethod
def from_json(cls, json_value, *args, **kwargs) -> symbolic.Object:
"""Override from_json for backward compatibility with serialized data."""
Expand Down Expand Up @@ -468,6 +469,9 @@ class DNA(symbolic.Object):
"""
# pylint: enable=line-too-long

# Use compact format for __str__ output.
__str_format_kwargs__ = dict(compact=True)

# Allow assignment on symbolic attributes.
allow_symbolic_assignment = True

Expand Down Expand Up @@ -1686,10 +1690,6 @@ def from_parameters(cls,
del use_literal_values
return cls.from_dict(parameters, dna_spec)

def __str__(self) -> str:
"""Use compact form as string representation."""
return self.format(compact=True)


symbolic.members([
(
Expand Down
10 changes: 8 additions & 2 deletions pyglove/core/object_utils/common_traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ class Formattable(metaclass=abc.ABCMeta):
All symbolic types implement this interface.
"""

# Additional format keyword arguments for `__str__`.
__str_format_kwargs__ = dict(compact=False, verbose=True)

# Additional format keyword arguments for `__repr__`.
__repr_format_kwargs__ = dict(compact=True)

@abc.abstractmethod
def format(self,
compact: bool = False,
Expand All @@ -53,11 +59,11 @@ def format(self,

def __str__(self) -> str:
"""Returns the full (maybe multi-line) representation of this object."""
return self.format(compact=False, verbose=True)
return self.format(**self.__str_format_kwargs__)

def __repr__(self) -> str:
"""Returns a single-line representation of this object."""
return self.format(compact=True)
return self.format(**self.__repr_format_kwargs__)


class MaybePartial(metaclass=abc.ABCMeta):
Expand Down
10 changes: 3 additions & 7 deletions pyglove/core/symbolic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,9 @@ class Symbolic(
:class:`pyglove.Dict`.
"""

# Do not include comments in str output.
__str_format_kwargs__ = dict(compact=False, verbose=False)

# Symbolic sub-types that will be set when they are defined.
# pylint: disable=invalid-name

Expand Down Expand Up @@ -1056,13 +1059,6 @@ class A(pg.Object):
v = query(self, path_regex, where, False, custom_selector)
object_utils.print(v, file=file, **kwargs)

def __str__(self) -> str:
"""Override Formattable.__str__ by setting verbose to False."""
return self.format(compact=False, verbose=False)

def __repr__(self) -> str:
return self.format(compact=True)

def __copy__(self) -> 'Symbolic':
"""Overridden shallow copy."""
return self.sym_clone(deep=False)
Expand Down
2 changes: 1 addition & 1 deletion pyglove/core/symbolic/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -967,7 +967,7 @@ def _should_include_key(key):

def __repr__(self) -> str:
"""Operator repr()."""
return self.format(compact=True)
return base.Symbolic.__repr__(self)

def __eq__(self, other: Any) -> bool:
"""Operator ==."""
Expand Down
4 changes: 0 additions & 4 deletions pyglove/core/tuning/protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ def __hash__(self):
"""Hash code."""
return hash(repr(self))

def __str__(self):
"""Overrides __str__ to use non-verbose format."""
return self.format(compact=False, verbose=False)


@symbolic.members([
('step', pg_typing.Int(), 'At which step the result is reported.'),
Expand Down
11 changes: 0 additions & 11 deletions pyglove/core/typing/class_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,14 +519,6 @@ def __ne__(self, other: Any) -> bool:
"""Operator !=."""
return not self.__eq__(other)

def __repr__(self) -> str:
"""Operator repr."""
return self.format(compact=True)

def __str__(self) -> str:
"""Operator str."""
return self.format(compact=False, verbose=True)

@classmethod
def from_annotation(
cls,
Expand Down Expand Up @@ -1268,9 +1260,6 @@ def to_json(self, **kwargs) -> Dict[str, Any]:
**kwargs,
)

def __str__(self) -> str:
return self.format(compact=False, verbose=True)

def __eq__(self, other: Any) -> bool:
if self is other:
return True
Expand Down

0 comments on commit 7e0a98b

Please sign in to comment.