Importing libraries for projects

Viewed 70

I have a python project with multiple classes and files.

This is my folder structure:

main.py
directory
  |_ parent_class.py
  |_sub_directory_1
     |_child_class_1.py
  |_sub_directory_2
     |_child_class_2.py

I am using the same imports like pandas and numpy e.g. in all files. Is there a way to import those a single time so my code is cleaner? Many Thanks in advance.

2 Answers

There is a way to "refacto" your imports inside a parent module and then import * from parent_module.

However I would not recommend such practice as the more your project grows the more likely you are to produce circular imports !

I would say that the best practice is to only import your packages/modules where you really need them. If you want a cleaner code base, I can suggest you tools such as isort that will automatically format your imports !

You can't do this unless there is a single file which is imported by all of the other files. And even in that case, you either have to use from <file> import * (which is not a good practice), or use <file>.<module> every time you want to reference one of those modules, which just makes things unnecessarily long.

Therefore, doing this is not usually a good idea...

...However, if there are a lot of imports shared by all files and you are sure that doing this would make your code much clearer, you could consider creating a new file specifically for this purpose.

For example, you could add a file called common_imports at the top level, put all the imports in there, and just use from common_imports import * at the start of each file.

So:

common_imports.py

import numpy as np
import pandas as pd
...
...

Other files

from common_imports import *
...  # Other imports

...
...
Related