classes.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. # Copyright (c) 2003-2011 LOGILAB S.A. (Paris, FRANCE).
  2. # http://www.logilab.fr/ -- mailto:contact@logilab.fr
  3. #
  4. # This program is free software; you can redistribute it and/or modify it under
  5. # the terms of the GNU General Public License as published by the Free Software
  6. # Foundation; either version 2 of the License, or (at your option) any later
  7. # version.
  8. #
  9. # This program is distributed in the hope that it will be useful, but WITHOUT
  10. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License along with
  14. # this program; if not, write to the Free Software Foundation, Inc.,
  15. # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  16. """classes checker for Python code
  17. """
  18. from __future__ import generators
  19. from logilab import astng
  20. from logilab.astng import YES, Instance, are_exclusive, AssAttr
  21. from pylint.interfaces import IASTNGChecker
  22. from pylint.checkers import BaseChecker
  23. from pylint.checkers.utils import (PYMETHODS, overrides_a_method,
  24. check_messages, is_attr_private, is_attr_protected, node_frame_class)
  25. def class_is_abstract(node):
  26. """return true if the given class node should be considered as an abstract
  27. class
  28. """
  29. for method in node.methods():
  30. if method.parent.frame() is node:
  31. if method.is_abstract(pass_is_abstract=False):
  32. return True
  33. return False
  34. MSGS = {
  35. 'F0202': ('Unable to check methods signature (%s / %s)',
  36. 'Used when PyLint has been unable to check methods signature \
  37. compatibility for an unexpected reason. Please report this kind \
  38. if you don\'t make sense of it.'),
  39. 'E0202': ('An attribute affected in %s line %s hide this method',
  40. 'Used when a class defines a method which is hidden by an '
  41. 'instance attribute from an ancestor class or set by some '
  42. 'client code.'),
  43. 'E0203': ('Access to member %r before its definition line %s',
  44. 'Used when an instance member is accessed before it\'s actually\
  45. assigned.'),
  46. 'W0201': ('Attribute %r defined outside __init__',
  47. 'Used when an instance attribute is defined outside the __init__\
  48. method.'),
  49. 'W0212': ('Access to a protected member %s of a client class', # E0214
  50. 'Used when a protected member (i.e. class member with a name \
  51. beginning with an underscore) is access outside the class or a \
  52. descendant of the class where it\'s defined.'),
  53. 'E0211': ('Method has no argument',
  54. 'Used when a method which should have the bound instance as \
  55. first argument has no argument defined.'),
  56. 'E0213': ('Method should have "self" as first argument',
  57. 'Used when a method has an attribute different the "self" as\
  58. first argument. This is considered as an error since this is\
  59. a so common convention that you shouldn\'t break it!'),
  60. 'C0202': ('Class method should have %s as first argument', # E0212
  61. 'Used when a class method has an attribute different than "cls"\
  62. as first argument, to easily differentiate them from regular \
  63. instance methods.'),
  64. 'C0203': ('Metaclass method should have "mcs" as first argument', # E0214
  65. 'Used when a metaclass method has an attribute different the \
  66. "mcs" as first argument.'),
  67. 'W0211': ('Static method with %r as first argument',
  68. 'Used when a static method has "self" or "cls" as first argument.'
  69. ),
  70. 'R0201': ('Method could be a function',
  71. 'Used when a method doesn\'t use its bound instance, and so could\
  72. be written as a function.'
  73. ),
  74. 'E0221': ('Interface resolved to %s is not a class',
  75. 'Used when a class claims to implement an interface which is not \
  76. a class.'),
  77. 'E0222': ('Missing method %r from %s interface',
  78. 'Used when a method declared in an interface is missing from a \
  79. class implementing this interface'),
  80. 'W0221': ('Arguments number differs from %s method',
  81. 'Used when a method has a different number of arguments than in \
  82. the implemented interface or in an overridden method.'),
  83. 'W0222': ('Signature differs from %s method',
  84. 'Used when a method signature is different than in the \
  85. implemented interface or in an overridden method.'),
  86. 'W0223': ('Method %r is abstract in class %r but is not overridden',
  87. 'Used when an abstract method (i.e. raise NotImplementedError) is \
  88. not overridden in concrete class.'
  89. ),
  90. 'F0220': ('failed to resolve interfaces implemented by %s (%s)', # W0224
  91. 'Used when a PyLint as failed to find interfaces implemented by \
  92. a class'),
  93. 'W0231': ('__init__ method from base class %r is not called',
  94. 'Used when an ancestor class method has an __init__ method \
  95. which is not called by a derived class.'),
  96. 'W0232': ('Class has no __init__ method',
  97. 'Used when a class has no __init__ method, neither its parent \
  98. classes.'),
  99. 'W0233': ('__init__ method from a non direct base class %r is called',
  100. 'Used when an __init__ method is called on a class which is not \
  101. in the direct ancestors for the analysed class.'),
  102. }
  103. class ClassChecker(BaseChecker):
  104. """checks for :
  105. * methods without self as first argument
  106. * overridden methods signature
  107. * access only to existent members via self
  108. * attributes not defined in the __init__ method
  109. * supported interfaces implementation
  110. * unreachable code
  111. """
  112. __implements__ = (IASTNGChecker,)
  113. # configuration section name
  114. name = 'classes'
  115. # messages
  116. msgs = MSGS
  117. priority = -2
  118. # configuration options
  119. options = (('ignore-iface-methods',
  120. {'default' : (#zope interface
  121. 'isImplementedBy', 'deferred', 'extends', 'names',
  122. 'namesAndDescriptions', 'queryDescriptionFor', 'getBases',
  123. 'getDescriptionFor', 'getDoc', 'getName', 'getTaggedValue',
  124. 'getTaggedValueTags', 'isEqualOrExtendedBy', 'setTaggedValue',
  125. 'isImplementedByInstancesOf',
  126. # twisted
  127. 'adaptWith',
  128. # logilab.common interface
  129. 'is_implemented_by'),
  130. 'type' : 'csv',
  131. 'metavar' : '<method names>',
  132. 'help' : 'List of interface methods to ignore, \
  133. separated by a comma. This is used for instance to not check methods defines \
  134. in Zope\'s Interface base class.'}
  135. ),
  136. ('defining-attr-methods',
  137. {'default' : ('__init__', '__new__', 'setUp'),
  138. 'type' : 'csv',
  139. 'metavar' : '<method names>',
  140. 'help' : 'List of method names used to declare (i.e. assign) \
  141. instance attributes.'}
  142. ),
  143. ('valid-classmethod-first-arg',
  144. {'default' : ('cls',),
  145. 'type' : 'csv',
  146. 'metavar' : '<argument names>',
  147. 'help' : 'List of valid names for the first argument in \
  148. a class method.'}
  149. ),
  150. )
  151. def __init__(self, linter=None):
  152. BaseChecker.__init__(self, linter)
  153. self._accessed = []
  154. self._first_attrs = []
  155. self._meth_could_be_func = None
  156. def visit_class(self, node):
  157. """init visit variable _accessed and check interfaces
  158. """
  159. self._accessed.append({})
  160. self._check_bases_classes(node)
  161. self._check_interfaces(node)
  162. # if not an interface, exception, metaclass
  163. if node.type == 'class':
  164. try:
  165. node.local_attr('__init__')
  166. except astng.NotFoundError:
  167. self.add_message('W0232', args=node, node=node)
  168. @check_messages('E0203', 'W0201')
  169. def leave_class(self, cnode):
  170. """close a class node:
  171. check that instance attributes are defined in __init__ and check
  172. access to existent members
  173. """
  174. # check access to existent members on non metaclass classes
  175. accessed = self._accessed.pop()
  176. if cnode.type != 'metaclass':
  177. self._check_accessed_members(cnode, accessed)
  178. # checks attributes are defined in an allowed method such as __init__
  179. if 'W0201' not in self.active_msgs:
  180. return
  181. defining_methods = self.config.defining_attr_methods
  182. for attr, nodes in cnode.instance_attrs.items():
  183. nodes = [n for n in nodes if not
  184. isinstance(n.statement(), (astng.Delete, astng.AugAssign))]
  185. if not nodes:
  186. continue # error detected by typechecking
  187. attr_defined = False
  188. # check if any method attr is defined in is a defining method
  189. for node in nodes:
  190. if node.frame().name in defining_methods:
  191. attr_defined = True
  192. if not attr_defined:
  193. # check attribute is defined in a parent's __init__
  194. for parent in cnode.instance_attr_ancestors(attr):
  195. attr_defined = False
  196. # check if any parent method attr is defined in is a defining method
  197. for node in parent.instance_attrs[attr]:
  198. if node.frame().name in defining_methods:
  199. attr_defined = True
  200. if attr_defined:
  201. # we're done :)
  202. break
  203. else:
  204. # check attribute is defined as a class attribute
  205. try:
  206. cnode.local_attr(attr)
  207. except astng.NotFoundError:
  208. self.add_message('W0201', args=attr, node=node)
  209. def visit_function(self, node):
  210. """check method arguments, overriding"""
  211. # ignore actual functions
  212. if not node.is_method():
  213. return
  214. klass = node.parent.frame()
  215. self._meth_could_be_func = True
  216. # check first argument is self if this is actually a method
  217. self._check_first_arg_for_type(node, klass.type == 'metaclass')
  218. if node.name == '__init__':
  219. self._check_init(node)
  220. return
  221. # check signature if the method overloads inherited method
  222. for overridden in klass.local_attr_ancestors(node.name):
  223. # get astng for the searched method
  224. try:
  225. meth_node = overridden[node.name]
  226. except KeyError:
  227. # we have found the method but it's not in the local
  228. # dictionary.
  229. # This may happen with astng build from living objects
  230. continue
  231. if not isinstance(meth_node, astng.Function):
  232. continue
  233. self._check_signature(node, meth_node, 'overridden')
  234. break
  235. if node.decorators:
  236. for decorator in node.decorators.nodes:
  237. if isinstance(decorator, astng.Getattr) and \
  238. decorator.attrname in ('getter', 'setter', 'deleter'):
  239. # attribute affectation will call this method, not hiding it
  240. return
  241. if isinstance(decorator, astng.Name) and decorator.name == 'property':
  242. # attribute affectation will either call a setter or raise
  243. # an attribute error, anyway not hiding the function
  244. return
  245. # check if the method is hidden by an attribute
  246. try:
  247. overridden = klass.instance_attr(node.name)[0] # XXX
  248. args = (overridden.root().name, overridden.fromlineno)
  249. self.add_message('E0202', args=args, node=node)
  250. except astng.NotFoundError:
  251. pass
  252. def leave_function(self, node):
  253. """on method node, check if this method couldn't be a function
  254. ignore class, static and abstract methods, initializer,
  255. methods overridden from a parent class and any
  256. kind of method defined in an interface for this warning
  257. """
  258. if node.is_method():
  259. if node.args.args is not None:
  260. self._first_attrs.pop()
  261. if 'R0201' not in self.active_msgs:
  262. return
  263. class_node = node.parent.frame()
  264. if (self._meth_could_be_func and node.type == 'method'
  265. and not node.name in PYMETHODS
  266. and not (node.is_abstract() or
  267. overrides_a_method(class_node, node.name))
  268. and class_node.type != 'interface'):
  269. self.add_message('R0201', node=node)
  270. def visit_getattr(self, node):
  271. """check if the getattr is an access to a class member
  272. if so, register it. Also check for access to protected
  273. class member from outside its class (but ignore __special__
  274. methods)
  275. """
  276. attrname = node.attrname
  277. # Check self
  278. if self.is_first_attr(node):
  279. self._accessed[-1].setdefault(attrname, []).append(node)
  280. return
  281. if 'W0212' not in self.active_msgs:
  282. return
  283. self._check_protected_attribute_access(node)
  284. def visit_assign(self, assign_node):
  285. if 'W0212' not in self.active_msgs:
  286. return
  287. node = assign_node.targets[0]
  288. if not isinstance(node, AssAttr):
  289. return
  290. if self.is_first_attr(node):
  291. return
  292. self._check_protected_attribute_access(node)
  293. def _check_protected_attribute_access(self, node):
  294. '''Given an attribute access node (set or get), check if attribute
  295. access is legitimate. Call _check_first_attr with node before calling
  296. this method. Valid cases are:
  297. * self._attr in a method or cls._attr in a classmethod. Checked by
  298. _check_first_attr.
  299. * Klass._attr inside "Klass" class.
  300. * Klass2._attr inside "Klass" class when Klass2 is a base class of
  301. Klass.
  302. '''
  303. attrname = node.attrname
  304. if is_attr_protected(attrname):
  305. klass = node_frame_class(node)
  306. # XXX infer to be more safe and less dirty ??
  307. # in classes, check we are not getting a parent method
  308. # through the class object or through super
  309. callee = node.expr.as_string()
  310. # We are not in a class, no remaining valid case
  311. if klass is None:
  312. self.add_message('W0212', node=node, args=attrname)
  313. return
  314. # We are in a class, one remaining valid cases, Klass._attr inside
  315. # Klass
  316. if not (callee == klass.name or callee in klass.basenames):
  317. self.add_message('W0212', node=node, args=attrname)
  318. def visit_name(self, node):
  319. """check if the name handle an access to a class member
  320. if so, register it
  321. """
  322. if self._first_attrs and (node.name == self._first_attrs[-1] or
  323. not self._first_attrs[-1]):
  324. self._meth_could_be_func = False
  325. def _check_accessed_members(self, node, accessed):
  326. """check that accessed members are defined"""
  327. # XXX refactor, probably much simpler now that E0201 is in type checker
  328. for attr, nodes in accessed.items():
  329. # deactivate "except doesn't do anything", that's expected
  330. # pylint: disable=W0704
  331. # is it a class attribute ?
  332. try:
  333. node.local_attr(attr)
  334. # yes, stop here
  335. continue
  336. except astng.NotFoundError:
  337. pass
  338. # is it an instance attribute of a parent class ?
  339. try:
  340. node.instance_attr_ancestors(attr).next()
  341. # yes, stop here
  342. continue
  343. except StopIteration:
  344. pass
  345. # is it an instance attribute ?
  346. try:
  347. defstmts = node.instance_attr(attr)
  348. except astng.NotFoundError:
  349. pass
  350. else:
  351. if len(defstmts) == 1:
  352. defstmt = defstmts[0]
  353. # check that if the node is accessed in the same method as
  354. # it's defined, it's accessed after the initial assignment
  355. frame = defstmt.frame()
  356. lno = defstmt.fromlineno
  357. for _node in nodes:
  358. if _node.frame() is frame and _node.fromlineno < lno \
  359. and not are_exclusive(_node.statement(), defstmt, ('AttributeError', 'Exception', 'BaseException')):
  360. self.add_message('E0203', node=_node,
  361. args=(attr, lno))
  362. def _check_first_arg_for_type(self, node, metaclass=0):
  363. """check the name of first argument, expect:
  364. * 'self' for a regular method
  365. * 'cls' for a class method
  366. * 'mcs' for a metaclass
  367. * not one of the above for a static method
  368. """
  369. # don't care about functions with unknown argument (builtins)
  370. if node.args.args is None:
  371. return
  372. first_arg = node.args.args and node.argnames()[0]
  373. self._first_attrs.append(first_arg)
  374. first = self._first_attrs[-1]
  375. # static method
  376. if node.type == 'staticmethod':
  377. if first_arg in ('self', 'cls', 'mcs'):
  378. self.add_message('W0211', args=first, node=node)
  379. self._first_attrs[-1] = None
  380. # class / regular method with no args
  381. elif not node.args.args:
  382. self.add_message('E0211', node=node)
  383. # metaclass method
  384. elif metaclass:
  385. if first != 'mcs':
  386. self.add_message('C0203', node=node)
  387. # class method
  388. elif node.type == 'classmethod':
  389. if first not in self.config.valid_classmethod_first_arg:
  390. if len(self.config.valid_classmethod_first_arg) == 1:
  391. valid = repr(self.config.valid_classmethod_first_arg[0])
  392. else:
  393. valid = ', '.join(
  394. repr(v)
  395. for v in self.config.valid_classmethod_first_arg[:-1])
  396. valid = '%s or %r' % (
  397. valid, self.config.valid_classmethod_first_arg[-1])
  398. self.add_message('C0202', args=valid, node=node)
  399. # regular method without self as argument
  400. elif first != 'self':
  401. self.add_message('E0213', node=node)
  402. def _check_bases_classes(self, node):
  403. """check that the given class node implements abstract methods from
  404. base classes
  405. """
  406. # check if this class abstract
  407. if class_is_abstract(node):
  408. return
  409. for method in node.methods():
  410. owner = method.parent.frame()
  411. if owner is node:
  412. continue
  413. # owner is not this class, it must be a parent class
  414. # check that the ancestor's method is not abstract
  415. if method.is_abstract(pass_is_abstract=False):
  416. self.add_message('W0223', node=node,
  417. args=(method.name, owner.name))
  418. def _check_interfaces(self, node):
  419. """check that the given class node really implements declared
  420. interfaces
  421. """
  422. e0221_hack = [False]
  423. def iface_handler(obj):
  424. """filter interface objects, it should be classes"""
  425. if not isinstance(obj, astng.Class):
  426. e0221_hack[0] = True
  427. self.add_message('E0221', node=node,
  428. args=(obj.as_string(),))
  429. return False
  430. return True
  431. ignore_iface_methods = self.config.ignore_iface_methods
  432. try:
  433. for iface in node.interfaces(handler_func=iface_handler):
  434. for imethod in iface.methods():
  435. name = imethod.name
  436. if name.startswith('_') or name in ignore_iface_methods:
  437. # don't check method beginning with an underscore,
  438. # usually belonging to the interface implementation
  439. continue
  440. # get class method astng
  441. try:
  442. method = node_method(node, name)
  443. except astng.NotFoundError:
  444. self.add_message('E0222', args=(name, iface.name),
  445. node=node)
  446. continue
  447. # ignore inherited methods
  448. if method.parent.frame() is not node:
  449. continue
  450. # check signature
  451. self._check_signature(method, imethod,
  452. '%s interface' % iface.name)
  453. except astng.InferenceError:
  454. if e0221_hack[0]:
  455. return
  456. implements = Instance(node).getattr('__implements__')[0]
  457. assignment = implements.parent
  458. assert isinstance(assignment, astng.Assign)
  459. # assignment.expr can be a Name or a Tuple or whatever.
  460. # Use as_string() for the message
  461. # FIXME: in case of multiple interfaces, find which one could not
  462. # be resolved
  463. self.add_message('F0220', node=implements,
  464. args=(node.name, assignment.value.as_string()))
  465. def _check_init(self, node):
  466. """check that the __init__ method call super or ancestors'__init__
  467. method
  468. """
  469. if not set(('W0231', 'W0233')) & self.active_msgs:
  470. return
  471. klass_node = node.parent.frame()
  472. to_call = _ancestors_to_call(klass_node)
  473. not_called_yet = dict(to_call)
  474. for stmt in node.nodes_of_class(astng.CallFunc):
  475. expr = stmt.func
  476. if not isinstance(expr, astng.Getattr) \
  477. or expr.attrname != '__init__':
  478. continue
  479. # skip the test if using super
  480. if isinstance(expr.expr, astng.CallFunc) and \
  481. isinstance(expr.expr.func, astng.Name) and \
  482. expr.expr.func.name == 'super':
  483. return
  484. try:
  485. klass = expr.expr.infer().next()
  486. if klass is YES:
  487. continue
  488. try:
  489. del not_called_yet[klass]
  490. except KeyError:
  491. if klass not in to_call:
  492. self.add_message('W0233', node=expr, args=klass.name)
  493. except astng.InferenceError:
  494. continue
  495. for klass in not_called_yet.keys():
  496. if klass.name == 'object':
  497. continue
  498. self.add_message('W0231', args=klass.name, node=node)
  499. def _check_signature(self, method1, refmethod, class_type):
  500. """check that the signature of the two given methods match
  501. class_type is in 'class', 'interface'
  502. """
  503. if not (isinstance(method1, astng.Function)
  504. and isinstance(refmethod, astng.Function)):
  505. self.add_message('F0202', args=(method1, refmethod), node=method1)
  506. return
  507. # don't care about functions with unknown argument (builtins)
  508. if method1.args.args is None or refmethod.args.args is None:
  509. return
  510. # if we use *args, **kwargs, skip the below checks
  511. if method1.args.vararg or method1.args.kwarg:
  512. return
  513. if is_attr_private(method1.name):
  514. return
  515. if len(method1.args.args) != len(refmethod.args.args):
  516. self.add_message('W0221', args=class_type, node=method1)
  517. elif len(method1.args.defaults) < len(refmethod.args.defaults):
  518. self.add_message('W0222', args=class_type, node=method1)
  519. def is_first_attr(self, node):
  520. """Check that attribute lookup name use first attribute variable name
  521. (self for method, cls for classmethod and mcs for metaclass).
  522. """
  523. return self._first_attrs and isinstance(node.expr, astng.Name) and \
  524. node.expr.name == self._first_attrs[-1]
  525. def _ancestors_to_call(klass_node, method='__init__'):
  526. """return a dictionary where keys are the list of base classes providing
  527. the queried method, and so that should/may be called from the method node
  528. """
  529. to_call = {}
  530. for base_node in klass_node.ancestors(recurs=False):
  531. try:
  532. base_node.local_attr(method)
  533. to_call[base_node] = 1
  534. except astng.NotFoundError:
  535. continue
  536. return to_call
  537. def node_method(node, method_name):
  538. """get astng for <method_name> on the given class node, ensuring it
  539. is a Function node
  540. """
  541. for n in node.local_attr(method_name):
  542. if isinstance(n, astng.Function):
  543. return n
  544. raise astng.NotFoundError(method_name)
  545. def register(linter):
  546. """required method to auto register this checker """
  547. linter.register_checker(ClassChecker(linter))