[Python-checkins] r57420 - in sandbox/trunk/2to3: README fixes/fix_type_equality.py tests/test_fixers.py
collin.winter
python-checkins at python.org
Sat Aug 25 00:01:40 CEST 2007
Author: collin.winter
Date: Sat Aug 25 00:01:39 2007
New Revision: 57420
Added:
sandbox/trunk/2to3/fixes/fix_type_equality.py
Modified:
sandbox/trunk/2to3/ (props changed)
sandbox/trunk/2to3/README
sandbox/trunk/2to3/tests/test_fixers.py
Log:
Add an initial draft of fix_type_equality by Jacques Frechet.
Modified: sandbox/trunk/2to3/README
==============================================================================
--- sandbox/trunk/2to3/README (original)
+++ sandbox/trunk/2to3/README Sat Aug 25 00:01:39 2007
@@ -83,6 +83,8 @@
* **fix_tuple_params** - remove tuple parameters from function, method and
lambda declarations (PEP 3113).
+
+* **fix_type_equality** - convert type(x) == T to isinstance(x, T).
* **fix_unicode** - convert, e.g., u"..." to "...", unicode(x) to str(x), etc.
Added: sandbox/trunk/2to3/fixes/fix_type_equality.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/2to3/fixes/fix_type_equality.py Sat Aug 25 00:01:39 2007
@@ -0,0 +1,21 @@
+"""Fix type(x) == T -> isinstance(x, T)."""
+# Author: Jacques Frechet
+
+# Local imports
+from fixes import basefix
+from fixes.util import Call, Comma, Name
+
+
+class FixTypeEquality(basefix.BaseFix):
+
+ PATTERN = """
+ comparison< power< 'type' trailer< '(' x=any ')' > > '==' T=any > |
+ comparison< T=any '==' power< 'type' trailer< '(' x=any ')' > > >
+ """
+
+ def transform(self, node, results):
+ x = results['x'].clone() # The thing inside of type()
+ T = results['T'].clone() # The type being compared against
+ x.set_prefix('')
+ T.set_prefix(' ')
+ return Call(Name('isinstance'), [x, Comma(), T])
Modified: sandbox/trunk/2to3/tests/test_fixers.py
==============================================================================
--- sandbox/trunk/2to3/tests/test_fixers.py (original)
+++ sandbox/trunk/2to3/tests/test_fixers.py Sat Aug 25 00:01:39 2007
@@ -2348,6 +2348,32 @@
a = """int"""
self.check(b, a)
+class Test_type_equality(FixerTestCase):
+ fixer = "type_equality"
+
+ def test_simple(self):
+ b = """type(x) == T"""
+ a = """isinstance(x, T)"""
+ self.check(b, a)
+
+ def test_reverse(self):
+ b = """T == type(x)"""
+ a = """isinstance(x, T)"""
+ self.check(b, a)
+
+ def test_expression(self):
+ b = """type(x+y) == d.get('T')"""
+ a = """isinstance(x+y, d.get('T'))"""
+ self.check(b, a)
+
+ b = """type( x + y) == d.get('T')"""
+ a = """isinstance(x + y, d.get('T'))"""
+ self.check(b, a)
+
+ def test_unchanged(self):
+ a = """type(x).__name__"""
+ self.unchanged(a)
+
if __name__ == "__main__":
import __main__
More information about the Python-checkins
mailing list