Skip to content

Commit

Permalink
Fixed #18013 -- Use the new 'as' syntax for exceptions.
Browse files Browse the repository at this point in the history
Thanks Clueless for the initial patch.
Note that unittest has been purposely left out (external package only used by Python 2.6).
  • Loading branch information
claudep committed Apr 29, 2012
1 parent eefb00f commit 3904b74
Show file tree
Hide file tree
Showing 107 changed files with 306 additions and 354 deletions.
2 changes: 1 addition & 1 deletion django/conf/__init__.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def __init__(self, settings_module):


try: try:
mod = importlib.import_module(self.SETTINGS_MODULE) mod = importlib.import_module(self.SETTINGS_MODULE)
except ImportError, e: except ImportError as e:
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))


# Settings that should be converted into tuples if they're mistakenly entered # Settings that should be converted into tuples if they're mistakenly entered
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/admin/tests.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def setUpClass(cls):
mod = import_module(module) mod = import_module(module)
WebDriver = getattr(mod, attr) WebDriver = getattr(mod, attr)
cls.selenium = WebDriver() cls.selenium = WebDriver()
except Exception, e: except Exception as e:
raise SkipTest('Selenium webdriver "%s" not installed or not ' raise SkipTest('Selenium webdriver "%s" not installed or not '
'operational: %s' % (cls.webdriver_class, str(e))) 'operational: %s' % (cls.webdriver_class, str(e)))
super(AdminSeleniumWebDriverTestCase, cls).setUpClass() super(AdminSeleniumWebDriverTestCase, cls).setUpClass()
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/admin/util.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def collect(self, objs, source_attr=None, **kwargs):
self.add_edge(None, obj) self.add_edge(None, obj)
try: try:
return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs) return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
except models.ProtectedError, e: except models.ProtectedError as e:
self.protected.update(e.protected_objects) self.protected.update(e.protected_objects)


def related_objects(self, related, objs): def related_objects(self, related, objs):
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/admin/views/main.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def get_filters(self, request):
use_distinct = (use_distinct or use_distinct = (use_distinct or
lookup_needs_distinct(self.lookup_opts, key)) lookup_needs_distinct(self.lookup_opts, key))
return filter_specs, bool(filter_specs), lookup_params, use_distinct return filter_specs, bool(filter_specs), lookup_params, use_distinct
except FieldDoesNotExist, e: except FieldDoesNotExist as e:
raise IncorrectLookupParameters(e) raise IncorrectLookupParameters(e)


def get_query_string(self, new_params=None, remove=None): def get_query_string(self, new_params=None, remove=None):
Expand Down Expand Up @@ -316,7 +316,7 @@ def get_query_set(self, request):
# Allow certain types of errors to be re-raised as-is so that the # Allow certain types of errors to be re-raised as-is so that the
# caller can treat them in a special way. # caller can treat them in a special way.
raise raise
except Exception, e: except Exception as e:
# Every other error is caught with a naked except, because we don't # Every other error is caught with a naked except, because we don't
# have any other way of validating lookup parameters. They might be # have any other way of validating lookup parameters. They might be
# invalid if the keyword arguments are incorrect, or if the values # invalid if the keyword arguments are incorrect, or if the values
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/admindocs/views.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ def load_all_installed_template_libraries():
for library_name in libraries: for library_name in libraries:
try: try:
lib = template.get_library(library_name) lib = template.get_library(library_name)
except template.InvalidTemplateLibrary, e: except template.InvalidTemplateLibrary:
pass pass


def get_return_data_type(func_name): def get_return_data_type(func_name):
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/auth/__init__.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ def load_backend(path):
module, attr = path[:i], path[i+1:] module, attr = path[:i], path[i+1:]
try: try:
mod = import_module(module) mod = import_module(module)
except ImportError, e: except ImportError as e:
raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (path, e)) raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (path, e))
except ValueError, e: except ValueError:
raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?') raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
try: try:
cls = getattr(mod, attr) cls = getattr(mod, attr)
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/comments/views/comments.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def post_comment(request, next=None, using=None):
return CommentPostBadRequest( return CommentPostBadRequest(
"No object matching content-type %r and object PK %r exists." % \ "No object matching content-type %r and object PK %r exists." % \
(escape(ctype), escape(object_pk))) (escape(ctype), escape(object_pk)))
except (ValueError, ValidationError), e: except (ValueError, ValidationError) as e:
return CommentPostBadRequest( return CommentPostBadRequest(
"Attempting go get content-type %r and object PK %r exists raised %s" % \ "Attempting go get content-type %r and object PK %r exists raised %s" % \
(escape(ctype), escape(object_pk), e.__class__.__name__)) (escape(ctype), escape(object_pk), e.__class__.__name__))
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/formtools/wizard/storage/__init__.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def get_storage(path, *args, **kwargs):
module, attr = path[:i], path[i+1:] module, attr = path[:i], path[i+1:]
try: try:
mod = import_module(module) mod = import_module(module)
except ImportError, e: except ImportError as e:
raise MissingStorageModule( raise MissingStorageModule(
'Error loading storage %s: "%s"' % (module, e)) 'Error loading storage %s: "%s"' % (module, e))
try: try:
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/gis/db/backends/base.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -164,13 +164,13 @@ def srs(self):
try: try:
self._srs = gdal.SpatialReference(self.wkt) self._srs = gdal.SpatialReference(self.wkt)
return self.srs return self.srs
except Exception, msg: except Exception as msg:
pass pass


