Python Django What is the pythonic way to import modules -


i using django, django rest_framework build apis. directory structure looks this

|-user_directory\   |-__init__.py   |-models\     |-__init__.py     |-contact.py   |-views\     |-__init__.py     |-contact.py |-myproject 

when writing views there lot of imports, moved them __init__.py. imports looks this

file user_directory/__init__.py

import logging, re, pdb logger = logging.getlogger("user_directory") 

file user_directory/views/__init__.py

from django.http import jsonresponse rest_framework.decorators import api_view, authentication_classes, permission_classes rest_framework import status rest_status rest_framework.response import response lib.request_utils import validate_request, customtokenauthentication rest_framework.permissions import isauthenticated user_directory import * 

file user_directory/views/contact.py

from user_directory.views import * user_directory.models.contact import contact 

now read @ many places doing from package import * considered bad practice in python. writing common imports in views/__init__.py not repeat code.

is way correct ? pythonic way ?

it's opinion-based question, here opinion.

using from package import * syntax horrible idea always. first problem have no idea variable came from: defined in imported file, imported in file file. it's hard manage, when project grows.

your ide/linter has no idea variable came either. can't check undeclared variables, can't find usages , can't use refactor -> rename function (which painful).

i suggest import it's exact name in every file. , not consider code duplication.

the 2 things improve in imports are:

  1. put every root package import on separate line:

    import logging import re import pdb 
  2. write imports in following order (standard library package, third-party packages , imports package), separate them empty line , order groups alphabetically. makes easier read:

    from django.http import jsonresponse rest_framework import status rest_status rest_framework.decorators import api_view, authentication_classes, permission_classes rest_framework.permissions import isauthenticated rest_framework.response import response  lib.request_utils import validate_request, customtokenauthentication 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -