def _function_pprint(obj, p, cycle):
"""Base pprint for all functions and builtin functions."""
name = _safe_getattr(obj, '__qualname__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
p.text('<function %s>' % name)
python类pprint()的实例源码
def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
"""
Like `pretty` but print to stdout.
"""
printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
printer.pretty(obj)
printer.flush()
sys.stdout.write(newline)
sys.stdout.flush()
def _set_pprinter_factory(start, end, basetype):
"""
Factory that returns a pprint function useful for sets and frozensets.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
# If the subclass provides its own repr, use it instead.
return p.text(typ.__repr__(obj))
if cycle:
return p.text(start + '...' + end)
if len(obj) == 0:
# Special case.
p.text(basetype.__name__ + '()')
else:
step = len(start)
p.begin_group(step, start)
# Like dictionary keys, we will try to sort the items if there aren't too many
items = obj
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
try:
items = sorted(obj)
except Exception:
# Sometimes the items don't sort.
pass
for idx, x in p._enumerate(items):
if idx:
p.text(',')
p.breakable()
p.pretty(x)
p.end_group(step, end)
return inner
def _dict_pprinter_factory(start, end, basetype=None):
"""
Factory that returns a pprint function used by the default pprint of
dicts and dict proxies.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
# If the subclass provides its own repr, use it instead.
return p.text(typ.__repr__(obj))
if cycle:
return p.text('{...}')
step = len(start)
p.begin_group(step, start)
keys = obj.keys()
# if dict isn't large enough to be truncated, sort keys before displaying
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
try:
keys = sorted(keys)
except Exception:
# Sometimes the keys don't sort.
pass
for idx, key in p._enumerate(keys):
if idx:
p.text(',')
p.breakable()
p.pretty(key)
p.text(': ')
p.pretty(obj[key])
p.end_group(step, end)
return inner
def _super_pprint(obj, p, cycle):
"""The pprint for the super type."""
p.begin_group(8, '<super: ')
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
if PYPY: # In PyPy, super() objects don't have __self__ attributes
dself = obj.__repr__.__self__
p.pretty(None if dself is obj else dself)
else:
p.pretty(obj.__self__)
p.end_group(8, '>')
def _type_pprint(obj, p, cycle):
"""The pprint for classes and types."""
# Heap allocated types might not have the module attribute,
# and others may set it to None.
# Checks for a __repr__ override in the metaclass. Can't compare the
# type(obj).__repr__ directly because in PyPy the representation function
# inherited from type isn't the same type.__repr__
if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
_repr_pprint(obj, p, cycle)
return
mod = _safe_getattr(obj, '__module__', None)
try:
name = obj.__qualname__
if not isinstance(name, string_types):
# This can happen if the type implements __qualname__ as a property
# or other descriptor in Python 2.
raise Exception("Try __name__")
except Exception:
name = obj.__name__
if not isinstance(name, string_types):
name = '<unknown type>'
if mod in (None, '__builtin__', 'builtins', 'exceptions'):
p.text(name)
else:
p.text(mod + '.' + name)
def _repr_pprint(obj, p, cycle):
"""A pprint that just redirects to the normal repr function."""
# Find newlines and replace them with p.break_()
output = repr(obj)
for idx,output_line in enumerate(output.splitlines()):
if idx:
p.break_()
p.text(output_line)
def _function_pprint(obj, p, cycle):
"""Base pprint for all functions and builtin functions."""
name = _safe_getattr(obj, '__qualname__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
p.text('<function %s>' % name)
def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
"""
Like `pretty` but print to stdout.
"""
printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
printer.pretty(obj)
printer.flush()
sys.stdout.write(newline)
sys.stdout.flush()
def _set_pprinter_factory(start, end, basetype):
"""
Factory that returns a pprint function useful for sets and frozensets.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
# If the subclass provides its own repr, use it instead.
return p.text(typ.__repr__(obj))
if cycle:
return p.text(start + '...' + end)
if len(obj) == 0:
# Special case.
p.text(basetype.__name__ + '()')
else:
step = len(start)
p.begin_group(step, start)
# Like dictionary keys, we will try to sort the items if there aren't too many
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
items = _sorted_for_pprint(obj)
else:
items = obj
for idx, x in p._enumerate(items):
if idx:
p.text(',')
p.breakable()
p.pretty(x)
p.end_group(step, end)
return inner
def _dict_pprinter_factory(start, end, basetype=None):
"""
Factory that returns a pprint function used by the default pprint of
dicts and dict proxies.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
# If the subclass provides its own repr, use it instead.
return p.text(typ.__repr__(obj))
if cycle:
return p.text('{...}')
step = len(start)
p.begin_group(step, start)
keys = obj.keys()
# if dict isn't large enough to be truncated, sort keys before displaying
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
keys = _sorted_for_pprint(keys)
for idx, key in p._enumerate(keys):
if idx:
p.text(',')
p.breakable()
p.pretty(key)
p.text(': ')
p.pretty(obj[key])
p.end_group(step, end)
return inner
def _super_pprint(obj, p, cycle):
"""The pprint for the super type."""
p.begin_group(8, '<super: ')
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
if PYPY: # In PyPy, super() objects don't have __self__ attributes
dself = obj.__repr__.__self__
p.pretty(None if dself is obj else dself)
else:
p.pretty(obj.__self__)
p.end_group(8, '>')
def _type_pprint(obj, p, cycle):
"""The pprint for classes and types."""
# Heap allocated types might not have the module attribute,
# and others may set it to None.
# Checks for a __repr__ override in the metaclass. Can't compare the
# type(obj).__repr__ directly because in PyPy the representation function
# inherited from type isn't the same type.__repr__
if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
_repr_pprint(obj, p, cycle)
return
mod = _safe_getattr(obj, '__module__', None)
try:
name = obj.__qualname__
if not isinstance(name, str):
# This can happen if the type implements __qualname__ as a property
# or other descriptor in Python 2.
raise Exception("Try __name__")
except Exception:
name = obj.__name__
if not isinstance(name, str):
name = '<unknown type>'
if mod in (None, '__builtin__', 'builtins', 'exceptions'):
p.text(name)
else:
p.text(mod + '.' + name)
def _repr_pprint(obj, p, cycle):
"""A pprint that just redirects to the normal repr function."""
# Find newlines and replace them with p.break_()
output = repr(obj)
for idx,output_line in enumerate(output.splitlines()):
if idx:
p.break_()
p.text(output_line)
def _function_pprint(obj, p, cycle):
"""Base pprint for all functions and builtin functions."""
name = _safe_getattr(obj, '__qualname__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
p.text('<function %s>' % name)