def lookup_by_type(self, typ): """Look up the registered formatter for a type. Parameters ---------- typ : type or '__module__.__name__' string for a type Returns ------- f : callable The registered formatting callable for the type. Raises ------ KeyError if the type has not been registered. """ if isinstance(typ, string_types): typ_key = tuple(typ.rsplit('.', 1)) if typ_key not in self.deferred_printers: # We may have it cached in the type map. We will have to # iterate over all of the types to check. for cls in self.type_printers: if _mod_name_key(cls) == typ_key: return self.type_printers[cls] else: return self.deferred_printers[typ_key] else: for cls in pretty._get_mro(typ): if cls in self.type_printers or self._in_deferred_types(cls): return self.type_printers[cls] # If we have reached here, the lookup failed. raise KeyError("No registered printer for {0!r}".format(typ))
def __call__(self, obj): """Compute the format for an object.""" if self.enabled: obj_id = id(obj) try: obj_class = getattr(obj, '__class__', None) or type(obj) # First try to find registered singleton printers for the type. try: printer = self.singleton_printers[obj_id] except (TypeError, KeyError): pass else: return printer(obj) # Next look for type_printers. for cls in pretty._get_mro(obj_class): if cls in self.type_printers: return self.type_printers[cls](obj) else: printer = self._in_deferred_types(cls) if printer is not None: return printer(obj) # Finally look for special method names. if hasattr(obj_class, self.print_method): printer = getattr(obj_class, self.print_method) return printer(obj) return None except Exception: pass else: return None
def lookup_by_type(self, typ): """Look up the registered formatter for a type. Parameters ---------- typ : type or '__module__.__name__' string for a type Returns ------- f : callable The registered formatting callable for the type. Raises ------ KeyError if the type has not been registered. """ if isinstance(typ, str): typ_key = tuple(typ.rsplit('.',1)) if typ_key not in self.deferred_printers: # We may have it cached in the type map. We will have to # iterate over all of the types to check. for cls in self.type_printers: if _mod_name_key(cls) == typ_key: return self.type_printers[cls] else: return self.deferred_printers[typ_key] else: for cls in pretty._get_mro(typ): if cls in self.type_printers or self._in_deferred_types(cls): return self.type_printers[cls] # If we have reached here, the lookup failed. raise KeyError("No registered printer for {0!r}".format(typ))