I have the following:
class JsonSerializable(object):
def to_json(self):
raise NotImplementedError
class InlineKeyboardMarkup(JsonSerializable):
def __init__(self, inline_keyboard):
self.inline_keyboard = inline_keyboard
def to_json(self):
obj = {'inline_keyboard': self.inline_keyboard}
return json.dumps(obj)
I need the InlineKeyboardMarkup return without accessing .to_json() like this:
>>> InlineKeyboardMarkup(inline_keyboard=[])
... '{"inline_keyboard":[]}'
CodePudding user response:
If all you want is to display it in the repl
loop, you can just override __repr__
, which is called under the hood by print
:
class InlineKeyboardMarkup(JsonSerializable):
def __init__(self, inline_keyboard):
self.inline_keyboard = inline_keyboard
def to_json(self):
obj = {'inline_keyboard': self.inline_keyboard}
return json.dumps(obj)
def __repr__(self):
return repr(self.to_json())
CodePudding user response:
Using repr :
import json
class JsonSerializable(object):
def to_json(self):
raise NotImplementedError
class InlineKeyboardMarkup(JsonSerializable):
def __init__(self, inline_keyboard):
self.inline_keyboard = inline_keyboard
def to_json(self):
obj = {'inline_keyboard': self.inline_keyboard}
return json.dumps(obj)
def __repr__(self):
return repr(self.to_json())
def test_inline_keyboard_markup():
dic = r'{"inline_keyboard": [[{}, {}], [{}]]}'
obj = InlineKeyboardMarkup(inline_keyboard=[[{}, {}], [{}]])
assert obj == dic
pytest-3 object.py -vvv
ERROR collecting objects.py
objects.py:27: in <module>
test_inline_keyboard_markup()
objects.py:24: in test_inline_keyboard_markup
assert obj == dic
E assert '{"inline_keyboard": [[{}, {}], [{}]]}' == '{"inline_keyboard": [[{}, {}], [{}]]}'
Interrupted: 1 errors during collection
1 error in 0.58 seconds