diff options
| author | Tim Graham <timograham@gmail.com> | 2017-09-07 08:16:21 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-09-07 08:16:21 -0400 |
| commit | 6e4c6281dbb7ee12bcdc22620894edb4e9cf623f (patch) | |
| tree | 1c21218d4b6f00c499f18943d5190ebe7b5248c9 /django/core | |
| parent | 8b2515a450ef376b9205029090af0a79c8341bd7 (diff) | |
Reverted "Fixed #27818 -- Replaced try/except/pass with contextlib.suppress()."
This reverts commit 550cb3a365dee4edfdd1563224d5304de2a57fda
because try/except performs better.
Diffstat (limited to 'django/core')
| -rw-r--r-- | django/core/cache/backends/filebased.py | 15 | ||||
| -rw-r--r-- | django/core/cache/backends/locmem.py | 19 | ||||
| -rw-r--r-- | django/core/files/move.py | 9 | ||||
| -rw-r--r-- | django/core/files/storage.py | 19 | ||||
| -rw-r--r-- | django/core/management/__init__.py | 13 | ||||
| -rw-r--r-- | django/core/management/base.py | 9 | ||||
| -rw-r--r-- | django/core/management/commands/flush.py | 5 | ||||
| -rw-r--r-- | django/core/management/commands/shell.py | 5 | ||||
| -rw-r--r-- | django/core/validators.py | 5 |
9 files changed, 61 insertions, 38 deletions
diff --git a/django/core/cache/backends/filebased.py b/django/core/cache/backends/filebased.py index deceffaa0d..dccc3fdc65 100644 --- a/django/core/cache/backends/filebased.py +++ b/django/core/cache/backends/filebased.py @@ -7,7 +7,6 @@ import random import tempfile import time import zlib -from contextlib import suppress from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.core.files.move import file_move_safe @@ -30,10 +29,12 @@ class FileBasedCache(BaseCache): def get(self, key, default=None, version=None): fname = self._key_to_file(key, version) - with suppress(FileNotFoundError): + try: with open(fname, 'rb') as f: if not self._is_expired(f): return pickle.loads(zlib.decompress(f.read())) + except FileNotFoundError: + pass return default def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): @@ -59,9 +60,11 @@ class FileBasedCache(BaseCache): def _delete(self, fname): if not fname.startswith(self._dir) or not os.path.exists(fname): return - with suppress(FileNotFoundError): - # The file may have been removed by another process. + try: os.remove(fname) + except FileNotFoundError: + # The file may have been removed by another process. + pass def has_key(self, key, version=None): fname = self._key_to_file(key, version) @@ -90,8 +93,10 @@ class FileBasedCache(BaseCache): def _createdir(self): if not os.path.exists(self._dir): - with suppress(FileExistsError): + try: os.makedirs(self._dir, 0o700) + except FileExistsError: + pass def _key_to_file(self, key, version=None): """ diff --git a/django/core/cache/backends/locmem.py b/django/core/cache/backends/locmem.py index 20b6dd4212..b2600d3169 100644 --- a/django/core/cache/backends/locmem.py +++ b/django/core/cache/backends/locmem.py @@ -1,7 +1,7 @@ "Thread-safe in-memory cache backend." import pickle import time -from contextlib import contextmanager, suppress +from contextlib import contextmanager from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.utils.synch import RWLock @@ -50,9 +50,11 @@ class LocMemCache(BaseCache): return default with (self._lock.writer() if acquire_lock else dummy()): - with suppress(KeyError): + try: del self._cache[key] del self._expire_info[key] + except KeyError: + pass return default def _set(self, key, value, timeout=DEFAULT_TIMEOUT): @@ -87,9 +89,11 @@ class LocMemCache(BaseCache): return True with self._lock.writer(): - with suppress(KeyError): + try: del self._cache[key] del self._expire_info[key] + except KeyError: + pass return False def _has_expired(self, key): @@ -107,11 +111,14 @@ class LocMemCache(BaseCache): self._delete(k) def _delete(self, key): - with suppress(KeyError): + try: del self._cache[key] - - with suppress(KeyError): + except KeyError: + pass + try: del self._expire_info[key] + except KeyError: + pass def delete(self, key, version=None): key = self.make_key(key, version=version) diff --git a/django/core/files/move.py b/django/core/files/move.py index 310e064a2d..4d791ac263 100644 --- a/django/core/files/move.py +++ b/django/core/files/move.py @@ -7,7 +7,6 @@ Move a file in the safest way possible:: import errno import os -from contextlib import suppress from shutil import copystat from django.core.files import locks @@ -42,14 +41,16 @@ def file_move_safe(old_file_name, new_file_name, chunk_size=1024 * 64, allow_ove if _samefile(old_file_name, new_file_name): return - # OSError happens with os.rename() if moving to another filesystem or when - # moving opened files on certain operating systems. - with suppress(OSError): + try: if not allow_overwrite and os.access(new_file_name, os.F_OK): raise IOError("Destination file %s exists and allow_overwrite is False" % new_file_name) os.rename(old_file_name, new_file_name) return + except OSError: + # OSError happens with os.rename() if moving to another filesystem or + # when moving opened files on certain operating systems. + pass # first open the old file, so that it won't go away with open(old_file_name, 'rb') as old_file: diff --git a/django/core/files/storage.py b/django/core/files/storage.py index fa98bb198a..30788d6d75 100644 --- a/django/core/files/storage.py +++ b/django/core/files/storage.py @@ -1,5 +1,4 @@ import os -from contextlib import suppress from datetime import datetime from urllib.parse import urljoin @@ -224,10 +223,7 @@ class FileSystemStorage(Storage): # Create any intermediate directories that do not exist. directory = os.path.dirname(full_path) if not os.path.exists(directory): - # There's a race between os.path.exists() and os.makedirs(). - # If os.makedirs() fails with FileNotFoundError, the directory - # was created concurrently. - with suppress(FileNotFoundError): + try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. @@ -238,6 +234,11 @@ class FileSystemStorage(Storage): os.umask(old_umask) else: os.makedirs(directory) + except FileNotFoundError: + # There's a race between os.path.exists() and os.makedirs(). + # If os.makedirs() fails with FileNotFoundError, the directory + # was created concurrently. + pass if not os.path.isdir(directory): raise IOError("%s exists and is not a directory." % directory) @@ -293,13 +294,15 @@ class FileSystemStorage(Storage): assert name, "The name argument is not allowed to be empty." name = self.path(name) # If the file or directory exists, delete it from the filesystem. - # FileNotFoundError is raised if the file or directory was removed - # concurrently. - with suppress(FileNotFoundError): + try: if os.path.isdir(name): os.rmdir(name) else: os.remove(name) + except FileNotFoundError: + # FileNotFoundError is raised if the file or directory was removed + # concurrently. + pass def exists(self, name): return os.path.exists(self.path(name)) diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py index b68692d60a..77c060c21c 100644 --- a/django/core/management/__init__.py +++ b/django/core/management/__init__.py @@ -3,7 +3,6 @@ import os import pkgutil import sys from collections import OrderedDict, defaultdict -from contextlib import suppress from importlib import import_module import django @@ -262,12 +261,14 @@ class ManagementUtility: subcommand_cls = self.fetch_command(cwords[0]) # special case: add the names of installed apps to options if cwords[0] in ('dumpdata', 'sqlmigrate', 'sqlsequencereset', 'test'): - # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The - # user will find out once they execute the command. - with suppress(ImportError): + try: app_configs = apps.get_app_configs() # Get the last part of the dotted path as the app name. options.extend((app_config.label, 0) for app_config in app_configs) + except ImportError: + # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The + # user will find out once they execute the command. + pass parser = subcommand_cls.create_parser('', cwords[0]) options.extend( (min(s_opt.option_strings), s_opt.nargs != 0) @@ -306,9 +307,11 @@ class ManagementUtility: parser.add_argument('--settings') parser.add_argument('--pythonpath') parser.add_argument('args', nargs='*') # catch-all - with suppress(CommandError): # Ignore any option errors at this point. + try: options, args = parser.parse_known_args(self.argv[2:]) handle_default_options(options) + except CommandError: + pass # Ignore any option errors at this point. try: settings.INSTALLED_APPS diff --git a/django/core/management/base.py b/django/core/management/base.py index b53b414fdb..41b6b0fa91 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -5,7 +5,6 @@ be executed through ``django-admin`` or ``manage.py``). import os import sys from argparse import ArgumentParser -from contextlib import suppress from io import TextIOBase import django @@ -298,10 +297,12 @@ class BaseCommand: self.stderr.write('%s: %s' % (e.__class__.__name__, e)) sys.exit(1) finally: - # Ignore if connections aren't setup at this point (e.g. no - # configured settings). - with suppress(ImproperlyConfigured): + try: connections.close_all() + except ImproperlyConfigured: + # Ignore if connections aren't setup at this point (e.g. no + # configured settings). + pass def execute(self, *args, **options): """ diff --git a/django/core/management/commands/flush.py b/django/core/management/commands/flush.py index 0df5f67e39..f6ae83940a 100644 --- a/django/core/management/commands/flush.py +++ b/django/core/management/commands/flush.py @@ -1,4 +1,3 @@ -from contextlib import suppress from importlib import import_module from django.apps import apps @@ -40,8 +39,10 @@ class Command(BaseCommand): # Import the 'management' module within each installed app, to register # dispatcher events. for app_config in apps.get_app_configs(): - with suppress(ImportError): + try: import_module('.management', app_config.name) + except ImportError: + pass sql_list = sql_flush(self.style, connection, only_django=True, reset_sequences=reset_sequences, diff --git a/django/core/management/commands/shell.py b/django/core/management/commands/shell.py index ce013bcec0..7c9a43434a 100644 --- a/django/core/management/commands/shell.py +++ b/django/core/management/commands/shell.py @@ -2,7 +2,6 @@ import os import select import sys import traceback -from contextlib import suppress from django.core.management import BaseCommand, CommandError from django.utils.datastructures import OrderedSet @@ -96,6 +95,8 @@ class Command(BaseCommand): available_shells = [options['interface']] if options['interface'] else self.shells for shell in available_shells: - with suppress(ImportError): + try: return getattr(self, shell)(options) + except ImportError: + pass raise CommandError("Couldn't import {} interface.".format(shell)) diff --git a/django/core/validators.py b/django/core/validators.py index c6d5e6e06a..b36ab60704 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -1,7 +1,6 @@ import ipaddress import os import re -from contextlib import suppress from urllib.parse import urlsplit, urlunsplit from django.core.exceptions import ValidationError @@ -215,9 +214,11 @@ class EmailValidator: literal_match = self.literal_regex.match(domain_part) if literal_match: ip_address = literal_match.group(1) - with suppress(ValidationError): + try: validate_ipv46_address(ip_address) return True + except ValidationError: + pass return False def __eq__(self, other): |
