2020年10月6日 / 746次阅读 / Last Modified 2020年10月6日
python标准库中的inspect模块,可以用来在运行时查看很多有用的信息。其getsource函数,就是用来查看对象的源码。
>>> import inspect
>>> import json
>>> print(inspect.getsource(json.load))
def load(fp, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders. If ``object_hook``
is also defined, the ``object_pairs_hook`` takes priority.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.
"""
return loads(fp.read(),
cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
也算是一种很方便的查看源码的方式。它的方便之处在于,你不用去很费劲地寻找源码所在的位置,用inspect.getsource直接将源码显示出来。
想知道引入对象的文件也可以,用inspect.getfile:
>>> inspect.getfile(json)
'/usr/local/python-3.8.5/lib/python3.8/json/__init__.py'
>>> inspect.getfile(json.load)
'/usr/local/python-3.8.5/lib/python3.8/json/__init__.py'
-- EOF --
本文链接:https://www.pynote.net/archives/2542
前一篇:什么时候用mmap?
后一篇:python如何直接跳出多重循环?
©Copyright 麦新杰 Since 2019 Python笔记