try: try:
self._srs = gdal.SpatialReference(self.proj4text) self._srs = gdal.SpatialReference(self.proj4text)
return self.srs return self.srs
except Exception, msg: except Exception as msg:
pass pass


raise Exception('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg)) raise Exception('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg))
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/db/backends/oracle/introspection.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def get_geometry_type(self, table_name, geo_col):
cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s', cursor.execute('SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s',
(table_name.upper(), geo_col.upper())) (table_name.upper(), geo_col.upper()))
row = cursor.fetchone() row = cursor.fetchone()
except Exception, msg: except Exception as msg:
raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n' raise Exception('Could not find entry in USER_SDO_GEOM_METADATA corresponding to "%s"."%s"\n'
'Error message: %s.' % (table_name, geo_col, msg)) 'Error message: %s.' % (table_name, geo_col, msg))


Expand Down
4 changes: 1 addition & 3 deletions django/contrib/gis/db/backends/postgis/operations.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -107,9 +107,7 @@ def __init__(self, connection):
'Was the database created from a spatial database ' 'Was the database created from a spatial database '
'template?' % self.connection.settings_dict['NAME'] 'template?' % self.connection.settings_dict['NAME']
) )
except Exception, e: # TODO: Raise helpful exceptions as they become known.
# TODO: Raise helpful exceptions as they become known.
raise


# PostGIS-specific operators. The commented descriptions of these # PostGIS-specific operators. The commented descriptions of these
# operators come from Section 7.6 of the PostGIS 1.4 documentation. # operators come from Section 7.6 of the PostGIS 1.4 documentation.
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/db/backends/spatialite/base.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _cursor(self):
cur = self.connection.cursor(factory=SQLiteCursorWrapper) cur = self.connection.cursor(factory=SQLiteCursorWrapper)
try: try:
cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,)) cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
except Exception, msg: except Exception as msg:
raise ImproperlyConfigured('Unable to load the SpatiaLite library extension ' raise ImproperlyConfigured('Unable to load the SpatiaLite library extension '
'"%s" because: %s' % (self.spatialite_lib, msg)) '"%s" because: %s' % (self.spatialite_lib, msg))
return cur return cur
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/db/backends/spatialite/operations.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def __init__(self, connection):
self.spatial_version = version self.spatial_version = version
except ImproperlyConfigured: except ImproperlyConfigured:
raise raise
except Exception, msg: except Exception as msg:
raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" ' raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
'database (error was "%s"). Was the SpatiaLite initialization ' 'database (error was "%s"). Was the SpatiaLite initialization '
'SQL loaded on this database?' % 'SQL loaded on this database?' %
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/gis/geometry/backend/__init__.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@


try: try:
module = import_module('.%s' % geom_backend, 'django.contrib.gis.geometry.backend') module = import_module('.%s' % geom_backend, 'django.contrib.gis.geometry.backend')
except ImportError, e: except ImportError:
try: try:
module = import_module(geom_backend) module = import_module(geom_backend)
except ImportError, e_user: except ImportError:
raise ImproperlyConfigured('Could not import user-defined GEOMETRY_BACKEND ' raise ImproperlyConfigured('Could not import user-defined GEOMETRY_BACKEND '
'"%s".' % geom_backend) '"%s".' % geom_backend)


Expand Down
2 changes: 1 addition & 1 deletion django/contrib/gis/management/commands/ogrinspect.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def handle(self, *args, **options):
# Getting the OGR DataSource from the string parameter. # Getting the OGR DataSource from the string parameter.
try: try:
ds = gdal.DataSource(data_source) ds = gdal.DataSource(data_source)
except gdal.OGRException, msg: except gdal.OGRException as msg:
raise CommandError(msg) raise CommandError(msg)


# Whether the user wants to generate the LayerMapping dictionary as well. # Whether the user wants to generate the LayerMapping dictionary as well.
Expand Down
75 changes: 15 additions & 60 deletions django/contrib/gis/tests/test_measure.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -62,32 +62,20 @@ def testAddition(self):
d4 -= d1 d4 -= d1
self.assertEqual(d4.m, -200) self.assertEqual(d4.m, -200)


