Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

design_analysis.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006, 2009-2010, 2012-2015 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2012, 2014 Google, Inc.
  4. # Copyright (c) 2014-2017 Claudiu Popa <pcmanticore@gmail.com>
  5. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  6. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  7. # Copyright (c) 2016 Łukasz Rogalski <rogalski.91@gmail.com>
  8. # Copyright (c) 2017 ahirnish <ahirnish@gmail.com>
  9. # Copyright (c) 2018 Ashley Whetter <ashley@awhetter.co.uk>
  10. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  11. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  12. """check for signs of poor design"""
  13. from collections import defaultdict
  14. import re
  15. from astroid import If, BoolOp
  16. from astroid import decorators
  17. from pylint.interfaces import IAstroidChecker
  18. from pylint.checkers import BaseChecker
  19. from pylint.checkers import utils as checker_utils
  20. from pylint.checkers.utils import check_messages
  21. from pylint import utils
  22. MSGS = {
  23. 'R0901': ('Too many ancestors (%s/%s)',
  24. 'too-many-ancestors',
  25. 'Used when class has too many parent classes, try to reduce \
  26. this to get a simpler (and so easier to use) class.'),
  27. 'R0902': ('Too many instance attributes (%s/%s)',
  28. 'too-many-instance-attributes',
  29. 'Used when class has too many instance attributes, try to reduce \
  30. this to get a simpler (and so easier to use) class.'),
  31. 'R0903': ('Too few public methods (%s/%s)',
  32. 'too-few-public-methods',
  33. 'Used when class has too few public methods, so be sure it\'s \
  34. really worth it.'),
  35. 'R0904': ('Too many public methods (%s/%s)',
  36. 'too-many-public-methods',
  37. 'Used when class has too many public methods, try to reduce \
  38. this to get a simpler (and so easier to use) class.'),
  39. 'R0911': ('Too many return statements (%s/%s)',
  40. 'too-many-return-statements',
  41. 'Used when a function or method has too many return statement, \
  42. making it hard to follow.'),
  43. 'R0912': ('Too many branches (%s/%s)',
  44. 'too-many-branches',
  45. 'Used when a function or method has too many branches, \
  46. making it hard to follow.'),
  47. 'R0913': ('Too many arguments (%s/%s)',
  48. 'too-many-arguments',
  49. 'Used when a function or method takes too many arguments.'),
  50. 'R0914': ('Too many local variables (%s/%s)',
  51. 'too-many-locals',
  52. 'Used when a function or method has too many local variables.'),
  53. 'R0915': ('Too many statements (%s/%s)',
  54. 'too-many-statements',
  55. 'Used when a function or method has too many statements. You \
  56. should then split it in smaller functions / methods.'),
  57. 'R0916': ('Too many boolean expressions in if statement (%s/%s)',
  58. 'too-many-boolean-expressions',
  59. 'Used when a if statement contains too many boolean '
  60. 'expressions'),
  61. }
  62. SPECIAL_OBJ = re.compile('^_{2}[a-z]+_{2}$')
  63. def _count_boolean_expressions(bool_op):
  64. """Counts the number of boolean expressions in BoolOp `bool_op` (recursive)
  65. example: a and (b or c or (d and e)) ==> 5 boolean expressions
  66. """
  67. nb_bool_expr = 0
  68. for bool_expr in bool_op.get_children():
  69. if isinstance(bool_expr, BoolOp):
  70. nb_bool_expr += _count_boolean_expressions(bool_expr)
  71. else:
  72. nb_bool_expr += 1
  73. return nb_bool_expr
  74. class MisdesignChecker(BaseChecker):
  75. """checks for sign of poor/misdesign:
  76. * number of methods, attributes, local variables...
  77. * size, complexity of functions, methods
  78. """
  79. __implements__ = (IAstroidChecker,)
  80. # configuration section name
  81. name = 'design'
  82. # messages
  83. msgs = MSGS
  84. priority = -2
  85. # configuration options
  86. options = (('max-args',
  87. {'default' : 5, 'type' : 'int', 'metavar' : '<int>',
  88. 'help': 'Maximum number of arguments for function / method'}
  89. ),
  90. ('max-locals',
  91. {'default' : 15, 'type' : 'int', 'metavar' : '<int>',
  92. 'help': 'Maximum number of locals for function / method body'}
  93. ),
  94. ('max-returns',
  95. {'default' : 6, 'type' : 'int', 'metavar' : '<int>',
  96. 'help': 'Maximum number of return / yield for function / '
  97. 'method body'}
  98. ),
  99. ('max-branches',
  100. {'default' : 12, 'type' : 'int', 'metavar' : '<int>',
  101. 'help': 'Maximum number of branch for function / method body'}
  102. ),
  103. ('max-statements',
  104. {'default' : 50, 'type' : 'int', 'metavar' : '<int>',
  105. 'help': 'Maximum number of statements in function / method '
  106. 'body'}
  107. ),
  108. ('max-parents',
  109. {'default' : 7,
  110. 'type' : 'int',
  111. 'metavar' : '<num>',
  112. 'help' : 'Maximum number of parents for a class (see R0901).'}
  113. ),
  114. ('max-attributes',
  115. {'default' : 7,
  116. 'type' : 'int',
  117. 'metavar' : '<num>',
  118. 'help' : 'Maximum number of attributes for a class \
  119. (see R0902).'}
  120. ),
  121. ('min-public-methods',
  122. {'default' : 2,
  123. 'type' : 'int',
  124. 'metavar' : '<num>',
  125. 'help' : 'Minimum number of public methods for a class \
  126. (see R0903).'}
  127. ),
  128. ('max-public-methods',
  129. {'default' : 20,
  130. 'type' : 'int',
  131. 'metavar' : '<num>',
  132. 'help' : 'Maximum number of public methods for a class \
  133. (see R0904).'}
  134. ),
  135. ('max-bool-expr',
  136. {'default': 5,
  137. 'type': 'int',
  138. 'metavar': '<num>',
  139. 'help': 'Maximum number of boolean expressions in a if '
  140. 'statement'}
  141. ),
  142. )
  143. def __init__(self, linter=None):
  144. BaseChecker.__init__(self, linter)
  145. self.stats = None
  146. self._returns = None
  147. self._branches = None
  148. self._stmts = 0
  149. def open(self):
  150. """initialize visit variables"""
  151. self.stats = self.linter.add_stats()
  152. self._returns = []
  153. self._branches = defaultdict(int)
  154. @decorators.cachedproperty
  155. def _ignored_argument_names(self):
  156. return utils.get_global_option(self, 'ignored-argument-names', default=None)
  157. @check_messages('too-many-ancestors', 'too-many-instance-attributes',
  158. 'too-few-public-methods', 'too-many-public-methods')
  159. def visit_classdef(self, node):
  160. """check size of inheritance hierarchy and number of instance attributes
  161. """
  162. nb_parents = len(list(node.ancestors()))
  163. if nb_parents > self.config.max_parents:
  164. self.add_message('too-many-ancestors', node=node,
  165. args=(nb_parents, self.config.max_parents))
  166. if len(node.instance_attrs) > self.config.max_attributes:
  167. self.add_message('too-many-instance-attributes', node=node,
  168. args=(len(node.instance_attrs),
  169. self.config.max_attributes))
  170. @check_messages('too-few-public-methods', 'too-many-public-methods')
  171. def leave_classdef(self, node):
  172. """check number of public methods"""
  173. my_methods = sum(1 for method in node.mymethods()
  174. if not method.name.startswith('_'))
  175. # Does the class contain less than n public methods ?
  176. # This checks only the methods defined in the current class,
  177. # since the user might not have control over the classes
  178. # from the ancestors. It avoids some false positives
  179. # for classes such as unittest.TestCase, which provides
  180. # a lot of assert methods. It doesn't make sense to warn
  181. # when the user subclasses TestCase to add his own tests.
  182. if my_methods > self.config.max_public_methods:
  183. self.add_message('too-many-public-methods', node=node,
  184. args=(my_methods,
  185. self.config.max_public_methods))
  186. # stop here for exception, metaclass and interface classes
  187. if node.type != 'class' or checker_utils.is_enum_class(node):
  188. return
  189. all_methods = sum(1 for method in node.methods()
  190. if not method.name.startswith('_'))
  191. # Special methods count towards the number of public methods,
  192. # but don't count towards there being too many methods.
  193. for method in node.mymethods():
  194. if SPECIAL_OBJ.search(method.name) and method.name != '__init__':
  195. all_methods += 1
  196. # Does the class contain more than n public methods ?
  197. # This checks all the methods defined by ancestors and
  198. # by the current class.
  199. if all_methods < self.config.min_public_methods:
  200. self.add_message('too-few-public-methods', node=node,
  201. args=(all_methods,
  202. self.config.min_public_methods))
  203. @check_messages('too-many-return-statements', 'too-many-branches',
  204. 'too-many-arguments', 'too-many-locals',
  205. 'too-many-statements', 'keyword-arg-before-vararg')
  206. def visit_functiondef(self, node):
  207. """check function name, docstring, arguments, redefinition,
  208. variable names, max locals
  209. """
  210. # init branch and returns counters
  211. self._returns.append(0)
  212. # check number of arguments
  213. args = node.args.args
  214. ignored_argument_names = self._ignored_argument_names
  215. if args is not None:
  216. ignored_args_num = 0
  217. if ignored_argument_names:
  218. ignored_args_num = sum(1 for arg in args if ignored_argument_names.match(arg.name))
  219. argnum = len(args) - ignored_args_num
  220. if argnum > self.config.max_args:
  221. self.add_message('too-many-arguments', node=node,
  222. args=(len(args), self.config.max_args))
  223. else:
  224. ignored_args_num = 0
  225. # check number of local variables
  226. locnum = len(node.locals) - ignored_args_num
  227. if locnum > self.config.max_locals:
  228. self.add_message('too-many-locals', node=node,
  229. args=(locnum, self.config.max_locals))
  230. # init statements counter
  231. self._stmts = 1
  232. visit_asyncfunctiondef = visit_functiondef
  233. @check_messages('too-many-return-statements', 'too-many-branches',
  234. 'too-many-arguments', 'too-many-locals',
  235. 'too-many-statements')
  236. def leave_functiondef(self, node):
  237. """most of the work is done here on close:
  238. checks for max returns, branch, return in __init__
  239. """
  240. returns = self._returns.pop()
  241. if returns > self.config.max_returns:
  242. self.add_message('too-many-return-statements', node=node,
  243. args=(returns, self.config.max_returns))
  244. branches = self._branches[node]
  245. if branches > self.config.max_branches:
  246. self.add_message('too-many-branches', node=node,
  247. args=(branches, self.config.max_branches))
  248. # check number of statements
  249. if self._stmts > self.config.max_statements:
  250. self.add_message('too-many-statements', node=node,
  251. args=(self._stmts, self.config.max_statements))
  252. leave_asyncfunctiondef = leave_functiondef
  253. def visit_return(self, _):
  254. """count number of returns"""
  255. if not self._returns:
  256. return # return outside function, reported by the base checker
  257. self._returns[-1] += 1
  258. def visit_default(self, node):
  259. """default visit method -> increments the statements counter if
  260. necessary
  261. """
  262. if node.is_statement:
  263. self._stmts += 1
  264. def visit_tryexcept(self, node):
  265. """increments the branches counter"""
  266. branches = len(node.handlers)
  267. if node.orelse:
  268. branches += 1
  269. self._inc_branch(node, branches)
  270. self._stmts += branches
  271. def visit_tryfinally(self, node):
  272. """increments the branches counter"""
  273. self._inc_branch(node, 2)
  274. self._stmts += 2
  275. @check_messages('too-many-boolean-expressions')
  276. def visit_if(self, node):
  277. """increments the branches counter and checks boolean expressions"""
  278. self._check_boolean_expressions(node)
  279. branches = 1
  280. # don't double count If nodes coming from some 'elif'
  281. if node.orelse and (len(node.orelse) > 1 or
  282. not isinstance(node.orelse[0], If)):
  283. branches += 1
  284. self._inc_branch(node, branches)
  285. self._stmts += branches
  286. def _check_boolean_expressions(self, node):
  287. """Go through "if" node `node` and counts its boolean expressions
  288. if the "if" node test is a BoolOp node
  289. """
  290. condition = node.test
  291. if not isinstance(condition, BoolOp):
  292. return
  293. nb_bool_expr = _count_boolean_expressions(condition)
  294. if nb_bool_expr > self.config.max_bool_expr:
  295. self.add_message('too-many-boolean-expressions', node=condition,
  296. args=(nb_bool_expr, self.config.max_bool_expr))
  297. def visit_while(self, node):
  298. """increments the branches counter"""
  299. branches = 1
  300. if node.orelse:
  301. branches += 1
  302. self._inc_branch(node, branches)
  303. visit_for = visit_while
  304. def _inc_branch(self, node, branchesnum=1):
  305. """increments the branches counter"""
  306. self._branches[node.scope()] += branchesnum
  307. def register(linter):
  308. """required method to auto register this checker """
  309. linter.register_checker(MisdesignChecker(linter))