nautobot icon indicating copy to clipboard operation
nautobot copied to clipboard

Refactor all imports to use module namespaces

Open jathanism opened this issue 3 years ago • 1 comments

Proposed Changes

Currently in the code base there are many examples of large imports into the global namespace. For example, here is a sample of forms-related imports from nautobot/extras/forms.py:

from django import forms

from nautobot.utilities.forms import (
    add_blank_choice,
    APISelectMultiple,
    BootstrapMixin,
    BulkEditForm,
    BulkEditNullBooleanSelect,
    ColorSelect,
    CSVModelChoiceField,
    CSVModelForm,
    CSVMultipleContentTypeField,
    DateTimePicker,
    DynamicModelChoiceField,
    DynamicModelMultipleChoiceField,
    JSONField,
    MultipleContentTypeField,
    SlugField,
    StaticSelect2,
    StaticSelect2Multiple,
    BOOLEAN_WITH_BLANK_CHOICES,
)

I'm proposing we move to this pattern:

from django import forms as djforms  # Django forms module
from nautobot.utilities import forms  # Our utilities.forms module
from nautobot.dcim import models as dcim_models  # DCIM models
    
 # In code..
class SomeForm(forms.CustomFieldModelForm, djforms.ModelForm):
    name = djforms.CharField(required=False)
    device = forms.CSVModelChoiceField(queryset=dcim_models.Device.objects.all())

    class Meta:
        model = dcim_models.Device

Justification

The current pattern is not only is unwieldy, but complicates merges, rebases, and refactors and in some cases can result in circular imports.

This way it's clear what is coming from Django forms and what is coming from internal forms modules, and any time something new is needed or used from nautobot.utilities.forms it doesn't need to be explicitly imported.

This also applies to more than just forms, but I was just selecting forms as a singular example of imports for a single module.

jathanism avatar Mar 26 '21 20:03 jathanism

We should get this codified into best practices and work towards this in every PR. If you touch it, update it.

bryanculver avatar Jul 12 '22 19:07 bryanculver

Script to automate refactoring of imports

refactor_imports.zip

gsnider2195 avatar Nov 22 '22 00:11 gsnider2195