Home | History | Annotate | Download | only in fixes
      1 # Copyright 2007 Google, Inc. All Rights Reserved.

      2 # Licensed to PSF under a Contributor Agreement.

      3 
      4 """Fixer for callable().
      5 
      6 This converts callable(obj) into isinstance(obj, collections.Callable), adding a
      7 collections import if needed."""
      8 
      9 # Local imports

     10 from lib2to3 import fixer_base
     11 from lib2to3.fixer_util import Call, Name, String, Attr, touch_import
     12 
     13 class FixCallable(fixer_base.BaseFix):
     14     BM_compatible = True
     15 
     16     order = "pre"
     17 
     18     # Ignore callable(*args) or use of keywords.

     19     # Either could be a hint that the builtin callable() is not being used.

     20     PATTERN = """
     21     power< 'callable'
     22            trailer< lpar='('
     23                     ( not(arglist | argument<any '=' any>) func=any
     24                       | func=arglist<(not argument<any '=' any>) any ','> )
     25                     rpar=')' >
     26            after=any*
     27     >
     28     """
     29 
     30     def transform(self, node, results):
     31         func = results['func']
     32 
     33         touch_import(None, u'collections', node=node)
     34 
     35         args = [func.clone(), String(u', ')]
     36         args.extend(Attr(Name(u'collections'), Name(u'Callable')))
     37         return Call(Name(u'isinstance'), args, prefix=node.prefix)
     38