3

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.

Redox
  • 9,321
  • 5
  • 9
  • 26
Blowsh1t
  • 109
  • 1
  • 4
  • you might want to take a look at https://stackoverflow.com/questions/3106089/python-import-scope –  May 30 '22 at 11:05
  • Don't do this... it doesn't really make your code cleaner, instead it adds a layer of indirection which someone reading the code has to trace through in order to understand where everything comes from. Having the imports at the top of every file, without any auto-magic imports, is part of what makes Python more readable than other languages which have mechanisms for such things to happen implicitly. – Anentropic May 30 '22 at 11:10

2 Answers2

1

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 !

KB201
  • 101
  • 3
0

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

...
...
Lecdi
  • 2,189
  • 2
  • 6
  • 20