Skip to content
Advertisement

how to manage file for import in Python?

I want to get a common library from several files. In order to reduce the amount of code, I want to create and manage a separate file for import. Will it be possible?

import_lib.py

from django.shortcuts import render, get_object_or_404

other_1.py

import import_lib

render()
get_object_or_404()

other_2.py

import import_lib

render()
get_object_or_404()

Advertisement

Answer

Don’t try to hide the imports needed in your module in another module – it’ll make your code harder to read. And good editors will allow you to collapse the import section if it gets in the way of editing. There’s ways of doing this, but they’ll make your code harder to understand and it’ll increase the odds of errors that are hard to figure out for yourself.

Having said that – this is how it can be done, if for some reason you know better, or actually have that rare use case where it makes sense:

import_lib.py

from django.shortcuts import render, get_object_or_404

other.py

from import_lib.py import *  # a rare case where a * import actually makes sense

Since * imports everything and makes it part of the name space of the module doing the importing, you get exactly what you need.

If you feel your use case does warrant this, at least consider a name for the imported module that’s a bit more descriptive, like django_imports.py, or whatever the logical grouping for the imports in that file is.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement