如何使用python识别只有一行代码的函数
我的目标是确定一行中的方法/函数。例如,在scenario.py中有两个函数,其中只有一行代码。我的工作是,我有一个大型应用程序,我将解析该应用程序中的所有python文件,并确定只有一行的函数如何使用python识别只有一行代码的函数,python,parsing,Python,Parsing,我的目标是确定一行中的方法/函数。例如,在scenario.py中有两个函数,其中只有一行代码。我的工作是,我有一个大型应用程序,我将解析该应用程序中的所有python文件,并确定只有一行的函数 #Scenario.py line 1---> class parent: line 2---> def father(self): line 3---> print "dad" line 4---> def mother(self): line
#Scenario.py
line 1---> class parent:
line 2---> def father(self):
line 3---> print "dad"
line 4---> def mother(self):
line 5---> print "mom"
Sample Output:
One liner function at : line=2, line =4
使用:
印刷品
2
4
注意
如果代码中存在语法错误,此代码将引发SyntaxError
。此外,如果您尝试用Python 2解析Python 3代码(反之亦然),则可能会引发SyntaxError
(并非总是如此)
使现代化
上述语句应替换为以下内容:
for f in iter_functions(code):
if len({node.lineno for stmt in f.body for node in ast.walk(stmt)
if hasattr(node, 'lineno')}) == 1:
print(f.lineno)
否则,以下功能将被视为一行:
def func():
if True:
pass
使用inspect和regex: import re import inspect import my_module for name, func in inspect.getmembers(my_module, predicate=inspect.isfunction): func_source = inspect.getsource(func) nlines = len(re.findall('\n', func_source)) print (name, nlines) 进口稀土 进口检验 导入my_模块 对于inspect.getmembers(my_模块,谓词=inspect.isfunction)中的名称func: func_source=inspect.getsource(func) nlines=len(关于findall('\n',函数源)) 打印(名称、行)
下面是一种使用“实时”Python函数的方法。注意,这是非常特定于CPython的
def func(x):
print(x)
def numlines(func):
lnotab = bytearray(func.__code__.co_lnotab)
return sum(lnotab[3::2]) + (bool(lnotab) and min(lnotab[1], 1))
print(numlines(func) < 2) # True
我的原始代码被严重破坏;它计算语句而不是行数。在我的辩护中,我把它写在了我的头顶上,并错误地记住了关于lnotab
的细节
请注意,在Python3中,转换为
bytearray
是不必要的(因为co\u lnotab
已经是bytes
),但这样做会使代码同时适用于Python2.x和3.x,其中co\u lnotab
是str
(我认为2.6和更高版本已经是\u\u-code
)只是好奇,这有什么用?可能有一个更好的解决方案。实际上,我正在将修饰符插入到具有多行的函数上,并在运行时检索一些动态信息myfunc
未定义。可能是func
。您应该将func
解压为name,func
。并且,此代码仅处理模块级函数(而不是方法)。如果的func(x)
的主体是If True:pass
(2行),oneliner
返回True
。Yep Yep Yep。搞砸了。我希望现在能把它修好。我删除了oneliner()
函数,因为它很容易测试numlines(func)
。
def func(x):
print(x)
def numlines(func):
lnotab = bytearray(func.__code__.co_lnotab)
return sum(lnotab[3::2]) + (bool(lnotab) and min(lnotab[1], 1))
print(numlines(func) < 2) # True
def numlines_including_docstring(func):
return sum(bytearray(func.__code__.co_lnotab)[1::2])