Python list source code
How to retrieve source code of Python functionsHow to retrieve source code of Python functionsLearn to use the inspect and dill libraries to access Python functions' source code.16 May 2018 Xiaodong DengFeed 288 upImage by : Opensource.com x Subscribe nowSometimes we want to know what some functions' source codes look like or where they are, or we need to manipulate the source codes as character strings. In such cases, we need to have a convenient way to retrieve our Python functions' source codes. More Python Resources
inspectinspectis a built-in library. It's already there after you install Python on your computer. The inspect module provides several useful functions to help you get information about live objects, such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. Among its many features, its capability to retrieve the source code of functions stands out.
In IPython or Jupyter, we can also use this method to retrieve the source code of the functions that we defined in the console.
Note that retrieving source codes of self-defined functions only works in IPython or Jupyter. If we are using plain Python and define a function interactively, we will encounter errorIOError: could not get source codeand will not be able to retrieve the source code. This is because its setting only supports objects loaded from files, not interactive sessions. dilldillextends Python's pickle module for serializing and deserializing Python objects to the majority of the built-in Python types. At the same time, it can also retrieve the source code of your Python objects. Please notedillis not a standard library, so you must install it separately. Its API is quite similar toinspect's.
However, a big difference between dill and inspect is that dill's retrieving feature supports self-defined objects in the plain Python console. TopicsPython Programming About the authorXiaodong Deng - From China and staying in Singapore now. I majored in mathematics during both my bachelor and MSc studies. But then I found dealing with coding is more interesting. Thinking from engineering perspective really helps me a lot. For more information, please refer to my webiste XD-DENG.com. More about me Recommended readingAnyone can compile open source code in these three simple steps Tips for formatting when printing to console from C++ 7 key components of observability in Python How to package your Python code 10 eureka moments of coding in the community What you need to know about containers for Python |