Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bumped minimum isort version to 5.1.0 and fixed inner imports. #13232

Merged
merged 1 commit into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions django/apps/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ def check_apps_ready(self):
"""Raise an exception if all apps haven't been imported yet."""
if not self.apps_ready:
from django.conf import settings

# If "not ready" is due to unconfigured settings, accessing
# INSTALLED_APPS raises a more helpful ImproperlyConfigured
# exception.
Expand Down
3 changes: 1 addition & 2 deletions django/contrib/admin/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,8 +814,7 @@ def _check_list_filter_item(self, obj, item, label):
2. ('field', SomeFieldListFilter) - a field-based list filter class
3. SomeListFilter - a non-field list filter class
"""

from django.contrib.admin import ListFilter, FieldListFilter
from django.contrib.admin import FieldListFilter, ListFilter

if callable(item) and not isinstance(item, models.Field):
# If item is option 3, it should be a ListFilter...
Expand Down
2 changes: 1 addition & 1 deletion django/contrib/admin/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class AuthorAdmin(admin.ModelAdmin):
The `site` kwarg is an admin site to use instead of the default admin site.
"""
from django.contrib.admin import ModelAdmin
from django.contrib.admin.sites import site as default_site, AdminSite
from django.contrib.admin.sites import AdminSite, site as default_site

def _model_admin_wrapper(admin_class):
if not models:
Expand Down
7 changes: 4 additions & 3 deletions django/contrib/admin/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -808,7 +808,7 @@ def log_addition(self, request, object, message):

The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, ADDITION
from django.contrib.admin.models import ADDITION, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
Expand All @@ -824,7 +824,7 @@ def log_change(self, request, object, message):

The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.admin.models import CHANGE, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
Expand All @@ -841,7 +841,7 @@ def log_deletion(self, request, object, object_repr):

The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, DELETION
from django.contrib.admin.models import DELETION, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
Expand Down Expand Up @@ -1910,6 +1910,7 @@ def _delete_view(self, request, object_id, extra_context):
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry

# First check if the user can see this history.
model = self.model
obj = self.get_object(request, unquote(object_id))
Expand Down
4 changes: 2 additions & 2 deletions django/contrib/admin/sites.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,11 +240,11 @@ def inner(request, *args, **kwargs):
return update_wrapper(inner, view)

def get_urls(self):
from django.urls import include, path, re_path
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.contenttypes.views imports ContentType.
from django.contrib.contenttypes import views as contenttype_views
from django.urls import include, path, re_path

def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
Expand Down Expand Up @@ -385,11 +385,11 @@ def login(self, request, extra_context=None):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)

