[Fixed]-Python Django What is the pythonic way to import modules

1👍

It’s really opinion-based question, so here is my opinion.

Using from package import * syntax is horrible idea almost always. The first problem is that you have no idea from where the variable came from: was it defined in imported file, was it imported in that file from another file. It’s really hard to manage, when your project grows.

Your IDE/linter has no idea from where this variable came either. So it can’t check for undeclared variables, can’t properly find usages and your can’t use Refactor -> Rename function (which is the most painful).

I would suggest to import everything by it’s exact name in every file. And do not consider it a code duplication.

The two things I would improve in your imports are:

  1. Put every root package import on separate line:

    import logging
    import re
    import pdb
    
  2. Write imports in the following order (standard library package, third-party packages and imports from your package), separate them by empty line and order groups alphabetically. It makes it much easier to read:

    from django.http import JsonResponse
    from rest_framework import status as rest_status
    from rest_framework.decorators import api_view, authentication_classes, permission_classes
    from rest_framework.permissions import IsAuthenticated
    from rest_framework.response import Response
    
    from lib.request_utils import validate_request, CustomTokenAuthentication
    

Leave a comment