Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to share import between modules?

Tags:

python

My package looks like this:

enter image description here

These helpers, since they are all dealing with scipy, all have common imports:

from matplotlib import pyplot as plt
import numpy as np

I'm wondering if it is possible to extract them out, and put it somewhere else, so I can reduce the duplicate code within each module?

like image 381
cqcn1991 Avatar asked Jan 30 '16 13:01

cqcn1991


1 Answers

You can create a file called my_imports.py which does all your imports and makes them available as * via the __all__ variable (note that the module names are declared as strings):

File my_imports.py:

import os, shutil
__all__ = ['os', 'shutil']

File your_other_file.py:

from my_imports import *
print(os.curdir)

Although you might want to be explicit in your other files:

File your_other_file.py:

from my_imports import os # or whichever you actually need.
print(os.curdir)

Still, this saves you having to specify the various sources each time — and can be done with a one-liner.

like image 68
andyhasit Avatar answered Oct 05 '22 04:10

andyhasit