I am using python 3.6 to make a package.
I have a base class that uses some of its children in its methods. This obviously creates circular dependencies which were not a problem to work around.
However, restructuring the project I decided to make the package into a sub-package of a larger project. I simply created a new directory and moved everything into it, then added an empty __init__.py to the (now otherwise empty) parent directory.
---> package
------> __init__.py
------> sub_package
---------> __init__.py
---------> base_class.py
---------> child_class.py
The current import strategy I am using looks like this.
package/sub_package/__init__.py
from .base_class import BaseClass
from .child_class import ChildClass
In the modules within the sub-package, I am importing exclusively through this __init__.py, like so:
package/sub_package/base_class.py
import package.sub_package
class BaseClass:
def __init__(self):
# do stuff
def use_import(self):
# do stuff
return package.sub_package.ChildClass() # use child class
package/sub_package/child_class.py
import package.sub_package
class ChildClass(package.sub_package.BaseClass): # the error comes here
def __init__(self):
# do stuff
package.sub_package.BaseClass.__init__()
In reality, there are many files within the sub-package containing other child classes that sometimes use each other, if this is relevant please let me know.
It does not seem to be relevant to the error I am getting:
class ChildClass(package.sub_package.BaseClass):
AttributeError: module 'package' has no attribute 'sub_package'
Can anyone explain why this error comes about? The sub-package seems to have been successfully imported on the line above the one that tries to use it and results in an error. I don't understand why the import didn't cause an error if using its result like this did.
Edit: The error occurs when from a python script/interpreter, at the same level in the directory structure as package, runs code like:
import package.sub_package
or if in the package/__init__.py I import the sub-package, then simply importing the package overall causes the same error.