Skip to content Skip to sidebar Skip to footer

How To Share Imports Between Modules?

My package looks like this: 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 i

Solution 1:

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

Edit

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

File your_other_file.py:

from my_imports import os, shutil  # 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.

Solution 2:

Alright, here is my tweak,

enter image description here

Create a gemfile under the package dir, like this

import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl

Then, for other files, like app_helper.py

from .gemfileimport *

This comes from here Can I use __init__.py to define global variables?

Post a Comment for "How To Share Imports Between Modules?"