Skip to content

Commit 569acf9

Browse files
committed
Some improved representation for model classes themselves. There's room for improvement here but this is a start.
1 parent 1fda4b9 commit 569acf9

1 file changed

Lines changed: 69 additions & 2 deletions

File tree

‎astropy/modeling/core.py‎

Lines changed: 69 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,23 @@ def __new__(mcls, name, bases, members):
6767

6868
return cls
6969

70+
def __repr__(cls):
71+
"""
72+
Custom repr for Model subclasses.
73+
"""
74+
75+
return cls._format_cls_repr()
76+
77+
def _repr_pretty_(cls, p, cycle):
78+
"""
79+
Repr for IPython's pretty printer.
80+
81+
By default IPython "pretty prints" classes, so we need to implement
82+
this so that IPython displays the custom repr for Models.
83+
"""
84+
85+
p.text(repr(cls))
86+
7087
@property
7188
def name(cls):
7289
"""
@@ -244,6 +261,56 @@ def __pow__(cls, other):
244261
def __or__(cls, other):
245262
return _make_compound_model(cls, other, '|')
246263

264+
# *** Other utilities ***
265+
266+
def _format_cls_repr(cls, keywords=[]):
267+
"""
268+
Internal implementation of ``__repr__``.
269+
270+
This is separated out for ease of use by subclasses that wish to
271+
override the default ``__repr__`` while keeping the same basic
272+
formatting.
273+
"""
274+
275+
# For the sake of familiarity start the output with the standard class
276+
# __repr__
277+
parts = [super(_ModelMeta, cls).__repr__()]
278+
279+
if cls is Model or cls.__name__.startswith('_'):
280+
return parts[0]
281+
282+
def format_inheritance(cls):
283+
bases = []
284+
for base in cls.mro()[1:]:
285+
if not issubclass(base, Model):
286+
continue
287+
elif (inspect.isabstract(base) or
288+
base.__name__.startswith('_')):
289+
break
290+
bases.append(base.name)
291+
if bases:
292+
return '{0} ({1})'.format(cls.name, ' -> '.join(bases))
293+
else:
294+
return cls.name
295+
296+
try:
297+
default_keywords = [
298+
('Name', format_inheritance(cls)),
299+
('Inputs', cls.inputs),
300+
('Outputs', cls.outputs),
301+
('Fittable parameters', cls.param_names)
302+
]
303+
304+
for keyword, value in default_keywords + keywords:
305+
if value is not None:
306+
parts.append('{0}: {1}'.format(keyword, value))
307+
308+
return '\n'.join(parts)
309+
except:
310+
# If any of the above formatting fails fall back on the basic repr
311+
# (this is particularly useful in debugging)
312+
return parts[0]
313+
247314

248315
@six.add_metaclass(_ModelMeta)
249316
class Model(object):
@@ -955,8 +1022,8 @@ def _format_str(self, keywords=[]):
9551022
default_keywords = [
9561023
('Model', self.__class__.__name__),
9571024
('Name', self.name),
958-
('Inputs', self.n_inputs),
959-
('Outputs', self.n_outputs),
1025+
('Inputs', self.inputs),
1026+
('Outputs', self.outputs),
9601027
('Model set size', len(self))
9611028
]
9621029

0 commit comments

Comments
 (0)