Function source code python

How to retrieve source code of Python functions

code.org keynote address

Sometimes 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.

There are two Python libraries that may help:

inspect

inspect is 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.

import pandas import inspect
source_DF = inspect.getsource(pandas.DataFrame) print(type(source_DF))

«»» Two-dimensional size-mutable, potentially heterogeneous tabular data

structure with labeled axes (rows and columns). Arithmetic operations

source_file_DF = inspect.getsourcefile(pandas.DataFrame) print(source_file_DF)
sourcelines_DF = inspect.getsourcelines(pandas.DataFrame) print(type(sourcelines_DF)) print(len(sourcelines_DF)) print(type(sourcelines_DF[0]))

In IPython or Jupyter, we can also use this method to retrieve the source code of the functions that we defined in the console.

def test(x): return x*2 print(inspect.getsource(test)) 
print(inspect.getsourcefile(test)) 
print(inspect.getsourcelines(test))

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 error IOError: could not get source code and will not be able to retrieve the source code. This is because its setting only supports objects loaded from files, not interactive sessions.

dill

dill extends 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 note dill is not a standard library, so you must install it separately.

Its API is quite similar to inspect ‘s.

import dill source_DF = dill.source.getsource(pandas.DataFrame) print(type(source_DF)) print(len(source_DF)) print(source_DF[:200]) source_file_DF = dill.source.getsourcefile(pandas.DataFrame) print(source_file_DF) sourcelines_DF = dill.source.getsourcelines(pandas.DataFrame) print(type(sourcelines_DF)) print(len(sourcelines_DF)) print(type(sourcelines_DF[0])) 195262 class DataFrame(NDFrame): """ Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row a /Users/XD/anaconda/lib/python2.7/site-packages/pandas/core/frame.py 2

However, a big difference between dill and inspect is that dill ‘s retrieving feature supports self-defined objects in the plain Python console.

Читайте также:  Document write html style

Источник

How to retrieve source code from Python objects?

This code defines a simple function my function that accepts two arguments and returns the sum of those arguments. We then retrieve the source code of the my function function using the inspect.getsource function and store it in the source code variable. Finally, the source code is output to the console.

The inspect.getsource function operates by reading the function’s source code from the file in which it is defined. It returns the function’s entire source code as a string, including any comments or blank lines present in the source code.

The inspect.getsourcefile function can also be used to retrieve the filename containing the source code of a function or module. This is helpful if you need to locate the file containing a specific function or module.

The following example demonstrates how to retrieve the file name containing a function’s source code −

Example

import inspect def my_function(x, y): return x + y source_file = inspect.getsourcefile(my_function) print(source_file)

Output

This code defines the same my function function as before and retrieves the file name containing the function’s source code using the inspect.getsourcefile function. This function returns the file name as a string, and not the actual source code.

The inspect module offers several functions for retrieving information about Python objects, including their source code. Here are some additional examples −

To retrieve the source code of a class method, call inspect.getsource on the method itself −

Example

import inspect class MyClass: def my_method(self, x, y): return x + y source_code = inspect.getsource(MyClass.my_method) print(source_code)

Output

def my_method(self, x, y): return x + y

In this example, the class MyClass has a single method called my method that accepts two arguments and returns their sum. The source code for the MyClass.my method method is then retrieved using inspect.getsource.

To retrieve the source code of a module in its entirety, use the inspect.getsource function on the module itself −

Example

import inspect import my_module source_code = inspect.getsource(my_module) print(source_code)

In this example, we import the my module module and retrieve its source code using inspect.getsource.

You can also use the inspect.getfile function to get the name of the file that holds the source code for a module, class, or function. Similar to inspect.getsourcefile, this function returns the filename as a string. This example demonstrates how to retrieve the filename of a module using inspect.getfile −

Читайте также:  Floating value in javascript

Example

import inspect import my_module source_file = inspect.getfile(my_module) print(source_file)

This code imports the my module module and uses inspect.getfile to retrieve the source code file’s name. Note that this function returns the file’s absolute path.

The dis module is another way to retrieve the source code of a Python function. The dis module gives you a disassembler for Python bytecode, which you can use to look at the bytecode instructions for a function. By decompiling the bytecode, it is possible to gain a more comprehensive understanding of how the function operates, including the exact order of operations.

Here is an example of how to retrieve the bytecode instructions of a function using the dis module −

Example

import dis def my_function(x, y): return x + y bytecode = dis.Bytecode(my_function) for instruction in bytecode: print(instruction)

Output

Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='x', argrepr='x', offset=0, starts_line=3, is_jump_target=False) Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='y', argrepr='y', offset=2, starts_line=None, is_jump_target=False) Instruction(opname='BINARY_ADD', opcode=23, arg=None, argval=None, argrepr='', offset=4, starts_line=None, is_jump_target=False) Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=6, starts_line=None, is_jump_target=False)

In this example, a simple function called my_function is defined that accepts two arguments and returns their sum. A dis.Bytecode object is then created by passing the my_function function to the dis.Bytecode function Object() < [native code] >. This gives us a view of the function’s bytecode instructions after they have been taken apart. We can then use a for loop to go through these instructions and print them to the console.

This code will return a series of dis.Instruction objects, which represent the function’s bytecode instructions. Each dis.Instruction object includes attributes such as opname (the name of the bytecode instruction), argval (the instruction’s argument), and offset (the byte offset of the instruction in the function’s bytecode). By looking at these attributes, you can learn everything you need to know about how the function works.

Please be aware that the dis module can be quite low-level and may not be appropriate for all use cases. However, if you need a thorough understanding of how a function operates, it can be a useful tool to have. We use the getsource() method of the inspect module to get the source code of the function.

Читайте также:  Css object fit image

Example

This returns the text of the object’s source code. It is possible for the argument to be a module, class, method, function, traceback, frame, or code object. Returns the source code as a single string. If it is not possible to retrieve the source code, an IOError is generated.

If the function is compiled from a string, stream, or imported from a previously compiled file, then its source code cannot be retrieved.

Following is how we import the inspect module and retrieve the source code for a given script

Example

#baz.py import inspect class foo: def bar(): print ('Hello') print(inspect.getsource(foo))

Output

class foo: def bar(): print ('Hello')

Источник

Доступ к исходному коду Python и байт-коду

Интерпретатор Python компилирует код в байт — код перед выполнением его на виртуальной машине Python.

Вот как просмотреть байт-код функции Python

Функция dis.dis в модуле Дис возвратит декомпилированный байткод функции переданного ему.

Изучение объекта кода функции

CPython разрешает доступ к объекту кода для объекта функции.

__code__ объект содержит необработанный байт — код ( co_code ) функции, а также другую информацию , такую как константы и имена переменных.

Показать исходный код объекта Объекты, которые не являются встроенными

Чтобы напечатать исходный код использования объекта в Python inspect .Обратите внимание, что это не будет работать ни для встроенных объектов, ни для объектов, определенных в интерактивном режиме. Для этого вам понадобятся другие методы, объясненные позже.

Вот как напечатать исходный код метода randint от random модуля:

 import random import inspect print(inspect.getsource(random.randint)) # Output: # def randint(self, a, b): # """Return random integer in range [a, b], including both end points. # """ # # return self.randrange(a, b+1) 

Просто напечатать строку документации

 print(inspect.getdoc(random.randint)) # Output: # Return random integer in range [a, b], including both end points. 

Печать полный путь к файлу , в котором метод random.randint определяется:

 print(inspect.getfile(random.randint)) # c:\Python35\lib\random.py print(random.randint.__code__.co_filename) # equivalent to the above # c:\Python35\lib\random.py 

Объекты, определенные в интерактивном режиме

Если объект определен в интерактивном режиме inspect не может предоставить исходный код , но вы можете использовать dill.source.getsource вместо

 # define a new function in the interactive shell def add(a, b): return a + b print(add.__code__.co_filename) # Output: import dill print dill.source.getsource(add) # def add(a, b): return a + b 

Исходный код для встроенных функций Python написано на C и может быть доступен только глядя на исходном коде языка Python (размещенные на ртутном или загрузить с https://www.python.org/downloads/source/ ).

 print(inspect.getsource(sorted)) # raises a TypeError type(sorted) #

Источник

Оцените статью