Say I had a package foo that contained a submodule bar. I want to remove bar and make it it’s own package.
I removed bar and make it it’s own package but to help with the deprecation cycle, I override the __init__.py for foo with a custom ModuleType subclass that overrides __getattr__. The goal of overriding __getattr__ is to warm the user of foo, who is trying to access bar that bar is now it’s own package and have __getattr__ return the new standalone bar package.
Is that possible? I’m not sure if submodules are attributes of a module.
So essentially the before
foo package with bar as submodule.
bar is now own package and removed.
In __init__.py of foo.
from types import ModuleType
def __getattr__(self, attr):
if attr == "bar":
warnings.warn("bar is now own package. Import directly. This will raise attribute error in future.", DeprecationWarning)
sys.modules[__name__].__class__ = FooModule
I apologize for poor indentation, I’m on mobile and tried my best.
I would like to do it like this, or some similar approach because at work we are in the process of breaking up a monorepo and having a list of submodules that have been split out and caught like this would be the easiest solution in my mind currently.