Saturday, 16 October 2021

Package-level exports, circular dependencies

I have the following package:

foo/
    __init__.py:
        from .body import UsefulClass
        from .another import AnotherClass

    body.py:

        from . import utll
        class UsefulClass:
            util.do_something()

    another.py:

        class AnotherClass: ...

    util.py:

        def do_something...

   

The idea is, when someone imports foo, they should be able to use foo.UsefulClass without worrying about the internal structure of the package. In other words, I don't want them to import foo.body, just foo.

However, when I do from . import util in body.py this also imports __init__.py, which in turn imports body once again. I realize that python handles this situation well, however I'm not comfortable having this obviously circular dependency.

Is there a better way to export things at the package level without creating circular dependencies in imports?

PS: I'd like to avoid in-function imports



from Package-level exports, circular dependencies

No comments:

Post a Comment