MCPcopy Create free account
hub / github.com/ipython/ipython / BaseFormatter

Class BaseFormatter

IPython/core/formatters.py:287–564  ·  view source on GitHub ↗

A base formatter class that is configurable. This formatter should usually be used as the base class of all formatters. It is a traited :class:`Configurable` class and includes an extensible API for users to determine how their objects are formatted. The following logic is used to f

Source from the content-addressed store, hash-verified

285
286
287class BaseFormatter(Configurable):
288 """A base formatter class that is configurable.
289
290 This formatter should usually be used as the base class of all formatters.
291 It is a traited :class:`Configurable` class and includes an extensible
292 API for users to determine how their objects are formatted. The following
293 logic is used to find a function to format an given object.
294
295 1. The object is introspected to see if it has a method with the name
296 :attr:`print_method`. If is does, that object is passed to that method
297 for formatting.
298 2. If no print method is found, three internal dictionaries are consulted
299 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
300 and :attr:`deferred_printers`.
301
302 Users should use these dictionaries to register functions that will be
303 used to compute the format data for their objects (if those objects don't
304 have the special print methods). The easiest way of using these
305 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
306 methods.
307
308 If no function/callable is found to compute the format data, ``None`` is
309 returned and this format type is not used.
310 """
311
312 format_type = Unicode('text/plain')
313 _return_type = str
314
315 enabled = Bool(True).tag(config=True)
316
317 print_method = ObjectName('__repr__')
318
319 # The singleton printers.
320 # Maps the IDs of the builtin singleton objects to the format functions.
321 singleton_printers = Dict().tag(config=True)
322
323 # The type-specific printers.
324 # Map type objects to the format functions.
325 type_printers = Dict().tag(config=True)
326
327 # The deferred-import type-specific printers.
328 # Map (modulename, classname) pairs to the format functions.
329 deferred_printers = Dict().tag(config=True)
330
331 @catch_format_error
332 def __call__(self, obj):
333 """Compute the format for an object."""
334 if self.enabled:
335 # lookup registered printer
336 try:
337 printer = self.lookup(obj)
338 except KeyError:
339 pass
340 else:
341 return printer(obj)
342 # Finally look for special method names
343 method = get_real_method(obj, self.print_method)
344 if method is not None:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected