Search code examples
pythonbackwards-compatibility

Moving code out of __init__.py but keeping backwards compatibility


I'm working on a Python project where a previous developer placed a large portion of the code in the base __init__.py file. I would like to be able to move code out of the file to a new file in a subdirectory.

spam/
    __init__.py
    foobar/
        __init__.py
        eggs.py

So importing the spam module would use the code in foobar/eggs.py.

I would like to keep 100% compatibility because the code that current implements spam can't be changed.


Solution

  • 100% compatibility is probably not possible. A few things (like pickle) really care about where something is defined.

    You can get most of the compatibility by importing the classses/functions in the __init__.py file.