python - Checking code for deprecation warnings -


consider following sample code:

data = [] try:     print data[0] except indexerror error:     print error.message 

there nothing syntactically wrong (using python2.7) code except if run python with warnings turned on, see deprecationwarning:

$ python -w test.py test.py:5: deprecationwarning: baseexception.message has been deprecated of python 2.6   print error.message list index out of range 

fyi, because .message deprecated since python2.6 , removed in python3.

now, i'd find places in project .message called on exception instance by using static code analysis tools. end goal, i'm planning have check running part of daily build&test&code quality check task , raise error if syntax still used.

is possible? pylint, pyflakes or other code analysis tools capable of?


i found pep8 tool has several similar checks implemented, instance, has_key() usage check:

$ cat test.py my_dict = {} print my_dict.has_key('test') $ pep8 test.py test.py:2:14: w601 .has_key() deprecated, use 'in' 

as alternative solution, can treat warnings errors (like suggested here) , make tests fail has disadvantages:

  • there other deprecation warnings coming third-party packages cannot fix
  • strictly speaking, requires 100% coverage, difficult maintain

since want statically, can use ast module parse code , scan occurrence of deprecated code subclass of nodevisitor class. so:

import ast, sys  class usingmessageattr(ast.nodevisitor):      error_object_names = []      def visit_attribute(self, node):         if (node.attr == 'message' ,              hasattr(node.value, 'id') ,              node.value.id in self.error_object_names):              print("danger robinson!!")             sys.exit(1)          self.generic_visit(node)      def visit_excepthandler(self, node):         if node.name not none:             self.error_object_names.append(node.name)             self.generic_visit(node)             self.error_object_names.pop()         else:             self.generic_visit(node)  open('sourcefile.py', 'r') f:     usingmessageattr().visit(ast.parse(f.read())) 

this works using python parse source file ast , uses visitor pattern walk through entire file , find instances of deprecated attribute. more information on how works, see the python documentation on ast module.

note won't work if use clever refer exception object. takes variable name exception object bound , checks if message attribute ever accessed variable of same name inside body of exception handler.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -