diff options
Diffstat (limited to 'django/utils')
| -rw-r--r-- | django/utils/autoreload.py | 21 | ||||
| -rw-r--r-- | django/utils/datastructures.py | 5 | ||||
| -rw-r--r-- | django/utils/dateformat.py | 11 | ||||
| -rw-r--r-- | django/utils/formats.py | 18 | ||||
| -rw-r--r-- | django/utils/http.py | 5 | ||||
| -rw-r--r-- | django/utils/translation/__init__.py | 8 | ||||
| -rw-r--r-- | django/utils/translation/trans_real.py | 13 |
7 files changed, 27 insertions, 54 deletions
diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py index 2784a89aeb..a872d42d65 100644 --- a/django/utils/autoreload.py +++ b/django/utils/autoreload.py @@ -34,6 +34,7 @@ import subprocess import sys import time import traceback +from contextlib import suppress import _thread @@ -43,10 +44,8 @@ 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 . -try: +with suppress(ImportError): import threading # NOQA -except ImportError: - pass try: import termios @@ -54,7 +53,7 @@ except ImportError: termios = None USE_INOTIFY = False -try: +with suppress(ImportError): # Test whether inotify is enabled and likely to work import pyinotify @@ -62,8 +61,6 @@ try: if fd >= 0: USE_INOTIFY = True os.close(fd) -except ImportError: - pass RUN_RELOADER = True @@ -210,10 +207,8 @@ def code_changed(): continue if mtime != _mtimes[filename]: _mtimes = {} - try: + with suppress(ValueError): del _error_files[_error_files.index(filename)] - except ValueError: - pass return I18N_MODIFIED if filename.endswith('.mo') else FILE_MODIFIED return False @@ -292,19 +287,15 @@ 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) - try: + with suppress(KeyboardInterrupt): reloader_thread() - except KeyboardInterrupt: - pass else: - try: + with suppress(KeyboardInterrupt): 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 769637f1d3..b42f674eb0 100644 --- a/django/utils/datastructures.py +++ b/django/utils/datastructures.py @@ -1,5 +1,6 @@ import copy from collections import OrderedDict +from contextlib import suppress class OrderedSet: @@ -18,10 +19,8 @@ class OrderedSet: del self.dict[item] def discard(self, item): - try: + with suppress(KeyError): 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 d3f586aacf..d811e83965 100644 --- a/django/utils/dateformat.py +++ b/django/utils/dateformat.py @@ -14,6 +14,7 @@ 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, @@ -81,11 +82,9 @@ class TimeFormat(Formatter): if not self.timezone: return "" - try: + with suppress(NotImplementedError): if hasattr(self.data, 'tzinfo') and self.data.tzinfo: return self.data.tzname() or '' - except NotImplementedError: - pass return "" def f(self): @@ -166,13 +165,11 @@ class TimeFormat(Formatter): return "" name = None - try: - name = self.timezone.tzname(self.data) - except Exception: + with suppress(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(). - pass + name = self.timezone.tzname(self.data) if name is None: name = self.format('O') return str(name) diff --git a/django/utils/formats.py b/django/utils/formats.py index b0c78f5ab2..33865d93a8 100644 --- a/django/utils/formats.py +++ b/django/utils/formats.py @@ -1,6 +1,7 @@ import datetime import decimal import unicodedata +from contextlib import suppress from importlib import import_module from django.conf import settings @@ -79,10 +80,8 @@ def iter_format_modules(lang, format_module_path=None): locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: - try: + with suppress(ImportError): yield import_module('%s.formats' % (location % loc)) - except ImportError: - pass def get_format_modules(lang=None, reverse=False): @@ -110,10 +109,8 @@ 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) - try: + with suppress(KeyError): 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 @@ -121,12 +118,9 @@ def get_format(format_type, lang=None, use_l10n=None): val = None if use_l10n: for module in get_format_modules(lang): - try: - val = getattr(module, format_type) - if val is not None: - break - except AttributeError: - pass + val = getattr(module, format_type, None) + if val is not None: + break if val is None: if format_type not in FORMAT_SETTINGS: return format_type diff --git a/django/utils/http.py b/django/utils/http.py index 07b6ae246a..0870f1f180 100644 --- a/django/utils/http.py +++ b/django/utils/http.py @@ -5,6 +5,7 @@ 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, @@ -165,10 +166,8 @@ def parse_http_date_safe(date): """ Same as parse_http_date, but return None if the input is invalid. """ - try: + with suppress(Exception): 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 f342cf7227..4a6840782c 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 +from contextlib import ContextDecorator, suppress from django.utils.deprecation import RemovedInDjango21Warning from django.utils.functional import lazy @@ -126,11 +126,9 @@ def lazy_number(func, resultclass, number=None, **kwargs): number_value = rhs kwargs['number'] = number_value translated = func(**kwargs) - try: + # String may not contain a placeholder for the number. + with suppress(TypeError): 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 6b3aeb127e..f36c21f0a1 100644 --- a/django/utils/translation/trans_real.py +++ b/django/utils/translation/trans_real.py @@ -6,6 +6,7 @@ import re import sys import warnings from collections import OrderedDict +from contextlib import suppress from threading import local from django.apps import apps @@ -256,10 +257,8 @@ def get_language(): """Return the currently selected language.""" t = getattr(_active, "value", None) if t is not None: - try: + with suppress(AttributeError): 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 @@ -425,10 +424,8 @@ 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] - try: + with suppress(KeyError): 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() @@ -486,10 +483,8 @@ def get_language_from_request(request, check_path=False): lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) - try: + with suppress(LookupError): 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): |