from django.contrib.auth.views import LoginView
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.admin.forms eventually imports User.
from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth.views import LoginView
context = {
**self.each_context(request),
'title': _('Log in'),
Expand Down
8 changes: 6 additions & 2 deletions django/contrib/gis/db/backends/oracle/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,15 @@ def spatial_aggregate_name(self, agg_name):

# Routines for getting the OGC-compliant models.
def geometry_columns(self):
from django.contrib.gis.db.backends.oracle.models import OracleGeometryColumns
from django.contrib.gis.db.backends.oracle.models import (
OracleGeometryColumns,
)
return OracleGeometryColumns

def spatial_ref_sys(self):
from django.contrib.gis.db.backends.oracle.models import OracleSpatialRefSys
from django.contrib.gis.db.backends.oracle.models import (
OracleSpatialRefSys,
)
return OracleSpatialRefSys

def modify_insert_params(self, placeholder, params):
Expand Down
8 changes: 6 additions & 2 deletions django/contrib/gis/db/backends/spatialite/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,15 @@ def spatial_aggregate_name(self, agg_name):

# Routines for getting the OGC-compliant models.
def geometry_columns(self):
from django.contrib.gis.db.backends.spatialite.models import SpatialiteGeometryColumns
from django.contrib.gis.db.backends.spatialite.models import (
SpatialiteGeometryColumns,
)
return SpatialiteGeometryColumns

def spatial_ref_sys(self):
from django.contrib.gis.db.backends.spatialite.models import SpatialiteSpatialRefSys
from django.contrib.gis.db.backends.spatialite.models import (
SpatialiteSpatialRefSys,
)
return SpatialiteSpatialRefSys

def get_geometry_converter(self, expression):
Expand Down
3 changes: 3 additions & 0 deletions django/contrib/gis/db/backends/spatialite/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def create_model(self, model):

def delete_model(self, model, **kwargs):
from django.contrib.gis.db.models import GeometryField

# Drop spatial metadata (dropping the table does not automatically remove them)
for field in model._meta.local_fields:
if isinstance(field, GeometryField):
Expand Down Expand Up @@ -113,6 +114,7 @@ def add_field(self, model, field):

def remove_field(self, model, field):
from django.contrib.gis.db.models import GeometryField

# NOTE: If the field is a geometry field, the table is just recreated,
# the parent's remove_field can't be used cause it will skip the
# recreation if the field does not have a database type. Geometry fields
Expand All @@ -125,6 +127,7 @@ def remove_field(self, model, field):

def alter_db_table(self, model, old_db_table, new_db_table, disable_constraints=True):
from django.contrib.gis.db.models import GeometryField

# Remove geometry-ness from temp table
for field in model._meta.local_fields:
if isinstance(field, GeometryField):
Expand Down
9 changes: 5 additions & 4 deletions django/contrib/gis/geos/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ def __init__(self, ptr, cls):
if cls is None:
if GEOSGeometryBase._GEOS_CLASSES is None:
# Inner imports avoid import conflicts with GEOSGeometry.
from .linestring import LineString, LinearRing
from .point import Point
from .polygon import Polygon
from .collections import (
GeometryCollection, MultiPoint, MultiLineString, MultiPolygon,
GeometryCollection, MultiLineString, MultiPoint,
MultiPolygon,
)
from .linestring import LinearRing, LineString
from .point import Point
from .polygon import Polygon
GEOSGeometryBase._GEOS_CLASSES = {
0: Point,
1: LineString,
Expand Down
1 change: 1 addition & 0 deletions django/contrib/gis/management/commands/ogrinspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def handle(self, *args, **options):
# Returning the output of ogrinspect with the given arguments
# and options.
from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping

# Filter options to params accepted by `_ogrinspect`
ogr_options = {k: v for k, v in options.items()
if k in get_func_args(_ogrinspect) and v is not None}
Expand Down
4 changes: 3 additions & 1 deletion django/contrib/gis/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
try:
# LayerMapping requires DJANGO_SETTINGS_MODULE to be set,
# and ImproperlyConfigured is raised if that's not the case.
from django.contrib.gis.utils.layermapping import LayerMapping, LayerMapError # NOQA
from django.contrib.gis.utils.layermapping import ( # NOQA
LayerMapError, LayerMapping,
)
except ImproperlyConfigured:
pass
6 changes: 4 additions & 2 deletions django/core/files/locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ def _fd(f):

if os.name == 'nt':
import msvcrt
from ctypes import (sizeof, c_ulong, c_void_p, c_int64,
Structure, Union, POINTER, windll, byref)
from ctypes import (
POINTER, Structure, Union, byref, c_int64, c_ulong, c_void_p, sizeof,
windll,
)
from ctypes.wintypes import BOOL, DWORD, HANDLE

LOCK_SH = 0 # the default
Expand Down
2 changes: 1 addition & 1 deletion django/core/management/commands/diffsettings.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def add_arguments(self, parser):
)

def handle(self, **options):
from django.conf import settings, Settings, global_settings
from django.conf import Settings, global_settings, settings

# Because settings are imported lazily, we need to explicitly load them.
if not settings.configured:
Expand Down
1 change: 1 addition & 0 deletions django/core/management/commands/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def bpython(self, options):

def python(self, options):
import code

# Set up a dictionary to serve as the environment for the shell, so
# that tab completion works on objects that are imported at runtime.
imported_objects = {}
Expand Down
5 changes: 2 additions & 3 deletions django/core/serializers/pyyaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@

# Use the C (faster) implementation if possible
try:
from yaml import CSafeLoader as SafeLoader
from yaml import CSafeDumper as SafeDumper
from yaml import CSafeDumper as SafeDumper, CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader, SafeDumper
from yaml import SafeDumper, SafeLoader


class DjangoSafeDumper(SafeDumper):
Expand Down
2 changes: 1 addition & 1 deletion django/db/backends/base/base.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import _thread
import copy
import threading
import time
import warnings
from collections import deque
from contextlib import contextmanager

import _thread
import pytz

from django.conf import settings
Expand Down
6 changes: 4 additions & 2 deletions django/db/models/fields/related_lookups.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ def as_sql(self, compiler, connection):
# For multicolumn lookups we need to build a multicolumn where clause.
# This clause is either a SubqueryConstraint (for values that need to be compiled to
# SQL) or an OR-combined list of (col1 = val1 AND col2 = val2 AND ...) clauses.
from django.db.models.sql.where import WhereNode, SubqueryConstraint, AND, OR
from django.db.models.sql.where import (
AND, OR, SubqueryConstraint, WhereNode,
)

root_constraint = WhereNode(connector=OR)
if self.rhs_is_direct_value():
Expand Down Expand Up @@ -120,7 +122,7 @@ def as_sql(self, compiler, connection):
if isinstance(self.lhs, MultiColSource):
assert self.rhs_is_direct_value()
self.rhs = get_normalized_value(self.rhs, self.lhs)
from django.db.models.sql.where import WhereNode, AND
from django.db.models.sql.where import AND, WhereNode
root_constraint = WhereNode()
for target, source, val in zip(self.lhs.targets, self.lhs.sources, self.rhs):
lookup_class = target.get_lookup(self.lookup_name)
Expand Down
4 changes: 3 additions & 1 deletion django/db/models/functions/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ def as_oracle(self, compiler, connection, **extra_context):
if self.output_field.get_internal_type() == 'DurationField':
expression = self.get_source_expressions()[0]
options = self._get_repr_options()
from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval
from django.db.backends.oracle.functions import (
IntervalToSeconds, SecondsToInterval,
)
return compiler.compile(
SecondsToInterval(self.__class__(IntervalToSeconds(expression), **options))
)
Expand Down
4 changes: 3 additions & 1 deletion django/db/models/lookups.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ def __init__(self, lhs, rhs):
if bilateral_transforms:
# Warn the user as soon as possible if they are trying to apply
# a bilateral transformation on a nested QuerySet: that won't work.
from django.db.models.sql.query import Query # avoid circular import
from django.db.models.sql.query import ( # avoid circular import
Query,
)
if isinstance(rhs, Query):
raise NotImplementedError("Bilateral transformations on nested querysets are not implemented.")
self.bilateral_transforms = bilateral_transforms
Expand Down
2 changes: 1 addition & 1 deletion django/forms/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,7 +815,7 @@ def save_new_objects(self, commit=True):

def add_fields(self, form, index):
"""Add a hidden field for the object's primary key."""
from django.db.models import AutoField, OneToOneField, ForeignKey
from django.db.models import AutoField, ForeignKey, OneToOneField
self._pk_field = pk = self.model._meta.pk
# If a pk isn't editable, then it won't be on the form, so we need to
# add it here so we can tell which object is which when we get the
Expand Down
1 change: 1 addition & 0 deletions django/template/context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def debug(request):
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
context_extras['debug'] = True
from django.db import connections

# Return a lazy reference that computes connection.queries on access,
# to ensure it contains queries triggered after this function runs.
context_extras['sql_queries'] = lazy(
Expand Down
2 changes: 1 addition & 1 deletion django/template/defaulttags.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ def __init__(self, view_name, args, kwargs, asvar):
self.asvar = asvar

def render(self, context):
from django.urls import reverse, NoReverseMatch
from django.urls import NoReverseMatch, reverse
args = [arg.resolve(context) for arg in self.args]
kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()}
view_name = self.view_name.resolve(context)
Expand Down
1 change: 1 addition & 0 deletions django/test/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,7 @@ def get_backend():

def _login(self, user, backend=None):
from django.contrib.auth import login

# Create a fake request to store login details.
request = HttpRequest()
if self.session:
Expand Down
4 changes: 3 additions & 1 deletion django/test/selenium.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ def import_options(cls, browser):

@classmethod
def get_capability(cls, browser):
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.desired_capabilities import (
DesiredCapabilities,
)
return getattr(DesiredCapabilities, browser.upper())

def create_options(self):
Expand Down
4 changes: 3 additions & 1 deletion django/test/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,9 @@ def static_finders_changed(**kwargs):
@receiver(setting_changed)
def auth_password_validators_changed(**kwargs):
if kwargs['setting'] == 'AUTH_PASSWORD_VALIDATORS':
from django.contrib.auth.password_validation import get_default_password_validators
from django.contrib.auth.password_validation import (
get_default_password_validators,
)
get_default_password_validators.cache_clear()


Expand Down
1 change: 1 addition & 0 deletions django/utils/autoreload.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ def run(self, django_main_thread):
logger.debug('Waiting for apps ready_event.')
self.wait_for_apps_ready(apps, django_main_thread)
from django.urls import get_resolver

# Prevent a race condition where URL modules aren't loaded when the
# reloader starts by accessing the urlconf_module property.
try:
Expand Down
4 changes: 3 additions & 1 deletion django/utils/translation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ def __getattr__(self, real_name):
from django.conf import settings
if settings.USE_I18N:
from django.utils.translation import trans_real as trans
from django.utils.translation.reloader import watch_for_translation_changes, translation_file_changed
from django.utils.translation.reloader import (
translation_file_changed, watch_for_translation_changes,
)
autoreload_started.connect(watch_for_translation_changes, dispatch_uid='translation_file_changed')
file_changed.connect(translation_file_changed, dispatch_uid='translation_file_changed')
else:
Expand Down
1 change: 1 addition & 0 deletions django/utils/translation/reloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def translation_file_changed(sender, file_path, **kwargs):
"""Clear the internal translations cache if a .mo file is modified."""
if file_path.suffix == '.mo':
import gettext

from django.utils.translation import trans_real
gettext._translations = {}
trans_real._translations = {}
Expand Down
2 changes: 1 addition & 1 deletion django/views/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME):
"""
Default view used when request fails CSRF protection
"""
from django.middleware.csrf import REASON_NO_REFERER, REASON_NO_CSRF_COOKIE
from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_REFERER
c = {
'title': _("Forbidden"),
'main': _("CSRF verification failed. Request aborted."),
Expand Down
2 changes: 1 addition & 1 deletion docs/internals/contributing/writing-code/coding-style.txt
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ Imports

.. console::

$ python -m pip install isort
$ python -m pip install isort >= 5.1.0
$ isort -rc .

This runs ``isort`` recursively from your current directory, modifying any
Expand Down
2 changes: 1 addition & 1 deletion docs/internals/contributing/writing-code/unit-tests.txt
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ version of Python. A list of default environments can be seen as follows:
py3
flake8
docs
isort
isort>=5.1.0

Testing other Python versions and database backends
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
1 change: 1 addition & 0 deletions tests/annotations/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def cxOracle_py3_bug(func):
we mark them as expected failures until someone fixes them in #23843.
"""
from unittest import expectedFailure

from django.db import connection
return expectedFailure(func) if connection.vendor == 'oracle' else func

Expand Down