Get python module code

Модуль inspect в Python

Модуль inspect Python – очень полезный модуль, который используется для интроспекции объектов в программе и просмотра исходного кода модулей, классов и функций, которые используются во всей программе.

Модуль фактически может использоваться для извлечения исходного кода самой функции, анализа аргументов, которые эта функция принимает.

Предоставление образца модуля

Сейчас мы создадим образец модуля с некоторыми функциями, классами и строками документации в Python. Вот фрагмент кода для sample.py:

def module_funct(arg1, arg2 = 'default', *args): """This is a module-level function.""" local_var = arg1 * 3 return local_var class X(object): """Definition for X class.""" def __init__(self, name): self.name = name def get_name(self): "Returns the name of the instance." return self.name x_obj = X('sample_instance') class Y(X): """This is the Y class, child of X class. """ # This method is not part of X class. def do_something(self): """Anything can be done here.""" def get_name(self): "Overrides version from X" return 'Y(' + self.name + ')'

Теперь, когда у нас есть образец модуля, готовый к использованию, мы можем начать извлекать и анализировать его исходный код, строку документации и детали объекта. Давайте начнем.

Изучение модуля

Давайте начнем с самоанализа определенного нами образца модуля. Обратите внимание, что для этого у нас есть файл образца модуля sample.py в том же каталоге, в котором мы выполняем наши скрипты. Вот фрагмент образца кода о том, как мы можем проверить наш модуль:

import inspect import sample for name, data in inspect.getmembers(sample): if name.startswith('__'): continue print('<> : '.format(name, data))

Посмотрим на результат этой программы:

Модуль самоанализа с инспектированием

Получение классов

Мы можем получить все классы, присутствующие в модуле, и предпринять действия, когда найдем класс, который искали:

import inspect import sample for key, data in inspect.getmembers(sample, inspect.isclass): print('<> : '.format(key, data))

Посмотрим на результат этой программы:

Изучение классов модулей с помощью inspect

Изучение методов класса

На этот раз мы пойдем дальше, исследуя методы, присутствующие в классе. Обратите внимание, что мы используем один и тот же метод getmembers, отличается только идентификатор свойства, то есть isfunction:

import inspect from pprint import pprint import sample pprint(inspect.getmembers(sample.X, inspect.isfunction))

Посмотрим на результат этой программы:

Изучение методов класса

Проверка объектов класса

С помощью модуля inspect можно отслеживать все экземпляры класса, созданные в программе, с помощью одного вызова функции:

import inspect from pprint import pprint import sample x = sample.X(name='inspect_getmembers') pprint(inspect.getmembers(x, inspect.ismethod))

Посмотрим на результат этой программы:

Проверка объектов класса

Получение строки документации для класса

Модуль inspect часто используется в инструментах Python, которые автоматизируют процесс извлечения классов и строк документации их методов, которые могут быть представлены конечным пользователям. Это означает, что разработчик может просто поместить строки документации в метод, и ту же строку можно использовать для представления другому разработчику приложения:

import inspect import sample print('X.__doc__:') print(sample.X.__doc__) print() print('getdoc(X):') print(inspect.getdoc(sample.X))

Пример inspect getdoc в python

Получение исходного кода класса

В интеллектуальных средах, таких как IDE, модуль inspect используется для представления исходного кода модулей, классов и функций:

import inspect import sample print(inspect.getsource(sample.Y))

Посмотрим на результат этой программы:

Читайте также:  Java in linux shell

Получение исходного кода класса

Получение источника метода

На этот раз мы получаем исходный код только одного метода:

import inspect import sample print(inspect.getsource(sample.Y.get_name))

Посмотрим на результат этой программы:

Получение исходного кода метода

Получение подписи метода

В качестве последнего примера мы получим сигнатуру метода, который часто используется в Intellisense IDE, чтобы представить разработчикам, какие аргументы принимает метод:

import inspect import sample print(inspect.signature(sample.module_funct))

Посмотрим на результат этой программы:

Источник

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.

Читайте также:  Html select text margin

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 −

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.

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.

Читайте также:  Failed java lang reflect invocationtargetexception

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')

Источник

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.

Источник

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