try: with self.assertRaises(TypeError):
d5 = d1 + 1 d5 = d1 + 1
except TypeError, e:
pass
else:
self.fail('Distance + number should raise TypeError') self.fail('Distance + number should raise TypeError')


try: with self.assertRaises(TypeError):
d5 = d1 - 1 d5 = d1 - 1
except TypeError, e:
pass
else:
self.fail('Distance - number should raise TypeError') self.fail('Distance - number should raise TypeError')


try: with self.assertRaises(TypeError):
d1 += 1 d1 += 1
except TypeError, e:
pass
else:
self.fail('Distance += number should raise TypeError') self.fail('Distance += number should raise TypeError')


try: with self.assertRaises(TypeError):
d1 -= 1 d1 -= 1
except TypeError, e:
pass
else:
self.fail('Distance -= number should raise TypeError') self.fail('Distance -= number should raise TypeError')


def testMultiplication(self): def testMultiplication(self):
Expand All @@ -110,25 +98,16 @@ def testMultiplication(self):
self.assertTrue(isinstance(a5, Area)) self.assertTrue(isinstance(a5, Area))
self.assertEqual(a5.sq_m, 100*10) self.assertEqual(a5.sq_m, 100*10)


try: with self.assertRaises(TypeError):
d1 *= D(m=1) d1 *= D(m=1)
except TypeError, e:
pass
else:
self.fail('Distance *= Distance should raise TypeError') self.fail('Distance *= Distance should raise TypeError')


try: with self.assertRaises(TypeError):
d5 = d1 / D(m=1) d5 = d1 / D(m=1)
except TypeError, e:
pass
else:
self.fail('Distance / Distance should raise TypeError') self.fail('Distance / Distance should raise TypeError')


try: with self.assertRaises(TypeError):
d1 /= D(m=1) d1 /= D(m=1)
except TypeError, e:
pass
else:
self.fail('Distance /= Distance should raise TypeError') self.fail('Distance /= Distance should raise TypeError')


def testUnitConversions(self): def testUnitConversions(self):
Expand Down Expand Up @@ -217,32 +196,20 @@ def testAddition(self):
a4 -= a1 a4 -= a1
self.assertEqual(a4.sq_m, -200) self.assertEqual(a4.sq_m, -200)


try: with self.assertRaises(TypeError):
a5 = a1 + 1 a5 = a1 + 1
except TypeError, e:
pass
else:
self.fail('Area + number should raise TypeError') self.fail('Area + number should raise TypeError')


try: with self.assertRaises(TypeError):
a5 = a1 - 1 a5 = a1 - 1
except TypeError, e:
pass
else:
self.fail('Area - number should raise TypeError') self.fail('Area - number should raise TypeError')


try: with self.assertRaises(TypeError):
a1 += 1 a1 += 1
except TypeError, e:
pass
else:
self.fail('Area += number should raise TypeError') self.fail('Area += number should raise TypeError')


try: with self.assertRaises(TypeError):
a1 -= 1 a1 -= 1
except TypeError, e:
pass
else:
self.fail('Area -= number should raise TypeError') self.fail('Area -= number should raise TypeError')


def testMultiplication(self): def testMultiplication(self):
Expand All @@ -261,32 +228,20 @@ def testMultiplication(self):
a4 /= 5 a4 /= 5
self.assertEqual(a4.sq_m, 10) self.assertEqual(a4.sq_m, 10)


try: with self.assertRaises(TypeError):
a5 = a1 * A(sq_m=1) a5 = a1 * A(sq_m=1)
except TypeError, e:
pass
else:
self.fail('Area * Area should raise TypeError') self.fail('Area * Area should raise TypeError')


try: with self.assertRaises(TypeError):
a1 *= A(sq_m=1) a1 *= A(sq_m=1)
except TypeError, e:
pass
else:
self.fail('Area *= Area should raise TypeError') self.fail('Area *= Area should raise TypeError')


try: with self.assertRaises(TypeError):
a5 = a1 / A(sq_m=1) a5 = a1 / A(sq_m=1)
except TypeError, e:
pass
else:
self.fail('Area / Area should raise TypeError') self.fail('Area / Area should raise TypeError')


try: with self.assertRaises(TypeError):
a1 /= A(sq_m=1) a1 /= A(sq_m=1)
except TypeError, e:
pass
else:
self.fail('Area /= Area should raise TypeError') self.fail('Area /= Area should raise TypeError')


def testUnitConversions(self): def testUnitConversions(self):
Expand Down
6 changes: 3 additions & 3 deletions django/contrib/gis/utils/layermapping.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ def coord_transform(self):


