Skip to content

Commit

Permalink
peek: add serialization of PythonArtifact object (pantsbuild#17537)
Browse files Browse the repository at this point in the history
peek: add serialization of PythonArtifact object

Use a Protocol to declare how to implement object serialization, and make types compatible with Python 3.7
  • Loading branch information
AlexTereshenkov authored Nov 29, 2022
1 parent c6137e0 commit 1c10b13
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/python/pants/backend/project_info/peek.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
import collections
import json
from dataclasses import asdict, dataclass, is_dataclass
from typing import Any, Iterable
from typing import Any, Iterable, Mapping

from typing_extensions import Protocol, runtime_checkable

from pants.engine.collection import Collection
from pants.engine.console import Console
Expand All @@ -26,6 +28,14 @@
from pants.option.option_types import BoolOption


@runtime_checkable
class Dictable(Protocol):
"""Make possible to avoid adding concrete types to serialize objects."""

def asdict(self) -> Mapping[str, Any]:
...


class PeekSubsystem(Outputting, GoalSubsystem):
"""Display detailed target information in JSON form."""

Expand Down Expand Up @@ -106,6 +116,8 @@ def default(self, o):
return list(o)
if isinstance(o, Field):
return self.default(o.value)
if isinstance(o, Dictable):
return o.asdict()
try:
return super().default(o)
except TypeError:
Expand Down
5 changes: 4 additions & 1 deletion src/python/pants/backend/python/macros/python_artifact.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class PythonArtifact:
def __init__(self, **kwargs):
"""
:param kwargs: Passed to `setuptools.setup
<https://pythonhosted.org/setuptools/setuptools.html>`_.
<https://setuptools.pypa.io/en/latest/setuptools.html>`_.
"""
if "entry_points" in kwargs:
# coerce entry points from Dict[str, List[str]] to Dict[str, Dict[str, str]]
Expand All @@ -79,6 +79,9 @@ def __init__(self, **kwargs):
def kwargs(self) -> Dict[str, Any]:
return self._kw

def asdict(self) -> Dict[str, Any]:
return self.kwargs

def __eq__(self, other: Any) -> bool:
if not isinstance(other, PythonArtifact):
return False
Expand Down

0 comments on commit 1c10b13

Please sign in to comment.