Self Nanny
Moshe Zadka
moshez at math.huji.ac.il
Sat Mar 4 08:11:10 EST 2000
This egoless nanny check that every method has a first argument named
"self". Please use it and enjoy!
-------------- selfnanny.py -----------------------
#!/usr/local/bin/python
import parser, symbol, types
def check_file(file):
return check_string(file.read())
def check_string(s):
return check_ast(parser.suite(s))
def check_ast(ast):
return check_tuple(ast.totuple(1)) # retain line numbers
def check_tuple(tup, classname=None):
if type(tup) != types.TupleType:
return []
problems = []
if tup[0] == symbol.funcdef:
if classname is not None:
args = get_function_args(tup)
if not args or args[0] != 'self':
funcname, funcline = tup[2][1:]
problems.append((funcline, funcname, classname))
classname = None
if tup[0] == symbol.classdef:
classname = tup[2][1]
for t in tup[1:]:
problems.extend(check_tuple(t, classname))
return problems
def get_function_args(tup):
ret = []
for t in tup[1:]:
if t[0] == symbol.parameters:
parameters = t
arglist = ()
for t in parameters[1:]:
if t[0] == symbol.varargslist:
arglist = t
for arg in arglist[1:]:
if arg[0] == symbol.fpdef:
ret.append(arg[1][1])
return ret
def format_problem(problem):
s = 'line %d: method %s in class %s missing first argument "self"'
return s % problem
def print_problems(problems):
for problem in problems:
print format_problem(problem)
def nanny(filename):
print_problems(check_file(open(filename)))
if __name__=='__main__':
import sys
for filename in sys.argv[1:]:
nanny(filename)
--------------- selfnanny.py ------------------------------
--
Moshe Zadka <mzadka at geocities.com>.
http://www.oreilly.com/news/prescod_0300.html
More information about the Python-list
mailing list