Search code examples
pythonimportmodulepackagelibraries

Python master import file


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 ?


Solution

  • 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