Форум сайта python.su
До каких пределов можно использовать интроспекцию в Питоне? Существует ли простой способ получить содержимое тела функции или метода (в виде строки)?
Офлайн
ну, с учетом того, что питон перед исполнением компилируется в байкод. то можно получить этот байткод.
import dis
dis.dis(f_name)
Если я правильно понял вопрос.
Отредактировано (Ноя. 26, 2008 21:47:11)
Офлайн
Я имею в виду, что мне надо получить код функции и желательно с ее названием, аргументами и телом функции:
def cmp(x,y):
if x < y: return -1
elif x > y: return 1
else return 0
cmp
x,y
if x < y: return -1
elif x > y: return 1
else return 0
Офлайн
не думаю что можно из байткода восстановить исходник.
Офлайн
Сам нашел отличное решение. В Питоне для целей интроспекции существует специальный модуль inspect.
Get useful information from live Python objects.
This module encapsulates the interface provided by the internal special
attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
It also provides some help for examining source code and class layout.
Here are some of the useful functions provided by this module:
ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
isroutine() - check object types
getmembers() - get members of an object that satisfy a given condition
getfile(), getsourcefile(), getsource() - find an object's source code
getdoc(), getcomments() - get documentation on an object
getmodule() - determine the module that an object came from
getclasstree() - arrange classes so as to represent their hierarchy
getargspec(), getargvalues() - get info about function arguments
formatargspec(), formatargvalues() - format an argument spec
getouterframes(), getinnerframes() - get info about frames
currentframe() - get the current stack frame
stack(), trace() - get info about frames on the stack or in a traceback
import inspect
def cmp(x,y):
if x < y: return -1
elif x > y: return 1
else return 0
print inspect.getsource(cmp)
Офлайн
Если есть только .pyc файл без .py - getsource не работает
Офлайн
class myClass():
def __init__(self,data):
self.__data = data
def myFunc():
return 'myFunc'
import inspect
print inspect.getsource(myClass)
Офлайн