Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import import_lib

render()
get_object_or_404()

other_2.py

import import_lib

render()
get_object_or_404()

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading