Circular Imports in Python


**packages : directory with __init__.py

**modules : files with .py extension

**submodules : modules that are inside larger package and subset of term module

Circular Imports: When 2 files are imported modules from each other.

When the import is used in Python files to import modules, that import will be dynamically executed and the modules will be generated on demand as required.

While having circular imports, the issue arises when the import of the first module gets called, another module is supposed to be created but another module also depends on the creation of the first module. This is where deadlock occurs.

The basic solution would be to stop the dynamic initiation of modules on the invocation of Python modules.

How to resolve the issue :

  1. Delegate the import : Import statement modules can be done inside the methods. So when the required method is needed only the import will be executed hence we are delegating the execution of import statements.In a.py

def func():
    from package import b
        

In b.py

def func():
    from package import a
        

2. Errors using imported objects with circular dependencies :

Now, while you may be able to import a module with a circular import dependency, you won't be able to import any objects defined in the module or actually be able to reference that imported module anywhere in the top level of the module where you're importing it. You can, however, use the imported module inside functions and code blocks that don't get run on import.

For example, this will work:

package/a.py

import package.b

def func_a():
    return "a"
        

package/b.py

import package.a

def func_b():
    # Notice how package.a is only referenced *inside* a function
    # and not the top level of the module.
    return package.a.func_a() + "b"        



要查看或添加评论,请登录

Pushkal Goyal的更多文章

  • Partitioning & Replication

    Partitioning & Replication

    Partitioning: Process of dividing data into independent segments. Need of Partitioning: If the data is served without…

  • Merkle Tree :

    Merkle Tree :

    A concept popular in Distributed Systems. Merkle Tree is a binary tree used for easy search and secure verification of…

  • Interpreter and Compiler

    Interpreter and Compiler

    Python => interpreter & other languages like CPP => compiler-based languages. I didn't know the way I could see the…

  • Consistent Hashing

    Consistent Hashing

    It is one of the system design techniques used to optimize performance issues with horizontal hashing while scaling…

  • POSIX

    POSIX

    It stands for Portable Operating System Interface. This is a compliance introduced by the US government for procurement…

社区洞察

其他会员也浏览了