How to structuring a read/write submodule in OOP Python

I am developing a python package that needs to be able to read/write from/to multiple formats. E.g. foo format and bar format. I am trying to contain the functions relating to each format in a single file, as below. I would also like the user interface to be along the lines of: c = my_package.io.read_foo(...) # do stuff c.write_to_bar(...) Structure my_class.py: contains main class of my package from io.write import WriteMixin class MyClass(WriteMixin): ... io/write.py: import foo, bar class WriteMixin: # register write functions, e.g.: def write_to_foo(self, ...): foo.write_foo(...) def write_to_bar(self, ...): bar.write_bar(...) io/__init__.py: from foo import read_foo from bar import read_bar io/foo.py: from my_class import MyClass def read_foo(): # ... read/parse foo into MyClass return MyClass(foos) def write_foo(): pass # other functions that deal with foo, might be used in read_foo, write_foo def foo_func1(): pass ... io/bar.py: from my_class import MyClass def read_bar(): # ... read/parse bar into MyClass return MyClass(bars) def write_bar(): pass # other functions that deal with bar, might be used in read_bar, write_bar def bar_func1(): pass ... This however results in a circular import (my_class

May 20, 2025 - 18:30
 0

I am developing a python package that needs to be able to read/write from/to multiple formats. E.g. foo format and bar format. I am trying to contain the functions relating to each format in a single file, as below. I would also like the user interface to be along the lines of:

c = my_package.io.read_foo(...)

# do stuff

c.write_to_bar(...)

Structure

my_class.py: contains main class of my package

from io.write import WriteMixin

class MyClass(WriteMixin):
    ...

io/write.py:

import foo, bar

class WriteMixin:
    # register write functions, e.g.:
    def write_to_foo(self, ...):
        foo.write_foo(...)

    def write_to_bar(self, ...):
        bar.write_bar(...)

io/__init__.py:

from foo import read_foo
from bar import read_bar

io/foo.py:

from my_class import MyClass

def read_foo():
    # ... read/parse foo into MyClass
    return MyClass(foos)

def write_foo():
    pass

# other functions that deal with foo, might be used in read_foo, write_foo
def foo_func1():
    pass
...

io/bar.py:

from my_class import MyClass

def read_bar():
    # ... read/parse bar into MyClass
    return MyClass(bars)

def write_bar():
    pass

# other functions that deal with bar, might be used in read_bar, write_bar
def bar_func1():
    pass
...

This however results in a circular import (my_class <-- io <-- my_class). I know I can split the read/write files, or importing the class within the function, but is there is a way to keep foo.py and bar.py as is, without any "hacky" fixes?

More generally, is there an accepted/recommended structure for i/o submodules in python, reading and writing multiple formats and using OOP?