faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes

Entry

Self Nanny

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 381, Moshe Zadka


"""
Packages: core_python;oop;miscellaneous
"""
"""
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)