Permalink
Browse files

Changed a whole bunch of places to raise exception instances instead …

…of old-style raising exception classes plus a comma. Good for the future Python 3 conversion

git-svn-id: http://code.djangoproject.com/svn/django/trunk@12180 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent bef8913 commit 5ceed0a05388079118319940acdb2abe4ee01de6 @adrianholovaty adrianholovaty committed Jan 10, 2010
Showing with 120 additions and 124 deletions.
  1. +2 −2 django/conf/__init__.py
  2. +4 −4 django/contrib/admin/templatetags/log.py
  3. +1 −1 django/contrib/admin/views/template.py
  4. +3 −3 django/contrib/admindocs/views.py
  5. +3 −3 django/contrib/auth/__init__.py
  6. +3 −3 django/contrib/contenttypes/generic.py
  7. +1 −1 django/contrib/gis/db/backends/spatialite/base.py
  8. +1 −1 django/contrib/gis/geos/collections.py
  9. +1 −1 django/contrib/gis/tests/geometries.py
  10. +1 −1 django/contrib/gis/utils/ogrinfo.py
  11. +5 −5 django/contrib/localflavor/es/forms.py
  12. +3 −3 django/contrib/markup/templatetags/markup.py
  13. +1 −1 django/contrib/sessions/models.py
  14. +2 −2 django/contrib/sites/managers.py
  15. +1 −1 django/contrib/syndication/feeds.py
  16. +3 −3 django/contrib/syndication/views.py
  17. +2 −2 django/core/cache/__init__.py
  18. +1 −1 django/core/cache/backends/base.py
  19. +1 −1 django/core/cache/backends/filebased.py
  20. +4 −4 django/core/handlers/base.py
  21. +1 −1 django/core/management/__init__.py
  22. +1 −1 django/core/servers/basehttp.py
  23. +6 −7 django/core/urlresolvers.py
  24. +1 −1 django/db/backends/dummy/base.py
  25. +2 −2 django/db/backends/sqlite3/base.py
  26. +4 −6 django/db/models/base.py
  27. +12 −12 django/db/models/fields/related.py
  28. +1 −1 django/db/models/loading.py
  29. +2 −2 django/db/models/manager.py
  30. +2 −2 django/db/models/options.py
  31. +1 −1 django/db/models/query.py
  32. +1 −1 django/forms/widgets.py
  33. +7 −8 django/template/defaulttags.py
  34. +2 −2 django/template/loader.py
  35. +7 −7 django/template/loader_tags.py
  36. +2 −2 django/template/loaders/app_directories.py
  37. +1 −1 django/template/loaders/cached.py
  38. +1 −1 django/template/loaders/eggs.py
  39. +1 −1 django/template/loaders/filesystem.py
  40. +9 −9 django/templatetags/i18n.py
  41. +4 −4 django/utils/datastructures.py
  42. +1 −1 django/utils/text.py
  43. +3 −3 django/views/generic/date_based.py
  44. +2 −2 django/views/generic/list_detail.py
  45. +1 −1 django/views/i18n.py
  46. +2 −2 django/views/static.py
