summaryrefslogtreecommitdiff
path: root/django/utils
diff options
context:
space:
mode:
authorTim Graham <timograham@gmail.com>2017-09-07 08:16:21 -0400
committerGitHub <noreply@github.com>2017-09-07 08:16:21 -0400
commit6e4c6281dbb7ee12bcdc22620894edb4e9cf623f (patch)
tree1c21218d4b6f00c499f18943d5190ebe7b5248c9 /django/utils
parent8b2515a450ef376b9205029090af0a79c8341bd7 (diff)
Reverted "Fixed #27818 -- Replaced try/except/pass with contextlib.suppress()."
This reverts commit 550cb3a365dee4edfdd1563224d5304de2a57fda because try/except performs better.
Diffstat (limited to 'django/utils')
-rw-r--r--django/utils/autoreload.py21
-rw-r--r--django/utils/datastructures.py5
-rw-r--r--django/utils/dateformat.py11
-rw-r--r--django/utils/formats.py9
-rw-r--r--django/utils/http.py5
-rw-r--r--django/utils/translation/__init__.py8
-rw-r--r--django/utils/translation/trans_real.py13
7 files changed, 48 insertions, 24 deletions
diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py
index a872d42d65..2784a89aeb 100644
--- a/django/utils/autoreload.py
+++ b/django/utils/autoreload.py
@@ -34,7 +34,6 @@ import subprocess
import sys
import time
import traceback
-from contextlib import suppress
import _thread
@@ -44,8 +43,10 @@ from django.core.signals import request_finished
# This import does nothing, but it's necessary to avoid some race conditions
# in the threading module. See http://code.djangoproject.com/ticket/2330 .
-with suppress(ImportError):
+try:
import threading # NOQA
+except ImportError:
+ pass
try:
import termios
@@ -53,7 +54,7 @@ except ImportError:
termios = None
USE_INOTIFY = False
-with suppress(ImportError):
+try:
# Test whether inotify is enabled and likely to work
import pyinotify
@@ -61,6 +62,8 @@ with suppress(ImportError):
if fd >= 0:
USE_INOTIFY = True
os.close(fd)
+except ImportError:
+ pass
RUN_RELOADER = True
@@ -207,8 +210,10 @@ def code_changed():
continue
if mtime != _mtimes[filename]:
_mtimes = {}
- with suppress(ValueError):
+ try:
del _error_files[_error_files.index(filename)]
+ except ValueError:
+ pass
return I18N_MODIFIED if filename.endswith('.mo') else FILE_MODIFIED
return False
@@ -287,15 +292,19 @@ def restart_with_reloader():
def python_reloader(main_func, args, kwargs):
if os.environ.get("RUN_MAIN") == "true":
_thread.start_new_thread(main_func, args, kwargs)
- with suppress(KeyboardInterrupt):
+ try:
reloader_thread()
+ except KeyboardInterrupt:
+ pass
else:
- with suppress(KeyboardInterrupt):
+ try:
exit_code = restart_with_reloader()
if exit_code < 0:
os.kill(os.getpid(), -exit_code)
else:
sys.exit(exit_code)
+ except KeyboardInterrupt:
+ pass
def jython_reloader(main_func, args, kwargs):
diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py
index 7713b08e8c..127c6dc774 100644
--- a/django/utils/datastructures.py
+++ b/django/utils/datastructures.py
@@ -1,6 +1,5 @@
import copy
from collections import OrderedDict
-from contextlib import suppress
class OrderedSet:
@@ -19,8 +18,10 @@ class OrderedSet:
del self.dict[item]
def discard(self, item):
- with suppress(KeyError):
+ try:
self.remove(item)
+ except KeyError:
+ pass
def __iter__(self):
return iter(self.dict)
diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py
index d811e83965..d3f586aacf 100644
--- a/django/utils/dateformat.py
+++ b/django/utils/dateformat.py
@@ -14,7 +14,6 @@ import calendar
import datetime
import re
import time
-from contextlib import suppress
from django.utils.dates import (
MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR,
@@ -82,9 +81,11 @@ class TimeFormat(Formatter):
if not self.timezone:
return ""
- with suppress(NotImplementedError):
+ try:
if hasattr(self.data, 'tzinfo') and self.data.tzinfo:
return self.data.tzname() or ''
+ except NotImplementedError:
+ pass
return ""
def f(self):
@@ -165,11 +166,13 @@ class TimeFormat(Formatter):
return ""
name = None
- with suppress(Exception):
+ try:
+ name = self.timezone.tzname(self.data)
+ except Exception:
# pytz raises AmbiguousTimeError during the autumn DST change.
# This happens mainly when __init__ receives a naive datetime
# and sets self.timezone = get_default_timezone().
- name = self.timezone.tzname(self.data)
+ pass
if name is None:
name = self.format('O')
return str(name)
diff --git a/django/utils/formats.py b/django/utils/formats.py
index 33865d93a8..f19449ec1e 100644
--- a/django/utils/formats.py
+++ b/django/utils/formats.py
@@ -1,7 +1,6 @@
import datetime
import decimal
import unicodedata
-from contextlib import suppress
from importlib import import_module
from django.conf import settings
@@ -80,8 +79,10 @@ def iter_format_modules(lang, format_module_path=None):
locales.append(locale.split('_')[0])
for location in format_locations:
for loc in locales:
- with suppress(ImportError):
+ try:
yield import_module('%s.formats' % (location % loc))
+ except ImportError:
+ pass
def get_format_modules(lang=None, reverse=False):
@@ -109,8 +110,10 @@ def get_format(format_type, lang=None, use_l10n=None):
if use_l10n and lang is None:
lang = get_language()
cache_key = (format_type, lang)
- with suppress(KeyError):
+ try:
return _format_cache[cache_key]
+ except KeyError:
+ pass
# The requested format_type has not been cached yet. Try to find it in any
# of the format_modules for the given lang if l10n is enabled. If it's not
diff --git a/django/utils/http.py b/django/utils/http.py
index 0870f1f180..07b6ae246a 100644
--- a/django/utils/http.py
+++ b/django/utils/http.py
@@ -5,7 +5,6 @@ import re
import unicodedata
import warnings
from binascii import Error as BinasciiError
-from contextlib import suppress
from email.utils import formatdate
from urllib.parse import (
ParseResult, SplitResult, _coerce_args, _splitnetloc, _splitparams, quote,
@@ -166,8 +165,10 @@ def parse_http_date_safe(date):
"""
Same as parse_http_date, but return None if the input is invalid.
"""
- with suppress(Exception):
+ try:
return parse_http_date(date)
+ except Exception:
+ pass
# Base 36 functions: useful for generating compact URLs
diff --git a/django/utils/translation/__init__.py b/django/utils/translation/__init__.py
index 4a6840782c..b4586885c4 100644
--- a/django/utils/translation/__init__.py
+++ b/django/utils/translation/__init__.py
@@ -3,7 +3,7 @@ Internationalization support.
"""
import re
import warnings
-from contextlib import ContextDecorator, suppress
+from contextlib import ContextDecorator
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.functional import lazy
@@ -126,9 +126,11 @@ def lazy_number(func, resultclass, number=None, **kwargs):
number_value = rhs
kwargs['number'] = number_value
translated = func(**kwargs)
- # String may not contain a placeholder for the number.
- with suppress(TypeError):
+ try:
translated = translated % rhs
+ except TypeError:
+ # String doesn't contain a placeholder for the number.
+ pass
return translated
proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs)
diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py
index f36c21f0a1..6b3aeb127e 100644
--- a/django/utils/translation/trans_real.py
+++ b/django/utils/translation/trans_real.py
@@ -6,7 +6,6 @@ import re
import sys
import warnings
from collections import OrderedDict
-from contextlib import suppress
from threading import local
from django.apps import apps
@@ -257,8 +256,10 @@ def get_language():
"""Return the currently selected language."""
t = getattr(_active, "value", None)
if t is not None:
- with suppress(AttributeError):
+ try:
return t.to_language()
+ except AttributeError:
+ pass
# If we don't have a real translation object, assume it's the default language.
return settings.LANGUAGE_CODE
@@ -424,8 +425,10 @@ def get_supported_language_variant(lang_code, strict=False):
if lang_code:
# If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
possible_lang_codes = [lang_code]
- with suppress(KeyError):
+ try:
possible_lang_codes.extend(LANG_INFO[lang_code]['fallback'])
+ except KeyError:
+ pass
generic_lang_code = lang_code.split('-')[0]
possible_lang_codes.append(generic_lang_code)
supported_lang_codes = get_languages()
@@ -483,8 +486,10 @@ def get_language_from_request(request, check_path=False):
lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
- with suppress(LookupError):
+ try:
return get_supported_language_variant(lang_code)
+ except LookupError:
+ pass
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
for accept_lang, unused in parse_accept_lang_header(accept):