1

I have several scripts in a project folder, most of which use the same handful of standard libraries and modules. Instead of having to reiterate in every single script

import pandas as pd
import numpy as np
import datetime
import re
etc
etc

is it possible for me to place all import statements in a masterImports.py file and simply import masterImports at the top of each script ?

ZwiTrader
  • 195
  • 1
  • 2
  • 12
  • Check this [question](https://stackoverflow.com/questions/49657845/python-import-import-multiple-modules-in-one-file) – Abhi Jul 20 '21 at 03:48

2 Answers2

1

Yes you can.

So the basic idea is to import all the libraries in one file. Then import that file.

An example:

masterImports.py

import pandas as pd
import numpy as np
import datetime
import re
etc
etc

otherFile.py

import masterImports as mi
print(mi.datetime.datetime(2021,7,20))

Or you could use wildcard imports -

from masterImports import * # OR from masterImports import important_package
print(datetime.datetime(2021,7,20))

Do not use wildcard asterix imports because there can be name clashes

Try this, and you will see that there is no error

PCM
  • 2,881
  • 2
  • 8
  • 30
  • Thanks, @PCM. However, can you please clarify your comments at the end of your post. You propose ```import * ``` as a solution, then proceed to say that it can cause problems, then say that it will cause no error. Based on another small test I ran, the wildcard import is giving me the desired result (importing into file2 all that was initially imported in file1), but I am failing to see what you are cautioning me about. – ZwiTrader Jul 22 '21 at 14:29
  • Well yeah, sometimes it can be useful. But as I said, it is better to use it carefully see [why](https://stackoverflow.com/questions/3615125/should-wildcard-import-be-avoided). I was only telling you to be cautious. Name clashes mean when you are importing any file it might overwrite in-built or user-built functions. So, I said it is better to avoid that. – PCM Jul 22 '21 at 14:49
  • If my answer helps you, kindly accept it. – PCM Jul 22 '21 at 14:50
0

It's possible, although not really the done thing

To use it, you'd need to do, at the top of each script:

from master_imports import *
Jiří Baum
  • 6,697
  • 2
  • 17
  • 17