My package has the following structure:
myPackage
-- __init__.py <-- empty
-- signal.py
-- plot.py
signal.py contains:
from plot import plot_signal
def build_filter():
...
def other_function():
plot_signal()
plot.py contains:
from signal import build_filter
def plot_signal():
...
def other_function():
build_filter()
I then have my script that makes use of this package that contains something like:
import myPackage as mp
mp.plot.plot_signal()
When I run this I get an attribute error: module 'myPackage' has no attribute 'plot'
I'm not sure why its referring to plot
as an attribute when its a module in my package, or why its referring to myPackage
as a module.
I then tried importing my package and calling the function a different way:
from myPackage import plot, signal
plot.plot_signal()
However, now I get an import error: cannot import name 'build_filter'
and the traceback is referring to plot.py
where its trying to import the build_filter()
function from a sibling module.
I'm thinking this has something to do with the fact that the 2 modules are using functions from one another, and recursively importing the other module.
What's the correct way to organize this package so that sibling modules can import functions from each other?
Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.
You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.
A file is considered as a module in python. To use the module, you have to import it using the import keyword. The function or variables present inside the file can be used in another file by importing the module.
Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
To make mp.plot.plot_signal()
work, you must import plot
in the myPackage.__init__.py
.
Another thing is that in both plot.py and signal.py you should import the whole module to avoid circular imports:
signal.py:
import myPackage.plot
myPackage.plot.plot_signal()
plot.py
import myPackage.signal
myPackage.signal.build_filter()
You could also use the relative imports in all 3 files but it will work only in Python 3.x:
signal.py:
from . import plot
plot.plot_signal()
plot.py
from . import signal
signal.build_filter()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With