Skip to content

Instantly share code, notes, and snippets.

@nikhilkumarsingh
Created November 2, 2019 23:00
Show Gist options
  • Save nikhilkumarsingh/472a8ddc02e398208f0822a2e6eaa865 to your computer and use it in GitHub Desktop.
Save nikhilkumarsingh/472a8ddc02e398208f0822a2e6eaa865 to your computer and use it in GitHub Desktop.
inspect in Python
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# inspect\n",
"\n",
"<img src=\"https://reinteractive.com/assets/services/inspect/reinteractive-code-inspect-4219b8efba8d96e4abc04f9e2e896e5cb5f7f5e963f102cbbcf1b05f636e5795.jpg\" height=400 width=400>\n",
"\n",
"An in-built python module which provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. \n",
"\n",
"----------\n",
"There are four main kinds of services provided by this module: \n",
"\n",
"- examine the contents of a class, \n",
"- retrieve the source code of a method, \n",
"- extract and format the argument list for a function, or \n",
"- get all the information you need to display a detailed traceback.\n",
"\n",
"-----------------"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Examining contents of an object\n",
"\n",
"- getmembers"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import requests"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"r = requests.get(\"http://httpbin.org/ip\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"b'{\\n \"origin\": \"122.175.20.87, 122.175.20.87\"\\n}\\n'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r.content"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"import inspect"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('__attrs__',\n",
" ['_content',\n",
" 'status_code',\n",
" 'headers',\n",
" 'url',\n",
" 'history',\n",
" 'encoding',\n",
" 'reason',\n",
" 'cookies',\n",
" 'elapsed',\n",
" 'request']),\n",
" ('__bool__', <bound method Response.__bool__ of <Response [200]>>),\n",
" ('__class__', requests.models.Response),\n",
" ('__delattr__',\n",
" <method-wrapper '__delattr__' of Response object at 0x7f0974910cf8>),\n",
" ('__dict__',\n",
" {'_content': b'{\\n \"origin\": \"122.175.20.87, 122.175.20.87\"\\n}\\n',\n",
" '_content_consumed': True,\n",
" 'status_code': 200,\n",
" 'headers': {'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', 'Content-Encoding': 'gzip', 'Content-Type': 'application/json', 'Date': 'Sat, 02 Nov 2019 20:55:05 GMT', 'Referrer-Policy': 'no-referrer-when-downgrade', 'Server': 'nginx', 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'Content-Length': '56', 'Connection': 'keep-alive'},\n",
" 'raw': <requests.packages.urllib3.response.HTTPResponse at 0x7f0974922668>,\n",
" 'url': 'http://httpbin.org/ip',\n",
" 'encoding': None,\n",
" 'history': [],\n",
" 'reason': 'OK',\n",
" 'cookies': <RequestsCookieJar[]>,\n",
" 'elapsed': datetime.timedelta(0, 0, 540747),\n",
" 'request': <PreparedRequest [GET]>,\n",
" 'connection': <requests.adapters.HTTPAdapter at 0x7f09749824a8>}),\n",
" ('__dir__', <function Response.__dir__>),\n",
" ('__doc__',\n",
" \"The :class:`Response <Response>` object, which contains a\\n server's response to an HTTP request.\\n \"),\n",
" ('__eq__', <method-wrapper '__eq__' of Response object at 0x7f0974910cf8>),\n",
" ('__format__', <function Response.__format__>),\n",
" ('__ge__', <method-wrapper '__ge__' of Response object at 0x7f0974910cf8>),\n",
" ('__getattribute__',\n",
" <method-wrapper '__getattribute__' of Response object at 0x7f0974910cf8>),\n",
" ('__getstate__', <bound method Response.__getstate__ of <Response [200]>>),\n",
" ('__gt__', <method-wrapper '__gt__' of Response object at 0x7f0974910cf8>),\n",
" ('__hash__',\n",
" <method-wrapper '__hash__' of Response object at 0x7f0974910cf8>),\n",
" ('__init__', <bound method Response.__init__ of <Response [200]>>),\n",
" ('__init_subclass__', <function Response.__init_subclass__>),\n",
" ('__iter__', <bound method Response.__iter__ of <Response [200]>>),\n",
" ('__le__', <method-wrapper '__le__' of Response object at 0x7f0974910cf8>),\n",
" ('__lt__', <method-wrapper '__lt__' of Response object at 0x7f0974910cf8>),\n",
" ('__module__', 'requests.models'),\n",
" ('__ne__', <method-wrapper '__ne__' of Response object at 0x7f0974910cf8>),\n",
" ('__new__', <function object.__new__(*args, **kwargs)>),\n",
" ('__nonzero__', <bound method Response.__nonzero__ of <Response [200]>>),\n",
" ('__reduce__', <function Response.__reduce__>),\n",
" ('__reduce_ex__', <function Response.__reduce_ex__>),\n",
" ('__repr__', <bound method Response.__repr__ of <Response [200]>>),\n",
" ('__setattr__',\n",
" <method-wrapper '__setattr__' of Response object at 0x7f0974910cf8>),\n",
" ('__setstate__', <bound method Response.__setstate__ of <Response [200]>>),\n",
" ('__sizeof__', <function Response.__sizeof__>),\n",
" ('__str__', <method-wrapper '__str__' of Response object at 0x7f0974910cf8>),\n",
" ('__subclasshook__', <function Response.__subclasshook__>),\n",
" ('__weakref__', None),\n",
" ('_content', b'{\\n \"origin\": \"122.175.20.87, 122.175.20.87\"\\n}\\n'),\n",
" ('_content_consumed', True),\n",
" ('apparent_encoding', 'ascii'),\n",
" ('close', <bound method Response.close of <Response [200]>>),\n",
" ('connection', <requests.adapters.HTTPAdapter at 0x7f09749824a8>),\n",
" ('content', b'{\\n \"origin\": \"122.175.20.87, 122.175.20.87\"\\n}\\n'),\n",
" ('cookies', <RequestsCookieJar[]>),\n",
" ('elapsed', datetime.timedelta(0, 0, 540747)),\n",
" ('encoding', None),\n",
" ('headers',\n",
" {'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', 'Content-Encoding': 'gzip', 'Content-Type': 'application/json', 'Date': 'Sat, 02 Nov 2019 20:55:05 GMT', 'Referrer-Policy': 'no-referrer-when-downgrade', 'Server': 'nginx', 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'Content-Length': '56', 'Connection': 'keep-alive'}),\n",
" ('history', []),\n",
" ('is_permanent_redirect', False),\n",
" ('is_redirect', False),\n",
" ('iter_content', <bound method Response.iter_content of <Response [200]>>),\n",
" ('iter_lines', <bound method Response.iter_lines of <Response [200]>>),\n",
" ('json', <bound method Response.json of <Response [200]>>),\n",
" ('links', {}),\n",
" ('ok', True),\n",
" ('raise_for_status',\n",
" <bound method Response.raise_for_status of <Response [200]>>),\n",
" ('raw', <requests.packages.urllib3.response.HTTPResponse at 0x7f0974922668>),\n",
" ('reason', 'OK'),\n",
" ('request', <PreparedRequest [GET]>),\n",
" ('status_code', 200),\n",
" ('text', '{\\n \"origin\": \"122.175.20.87, 122.175.20.87\"\\n}\\n'),\n",
" ('url', 'http://httpbin.org/ip')]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inspect.getmembers(r)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Retrieving the source code\n",
"\n",
"- getsource, getsourcelines\n",
"- `python3 -m inspect <module>:<class/function>`\n",
"- getdoc\n",
"- getfile"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'/usr/local/lib/python3.6/dist-packages/requests/__init__.py'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inspect.getfile(requests)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"A user-created :class:`Request <Request>` object.\\n\\nUsed to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\\n\\n:param method: HTTP method to use.\\n:param url: URL to send.\\n:param headers: dictionary of headers to send.\\n:param files: dictionary of {filename: fileobject} files to multipart upload.\\n:param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.\\n:param json: json for the body to attach to the request (if files or data is not specified).\\n:param params: dictionary of URL parameters to append to the URL.\\n:param auth: Auth handler or (user, pass) tuple.\\n:param cookies: dictionary or CookieJar of cookies to attach to this request.\\n:param hooks: dictionary of callback hooks, for internal usage.\\n\\nUsage::\\n\\n >>> import requests\\n >>> req = requests.Request('GET', 'http://httpbin.org/get')\\n >>> req.prepare()\\n <PreparedRequest [GET]>\""
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inspect.getdoc(requests.Request)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"A user-created :class:`Request <Request>` object.\\n\\n Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\\n\\n :param method: HTTP method to use.\\n :param url: URL to send.\\n :param headers: dictionary of headers to send.\\n :param files: dictionary of {filename: fileobject} files to multipart upload.\\n :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.\\n :param json: json for the body to attach to the request (if files or data is not specified).\\n :param params: dictionary of URL parameters to append to the URL.\\n :param auth: Auth handler or (user, pass) tuple.\\n :param cookies: dictionary or CookieJar of cookies to attach to this request.\\n :param hooks: dictionary of callback hooks, for internal usage.\\n\\n Usage::\\n\\n >>> import requests\\n >>> req = requests.Request('GET', 'http://httpbin.org/get')\\n >>> req.prepare()\\n <PreparedRequest [GET]>\\n \""
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"requests.Request.__doc__"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"class Request(RequestHooksMixin):\n",
" \"\"\"A user-created :class:`Request <Request>` object.\n",
"\n",
" Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n",
"\n",
" :param method: HTTP method to use.\n",
" :param url: URL to send.\n",
" :param headers: dictionary of headers to send.\n",
" :param files: dictionary of {filename: fileobject} files to multipart upload.\n",
" :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.\n",
" :param json: json for the body to attach to the request (if files or data is not specified).\n",
" :param params: dictionary of URL parameters to append to the URL.\n",
" :param auth: Auth handler or (user, pass) tuple.\n",
" :param cookies: dictionary or CookieJar of cookies to attach to this request.\n",
" :param hooks: dictionary of callback hooks, for internal usage.\n",
"\n",
" Usage::\n",
"\n",
" >>> import requests\n",
" >>> req = requests.Request('GET', 'http://httpbin.org/get')\n",
" >>> req.prepare()\n",
" <PreparedRequest [GET]>\n",
" \"\"\"\n",
"\n",
" def __init__(self, method=None, url=None, headers=None, files=None,\n",
" data=None, params=None, auth=None, cookies=None, hooks=None, json=None):\n",
"\n",
" # Default empty dicts for dict params.\n",
" data = [] if data is None else data\n",
" files = [] if files is None else files\n",
" headers = {} if headers is None else headers\n",
" params = {} if params is None else params\n",
" hooks = {} if hooks is None else hooks\n",
"\n",
" self.hooks = default_hooks()\n",
" for (k, v) in list(hooks.items()):\n",
" self.register_hook(event=k, hook=v)\n",
"\n",
" self.method = method\n",
" self.url = url\n",
" self.headers = headers\n",
" self.files = files\n",
" self.data = data\n",
" self.json = json\n",
" self.params = params\n",
" self.auth = auth\n",
" self.cookies = cookies\n",
"\n",
" def __repr__(self):\n",
" return '<Request [%s]>' % (self.method)\n",
"\n",
" def prepare(self):\n",
" \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n",
" p = PreparedRequest()\n",
" p.prepare(\n",
" method=self.method,\n",
" url=self.url,\n",
" headers=self.headers,\n",
" files=self.files,\n",
" data=self.data,\n",
" json=self.json,\n",
" params=self.params,\n",
" auth=self.auth,\n",
" cookies=self.cookies,\n",
" hooks=self.hooks,\n",
" )\n",
" return p\n",
"\n"
]
}
],
"source": [
"print(inspect.getsource(requests.Request))"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(['class Request(RequestHooksMixin):\\n', ' \"\"\"A user-created :class:`Request <Request>` object.\\n', '\\n', ' Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\\n', '\\n', ' :param method: HTTP method to use.\\n', ' :param url: URL to send.\\n', ' :param headers: dictionary of headers to send.\\n', ' :param files: dictionary of {filename: fileobject} files to multipart upload.\\n', ' :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.\\n', ' :param json: json for the body to attach to the request (if files or data is not specified).\\n', ' :param params: dictionary of URL parameters to append to the URL.\\n', ' :param auth: Auth handler or (user, pass) tuple.\\n', ' :param cookies: dictionary or CookieJar of cookies to attach to this request.\\n', ' :param hooks: dictionary of callback hooks, for internal usage.\\n', '\\n', ' Usage::\\n', '\\n', ' >>> import requests\\n', \" >>> req = requests.Request('GET', 'http://httpbin.org/get')\\n\", ' >>> req.prepare()\\n', ' <PreparedRequest [GET]>\\n', ' \"\"\"\\n', '\\n', ' def __init__(self, method=None, url=None, headers=None, files=None,\\n', ' data=None, params=None, auth=None, cookies=None, hooks=None, json=None):\\n', '\\n', ' # Default empty dicts for dict params.\\n', ' data = [] if data is None else data\\n', ' files = [] if files is None else files\\n', ' headers = {} if headers is None else headers\\n', ' params = {} if params is None else params\\n', ' hooks = {} if hooks is None else hooks\\n', '\\n', ' self.hooks = default_hooks()\\n', ' for (k, v) in list(hooks.items()):\\n', ' self.register_hook(event=k, hook=v)\\n', '\\n', ' self.method = method\\n', ' self.url = url\\n', ' self.headers = headers\\n', ' self.files = files\\n', ' self.data = data\\n', ' self.json = json\\n', ' self.params = params\\n', ' self.auth = auth\\n', ' self.cookies = cookies\\n', '\\n', ' def __repr__(self):\\n', \" return '<Request [%s]>' % (self.method)\\n\", '\\n', ' def prepare(self):\\n', ' \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\\n', ' p = PreparedRequest()\\n', ' p.prepare(\\n', ' method=self.method,\\n', ' url=self.url,\\n', ' headers=self.headers,\\n', ' files=self.files,\\n', ' data=self.data,\\n', ' json=self.json,\\n', ' params=self.params,\\n', ' auth=self.auth,\\n', ' cookies=self.cookies,\\n', ' hooks=self.hooks,\\n', ' )\\n', ' return p\\n'], 193)\n"
]
}
],
"source": [
"print(inspect.getsourcelines(requests.Request))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Class tree\n",
"\n",
"- getclasstree"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"class A:\n",
" pass\n",
"\n",
"class B(A):\n",
" pass\n",
"\n",
"class C(B):\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"tree = inspect.getclasstree([A,B,C])"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(object, ()),\n",
" [(__main__.A, (object,)),\n",
" [(__main__.B, (__main__.A,)), [(__main__.C, (__main__.B,))]]]]"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tree"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"root\n",
"A\n",
"B\n",
"C"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Extracting the argument list for a function\n",
"\n",
"- signature\n",
"- getfullargspec"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"sig = inspect.signature(requests.get)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<Signature (url, params=None, **kwargs)>"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sig"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"POSITIONAL_OR_KEYWORD\n",
"POSITIONAL_OR_KEYWORD\n",
"VAR_KEYWORD\n"
]
}
],
"source": [
"for param in sig.parameters.values():\n",
" print(param.kind)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"FullArgSpec(args=['url', 'params'], varargs=None, varkw='kwargs', defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={})"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inspect.getfullargspec(requests.get)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"def add(a: int, b: int):\n",
" return a + b"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={'a': <class 'int'>, 'b': <class 'int'>})"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inspect.getfullargspec(add)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Unwrapping functions\n",
"\n",
"- unwrap"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"import functools\n",
"\n",
"@functools.lru_cache()\n",
"def func(a, b):\n",
" return a + b"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<functools._lru_cache_wrapper at 0x7f09748efb70>"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"func"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<function __main__.func(a, b)>"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inspect.unwrap(func)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"import math\n",
"\n",
"\n",
"def logger(func):\n",
" @functools.wraps(func)\n",
" def wrapper(*args, **kwargs):\n",
" print(\"Running function:\", func.__name__)\n",
" func(*args, **kwargs)\n",
" print(\"Finished running function:\", func.__name__)\n",
" return wrapper\n",
"\n",
"def timer(func):\n",
" @functools.wraps(func)\n",
" def wrapper(*args, **kwargs): \n",
" begin = time.time() \n",
" func(*args, **kwargs)\n",
" end = time.time() \n",
" print(\"Total time taken:\", end - begin) \n",
" return wrapper\n",
"\n",
"@timer\n",
"@logger\n",
"def factorial(num): \n",
" print(math.factorial(num)) "
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Running function: factorial\n",
"3628800\n",
"Finished running function: factorial\n",
"Total time taken: 0.00023889541625976562\n"
]
}
],
"source": [
"factorial(10)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3628800\n"
]
}
],
"source": [
"factorial.__wrapped__.__wrapped__(10)"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3628800\n"
]
}
],
"source": [
"inspect.unwrap(factorial)(10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. Getting current state of generators\n",
"\n",
"- getgeneratorstate\n",
"- getgeneratorlocals"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"def values_gen():\n",
" for x in range(3):\n",
" yield x"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"gen = values_gen()"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{}"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inspect.getgeneratorlocals(gen)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'GEN_CREATED'"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inspect.getgeneratorstate(gen)"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"next(gen)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7. Getting traceback frames\n",
"\n",
"- trace\n",
"\n",
"> Return a list of frame records for the stack between the current frame and the frame in which an exception currently being handled was raised in. The first entry in the list represents the caller; the last entry represents where the exception was raised."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[' do_something()\\n'] 8\n",
"[' divide(1,0)\\n'] 5\n",
"[' return a/b\\n'] 2\n"
]
}
],
"source": [
"def divide(a,b):\n",
" return a/b\n",
"\n",
"def do_something():\n",
" divide(1,0)\n",
" \n",
"try:\n",
" do_something()\n",
"except:\n",
" for frame in inspect.trace():\n",
" print(frame.code_context, frame.lineno)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment