Home > Software engineering >  Is it possible to import all packages from a file like we do with requirements.txt?
Is it possible to import all packages from a file like we do with requirements.txt?

Time:11-08

I am always typing a lot of:

import pandas as pd
import stuff from stuff
import etc...

Is there any way to make a list of imports in a file to use with one line code?

Thanks

CodePudding user response:

Python follows the rule "explicit is better than implicit". So it's intended to have all imports used at the beginning of your file, even there are many.

If there is too much, it can be a sign that you should split your file into multiple files belonging to the same package.

CodePudding user response:

If you have a list of packages you want to import, saved as my_list.txt, you can do something like this:

with open('my_list.txt', 'r') as packages:
     for line in lines:
            __import__(line)

As a result, you will import every package indicated by my_list's lines.

  • Related