@@ -46,7 +46,7 @@ def configure(self, default_settings=global_settings, **options):
argument must support attribute access (__getattr__)).
"""
if self._wrapped != None:
- raise RuntimeError, 'Settings already configured.'
+ raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings)
for name, value in options.items():
setattr(holder, name, value)
@@ -72,7 +72,7 @@ def __init__(self, settings_module):
try:
mod = importlib.import_module(self.SETTINGS_MODULE)
except ImportError, e:
- raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
+ raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e))
# Settings that should be converted into tuples if they're mistakenly entered
# as strings.
@@ -44,14 +44,14 @@ def __init__(self, tag_name):
def __call__(self, parser, token):
tokens = token.contents.split()
if len(tokens) < 4:
- raise template.TemplateSyntaxError, "'%s' statements require two arguments" % self.tag_name
+ raise template.TemplateSyntaxError("'%s' statements require two arguments" % self.tag_name)
if not tokens[1].isdigit():
- raise template.TemplateSyntaxError, "First argument in '%s' must be an integer" % self.tag_name
+ raise template.TemplateSyntaxError("First argument in '%s' must be an integer" % self.tag_name)
if tokens[2] != 'as':
- raise template.TemplateSyntaxError, "Second argument in '%s' must be 'as'" % self.tag_name
+ raise template.TemplateSyntaxError("Second argument in '%s' must be 'as'" % self.tag_name)
if len(tokens) > 4:
if tokens[4] != 'for_user':
- raise template.TemplateSyntaxError, "Fourth argument in '%s' must be 'for_user'" % self.tag_name
+ raise template.TemplateSyntaxError("Fourth argument in '%s' must be 'for_user'" % self.tag_name)
return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(len(tokens) > 5 and tokens[5] or None))
register.tag('get_admin_log', DoGetAdminLog('get_admin_log'))
@@ -76,4 +76,4 @@ def new_do_extends(parser, token):
error = e
template.builtins.remove(register)
if error:
- raise forms.ValidationError, e.args
+ raise forms.ValidationError(e.args)
@@ -187,14 +187,14 @@ def model_detail(request, app_label, model_name):
try:
app_mod = models.get_app(app_label)
except ImproperlyConfigured:
- raise Http404, _("App %r not found") % app_label
+ raise Http404(_("App %r not found") % app_label)
model = None
for m in models.get_models(app_mod):
if m._meta.object_name.lower() == model_name:
model = m
break
if model is None:
- raise Http404, _("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label}
+ raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label})
opts = model._meta
@@ -353,7 +353,7 @@ def extract_views_from_urlpatterns(urlpatterns, base=''):
continue
views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern))
else:
- raise TypeError, _("%s does not appear to be a urlpattern object") % p
+ raise TypeError(_("%s does not appear to be a urlpattern object") % p)
return views
named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)')
@@ -13,13 +13,13 @@ def load_backend(path):
try:
mod = import_module(module)
except ImportError, e:
- raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e)
+ raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (module, e))
except ValueError, e:
- 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:
cls = getattr(mod, attr)
except AttributeError:
- raise ImproperlyConfigured, 'Module "%s" does not define a "%s" authentication backend' % (module, attr)
+ raise ImproperlyConfigured('Module "%s" does not define a "%s" authentication backend' % (module, attr))
try:
getattr(cls, 'supports_object_permissions')
except AttributeError:
@@ -83,7 +83,7 @@ def __get__(self, instance, instance_type=None):
def __set__(self, instance, value):
if instance is None:
- raise AttributeError, u"%s must be accessed via instance" % self.related.opts.object_name
+ raise AttributeError(u"%s must be accessed via instance" % self.related.opts.object_name)
ct = None
fk = None
@@ -210,7 +210,7 @@ def __get__(self, instance, instance_type=None):
def __set__(self, instance, value):
if instance is None:
- raise AttributeError, "Manager must be accessed via instance"
+ raise AttributeError("Manager must be accessed via instance")
manager = self.__get__(instance)
manager.clear()
@@ -252,7 +252,7 @@ def get_query_set(self):
def add(self, *objs):
for obj in objs:
if not isinstance(obj, self.model):
- raise TypeError, "'%s' instance expected" % self.model._meta.object_name
+ raise TypeError("'%s' instance expected" % self.model._meta.object_name)
setattr(obj, self.content_type_field_name, self.content_type)
setattr(obj, self.object_id_field_name, self.pk_val)
obj.save(using=self.instance._state.db)
@@ -39,7 +39,7 @@ def _cursor(self):
settings_dict = self.settings_dict
if not settings_dict['NAME']:
from django.core.exceptions import ImproperlyConfigured
- raise ImproperlyConfigured, "Please fill out the database NAME in the settings module before using the database."
+ raise ImproperlyConfigured("Please fill out the database NAME in the settings module before using the database.")
kwargs = {
'database': settings_dict['NAME'],
'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
@@ -19,7 +19,7 @@ def __init__(self, *args, **kwargs):
# Checking the arguments
if not args:
- raise TypeError, 'Must provide at least one Geometry to initialize %s.' % self.__class__.__name__
+ raise TypeError('Must provide at least one Geometry to initialize %s.' % self.__class__.__name__)
if len(args) == 1:
# If only one geometry provided or a list of geometries is provided
@@ -12,7 +12,7 @@ def __init__(self, wkt, **kwargs):
if not self.bad:
m = wkt_regex.match(wkt)
if not m:
- raise Exception, 'Improper WKT: "%s"' % wkt
+ raise Exception('Improper WKT: "%s"' % wkt)
self.geo_type = m.group('type')
for key, value in kwargs.items():
@@ -19,7 +19,7 @@ def ogrinfo(data_source, num_features=10):
elif isinstance(data_source, DataSource):
pass
else:
- raise Exception, 'Data source parameter must be a string or a DataSource object.'
+ raise Exception('Data source parameter must be a string or a DataSource object.')
for i, layer in enumerate(data_source):
print "data source : %s" % data_source.name
@@ -97,13 +97,13 @@ def clean(self, value):
if letter2 == nif_get_checksum(number):
return value
else:
- raise ValidationError, self.error_messages['invalid_nif']
+ raise ValidationError(self.error_messages['invalid_nif'])
elif letter1 in self.nie_types and letter2:
# NIE
if letter2 == nif_get_checksum(number):
return value
else:
- raise ValidationError, self.error_messages['invalid_nie']
+ raise ValidationError(self.error_messages['invalid_nie'])
elif not self.only_nif and letter1 in self.cif_types and len(number) in [7, 8]:
# CIF
if not letter2:
@@ -112,9 +112,9 @@ def clean(self, value):
if letter2 in (checksum, self.cif_control[checksum]):
return value
else:
- raise ValidationError, self.error_messages['invalid_cif']
+ raise ValidationError(self.error_messages['invalid_cif'])
else:
- raise ValidationError, self.error_messages['invalid']
+ raise ValidationError(self.error_messages['invalid'])
class ESCCCField(RegexField):
"""
@@ -159,7 +159,7 @@ def clean(self, value):
if get_checksum('00' + entity + office) + get_checksum(account) == checksum:
return value
else:
- raise ValidationError, self.error_messages['checksum']
+ raise ValidationError(self.error_messages['checksum'])
class ESRegionSelect(Select):
"""
@@ -26,7 +26,7 @@ def textile(value):
import textile
except ImportError:
if settings.DEBUG:
- raise template.TemplateSyntaxError, "Error in {% textile %} filter: The Python textile library isn't installed."
+ raise template.TemplateSyntaxError("Error in {% textile %} filter: The Python textile library isn't installed.")
return force_unicode(value)
else:
return mark_safe(force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8')))
@@ -53,7 +53,7 @@ def markdown(value, arg=''):
import markdown
except ImportError:
if settings.DEBUG:
- raise template.TemplateSyntaxError, "Error in {% markdown %} filter: The Python markdown library isn't installed."
+ raise template.TemplateSyntaxError("Error in {% markdown %} filter: The Python markdown library isn't installed.")
return force_unicode(value)
else:
# markdown.version was first added in 1.6b. The only version of markdown
@@ -81,7 +81,7 @@ def restructuredtext(value):
from docutils.core import publish_parts
except ImportError:
if settings.DEBUG:
- raise template.TemplateSyntaxError, "Error in {% restructuredtext %} filter: The Python docutils library isn't installed."
+ raise template.TemplateSyntaxError("Error in {% restructuredtext %} filter: The Python docutils library isn't installed.")
return force_unicode(value)
else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
@@ -58,7 +58,7 @@ def get_decoded(self):
pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
from django.core.exceptions import SuspiciousOperation
- raise SuspiciousOperation, "User tampered with session cookie."
+ raise SuspiciousOperation("User tampered with session cookie.")
try:
return pickle.loads(pickled)
# Unpickling can cause a variety of exceptions. If something happens,
@@ -14,7 +14,7 @@ def get_query_set(self):
try:
self.model._meta.get_field(self.__field_name)
except FieldDoesNotExist:
- raise ValueError, "%s couldn't find a field named %s in %s." % \
- (self.__class__.__name__, self.__field_name, self.model._meta.object_name)
+ raise ValueError("%s couldn't find a field named %s in %s." % \
+ (self.__class__.__name__, self.__field_name, self.model._meta.object_name))
self.__is_validated = True
return super(CurrentSiteManager, self).get_query_set().filter(**{self.__field_name + '__id__exact': settings.SITE_ID})
@@ -38,7 +38,7 @@ def item_link(self, item):
try:
return item.get_absolute_url()
except AttributeError:
- raise ImproperlyConfigured, "Give your %s class a get_absolute_url() method, or define an item_link() method in your Feed class." % item.__class__.__name__
+ raise ImproperlyConfigured("Give your %s class a get_absolute_url() method, or define an item_link() method in your Feed class." % item.__class__.__name__)
def __get_dynamic_attr(self, attname, obj, default=None):
try:
@@ -3,7 +3,7 @@
def feed(request, url, feed_dict=None):
if not feed_dict:
- raise Http404, "No feeds are registered."
+ raise Http404("No feeds are registered.")
try:
slug, param = url.split('/', 1)
@@ -13,12 +13,12 @@ def feed(request, url, feed_dict=None):
try:
f = feed_dict[slug]
except KeyError:
- raise Http404, "Slug %r isn't registered." % slug
+ raise Http404("Slug %r isn't registered." % slug)
try:
feedgen = f(slug, request).get_feed(param)
except feeds.FeedDoesNotExist:
- raise Http404, "Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug
+ raise Http404("Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug)
response = HttpResponse(mimetype=feedgen.mime_type)
feedgen.write(response, 'utf-8')
@@ -39,10 +39,10 @@ def parse_backend_uri(backend_uri):
(scheme, host, params) tuple.
"""
if backend_uri.find(':') == -1:
- raise InvalidCacheBackendError, "Backend URI must start with scheme://"
+ raise InvalidCacheBackendError("Backend URI must start with scheme://")
scheme, rest = backend_uri.split(':', 1)
if not rest.startswith('//'):
- raise InvalidCacheBackendError, "Backend URI must start with scheme://"
+ raise InvalidCacheBackendError("Backend URI must start with scheme://")
host = rest[2:]
qpos = rest.find('?')
@@ -71,7 +71,7 @@ def incr(self, key, delta=1):
ValueError exception.
"""
if key not in self:
- raise ValueError, "Key '%s' not found" % key
+ raise ValueError("Key '%s' not found" % key)
new_value = self.get(key) + delta
self.set(key, new_value)
return new_value
@@ -129,7 +129,7 @@ def _createdir(self):
try:
os.makedirs(self._dir)
except OSError:
- raise EnvironmentError, "Cache directory '%s' does not exist and could not be created'" % self._dir
+ raise EnvironmentError("Cache directory '%s' does not exist and could not be created'" % self._dir)
def _key_to_file(self, key):
"""
@@ -34,16 +34,16 @@ def load_middleware(self):
try:
dot = middleware_path.rindex('.')
except ValueError:
- raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path
+ raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path)
mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
try:
mod = import_module(mw_module)
except ImportError, e:
- raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
+ raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
try:
mw_class = getattr(mod, mw_classname)
except AttributeError:
- raise exceptions.ImproperlyConfigured, 'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
+ raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname))
try:
mw_instance = mw_class()
@@ -113,7 +113,7 @@ def get_response(self, request):
view_name = callback.func_name # If it's a function
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class
- raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)
+ raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))
return response
except http.Http404, e:
@@ -152,7 +152,7 @@ def call_command(name, *args, **options):
else:
klass = load_command_class(app_name, name)
except KeyError:
- raise CommandError, "Unknown command: %r" % name
+ raise CommandError("Unknown command: %r" % name)
# Grab out a list of defaults from the options. optparse does this for us
# when the script runs from the command line, but since call_command can
@@ -530,7 +530,7 @@ def server_bind(self):
try:
HTTPServer.server_bind(self)
except Exception, e:
- raise WSGIServerException, e
+ raise WSGIServerException(e)
self.setup_environ()
def setup_environ(self):
@@ -135,10 +135,10 @@ def _get_callback(self):
self._callback = get_callable(self._callback_str)
except ImportError, e:
mod_name, _ = get_mod_func(self._callback_str)
- raise ViewDoesNotExist, "Could not import %s. Error was: %s" % (mod_name, str(e))
+ raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))
except AttributeError, e:
mod_name, func_name = get_mod_func(self._callback_str)
- raise ViewDoesNotExist, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))
+ raise ViewDoesNotExist("Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e)))
return self._callback
callback = property(_get_callback)
@@ -234,8 +234,8 @@ def resolve(self, path):
sub_match_dict[smart_str(k)] = v
return sub_match[0], sub_match[1], sub_match_dict
tried.append(pattern.regex.pattern)
- raise Resolver404, {'tried': tried, 'path': new_path}
- raise Resolver404, {'path' : path}
+ raise Resolver404({'tried': tried, 'path': new_path})
+ raise Resolver404({'path' : path})
def _get_urlconf_module(self):
try:
@@ -250,8 +250,7 @@ def _get_url_patterns(self):
try:
iter(patterns)
except TypeError:
- raise ImproperlyConfigured("The included urlconf %s doesn't have any "
- "patterns in it" % self.urlconf_name)
+ raise ImproperlyConfigured("The included urlconf %s doesn't have any patterns in it" % self.urlconf_name)
return patterns
url_patterns = property(_get_url_patterns)
@@ -260,7 +259,7 @@ def _resolve_special(self, view_type):
try:
return get_callable(callback), {}
except (ImportError, AttributeError), e:
- raise ViewDoesNotExist, "Tried %s. Error was: %s" % (callback, str(e))
+ raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, str(e)))
def resolve404(self):
return self._resolve_special('404')
@@ -12,7 +12,7 @@
from django.db.backends.creation import BaseDatabaseCreation
def complain(*args, **kwargs):
- raise ImproperlyConfigured, "You haven't set the database ENGINE setting yet."
+ raise ImproperlyConfigured("You haven't set the database ENGINE setting yet.")
def ignore(*args, **kwargs):
pass
Oops, something went wrong. Retry.

0 comments on commit 5ceed0a

Please sign in to comment.