summaryrefslogtreecommitdiff
path: root/gitlab
diff options
context:
space:
mode:
authorNejc Habjan <nejc.habjan@siemens.com>2022-07-20 22:11:15 +0200
committerGitHub <noreply@github.com>2022-07-20 22:11:15 +0200
commitfcbced88025dcf2ff980104bec1d48df3258bc7c (patch)
tree284b349c5321264a648a550c8508dd66b6798d6f /gitlab
parent2c90fd0f317213a5a29bf6a2b63715a287e9fcfa (diff)
parent08ac071abcbc28af04c0fa655576e25edbdaa4e2 (diff)
downloadgitlab-fcbced88025dcf2ff980104bec1d48df3258bc7c.tar.gz
Merge pull request #1872 from python-gitlab/jlvillal/as_dict
feat: add `asdict()` and `to_json()` methods to Gitlab Objects
Diffstat (limited to 'gitlab')
-rw-r--r--gitlab/base.py32
1 files changed, 19 insertions, 13 deletions
diff --git a/gitlab/base.py b/gitlab/base.py
index dd59240..e813fcd 100644
--- a/gitlab/base.py
+++ b/gitlab/base.py
@@ -15,7 +15,9 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+import copy
import importlib
+import json
import pprint
import textwrap
from types import ModuleType
@@ -151,15 +153,26 @@ class RESTObject:
def __setattr__(self, name: str, value: Any) -> None:
self.__dict__["_updated_attrs"][name] = value
+ def asdict(self, *, with_parent_attrs: bool = False) -> Dict[str, Any]:
+ data = {}
+ if with_parent_attrs:
+ data.update(copy.deepcopy(self._parent_attrs))
+ data.update(copy.deepcopy(self._attrs))
+ data.update(copy.deepcopy(self._updated_attrs))
+ return data
+
+ @property
+ def attributes(self) -> Dict[str, Any]:
+ return self.asdict(with_parent_attrs=True)
+
+ def to_json(self, *, with_parent_attrs: bool = False, **kwargs: Any) -> str:
+ return json.dumps(self.asdict(with_parent_attrs=with_parent_attrs), **kwargs)
+
def __str__(self) -> str:
- data = self._attrs.copy()
- data.update(self._updated_attrs)
- return f"{type(self)} => {data}"
+ return f"{type(self)} => {self.asdict()}"
def pformat(self) -> str:
- data = self._attrs.copy()
- data.update(self._updated_attrs)
- return f"{type(self)} => \n{pprint.pformat(data)}"
+ return f"{type(self)} => \n{pprint.pformat(self.asdict())}"
def pprint(self) -> None:
print(self.pformat())
@@ -250,13 +263,6 @@ class RESTObject:
obj_id = gitlab.utils.EncodedId(obj_id)
return obj_id
- @property
- def attributes(self) -> Dict[str, Any]:
- d = self.__dict__["_updated_attrs"].copy()
- d.update(self.__dict__["_attrs"])
- d.update(self.__dict__["_parent_attrs"])
- return d
-
class RESTObjectList:
"""Generator object representing a list of RESTObject's.