# Creating the CoordTransform object # Creating the CoordTransform object
return CoordTransform(self.source_srs, target_srs) return CoordTransform(self.source_srs, target_srs)
except Exception, msg: except Exception as msg:
raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg) raise LayerMapError('Could not translate between the data source and model geometry: %s' % msg)


def geometry_field(self): def geometry_field(self):
Expand Down Expand Up @@ -514,7 +514,7 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
# Getting the keyword arguments # Getting the keyword arguments
try: try:
kwargs = self.feature_kwargs(feat) kwargs = self.feature_kwargs(feat)
except LayerMapError, msg: except LayerMapError as msg:
# Something borked the validation # Something borked the validation
if strict: raise if strict: raise
elif not silent: elif not silent:
Expand Down Expand Up @@ -553,7 +553,7 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m)) if verbose: stream.write('%s: %s\n' % (is_update and 'Updated' or 'Saved', m))
except SystemExit: except SystemExit:
raise raise
except Exception, msg: except Exception as msg:
if self.transaction_mode == 'autocommit': if self.transaction_mode == 'autocommit':
# Rolling back the transaction so that other model saves # Rolling back the transaction so that other model saves
# will work. # will work.
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/markup/tests.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def test_docutils(self):
# Docutils v0.4 and earlier # Docutils v0.4 and earlier
self.assertEqual(rendered, """<p>Paragraph 1</p> self.assertEqual(rendered, """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""") <p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""")
except AssertionError, e: except AssertionError:
# Docutils from SVN (which will become 0.5) # Docutils from SVN (which will become 0.5)
self.assertEqual(rendered, """<p>Paragraph 1</p> self.assertEqual(rendered, """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""") <p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""")
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/messages/storage/__init__.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def get_storage(import_path):
module, classname = import_path[:dot], import_path[dot + 1:] module, classname = import_path[:dot], import_path[dot + 1:]
try: try:
mod = import_module(module) mod = import_module(module)
except ImportError, e: except ImportError as e:
raise ImproperlyConfigured('Error importing module %s: "%s"' % raise ImproperlyConfigured('Error importing module %s: "%s"' %
(module, e)) (module, e))
try: try:
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/sessions/backends/file.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def save(self, must_create=False):
fd = os.open(session_file_name, flags) fd = os.open(session_file_name, flags)
os.close(fd) os.close(fd)


except OSError, e: except OSError as e:
if must_create and e.errno == errno.EEXIST: if must_create and e.errno == errno.EEXIST:
raise CreateError raise CreateError
raise raise
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/staticfiles/finders.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def _get_finder(import_path):
module, attr = import_path.rsplit('.', 1) module, attr = import_path.rsplit('.', 1)
try: try:
mod = import_module(module) mod = import_module(module)
except ImportError, e: except ImportError as e:
raise ImproperlyConfigured('Error importing module %s: "%s"' % raise ImproperlyConfigured('Error importing module %s: "%s"' %
(module, e)) (module, e))
try: try:
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/staticfiles/handlers.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def get_response(self, request):
if self._should_handle(request.path): if self._should_handle(request.path):
try: try:
return self.serve(request) return self.serve(request)
except Http404, e: except Http404 as e:
if settings.DEBUG: if settings.DEBUG:
from django.views import debug from django.views import debug
return debug.technical_404_response(request, e) return debug.technical_404_response(request, e)
Expand Down
2 changes: 1 addition & 1 deletion django/core/cache/__init__.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def get_cache(backend, **kwargs):
mod_path, cls_name = backend.rsplit('.', 1) mod_path, cls_name = backend.rsplit('.', 1)
mod = importlib.import_module(mod_path) mod = importlib.import_module(mod_path)
backend_cls = getattr(mod, cls_name) backend_cls = getattr(mod, cls_name)
except (AttributeError, ImportError), e: except (AttributeError, ImportError) as e:
raise InvalidCacheBackendError( raise InvalidCacheBackendError(
"Could not find backend '%s': %s" % (backend, e)) "Could not find backend '%s': %s" % (backend, e))
cache = backend_cls(location, params) cache = backend_cls(location, params)
Expand Down
2 changes: 1 addition & 1 deletion django/core/files/move.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_ove


try: try:
os.remove(old_file_name) os.remove(old_file_name)
except OSError, e: except OSError as e:
# Certain operating systems (Cygwin and Windows) # Certain operating systems (Cygwin and Windows)
# fail when deleting opened files, ignore it. (For the # fail when deleting opened files, ignore it. (For the
# systems where this happens, temporary files will be auto-deleted # systems where this happens, temporary files will be auto-deleted
Expand Down
Loading

0 comments on commit 3904b74

Please sign in to comment.