How to avoid the "Duplicate Module Import Trap" in python?

Описание к видео How to avoid the "Duplicate Module Import Trap" in python?

Hello everyone! I hope this video has helped solve your questions and issues. This video is shared because a solution has been found for the question/problem. I create videos for questions that have solutions. If you have any other issues, feel free to reach out to me on Instagram:   / ky.emrah  

Below, you can find the text related to the question/problem. In the video, the question will be presented first, followed by the answers. If the video moves too fast, feel free to pause and review the answers. If you need more detailed information, you can find the necessary sources and links at the bottom of this description. I hope this video has been helpful, and even if it doesn't directly solve your problem, it will guide you to the source of the solution. I'd appreciate it if you like the video and subscribe to my channel!Hello everyone! I hope this video has helped solve your questions and issues. This video is shared because a solution has been found for the question/problem. I create videos for questions that have solutions. If you have any other issues, feel free to reach out to me on Instagram:   / ky.emrah  

Below, you can find the text related to the question/problem. In the video, the question will be presented first, followed by the answers. If the video moves too fast, feel free to pause and review the answers. If you need more detailed information, you can find the necessary sources and links at the bottom of this description. I hope this video has been helpful, and even if it doesn't directly solve your problem, it will guide you to the source of the solution. I'd appreciate it if you like the video and subscribe to my channel!How to avoid the "Duplicate Module Import Trap" in python?

I recently encountered a perplexing issue regarding module imports in Python, particularly with the way instances of classes can be duplicated based on different import styles.
I had to fight to be able to reproduce. It was not so easy.
Main issue
Main issue
According to the import style, a module variable can be duplicated (instantiated several time, even without cyclic import). It's very hard to see that at program time, and can be tedious to debug.
Main question
Main question
What is the best practice to avoid this issue?
Illustration
Illustration
Here is a simple project
PROJECT ROOT FOLDER
└───app
│ main.py

└───websocket
a.py
b.py
ws.py
__init__.py

PROJECT ROOT FOLDER
└───app
│ main.py

└───websocket
a.py
b.py
ws.py
__init__.py

main.py
import sys


def log_modules():
print("\n\nModules currently in cache:")
for module_name in sys.modules:
if ("web" in module_name or "ws" in module_name) and ("windows" not in module_name and "asyncio" not in module_name):
print(f" - {module_name}: {id(sys.modules[module_name])}")


from app.websocket.a import a
log_modules()
from app.websocket.b import b
log_modules()


if _name_ == "__main__":
a()
b()

import sys


def log_modules():
print("\n\nModules currently in cache:")
for module_name in sys.modules:
if ("web" in module_name or "ws" in module_name) and ("windows" not in module_name and "asyncio" not in module_name):
print(f" - {module_name}: {id(sys.modules[module_name])}")


from app.websocket.a import a
log_modules()
from app.websocket.b import b
log_modules()


if _name_ == "__main__":
a()
b()

ws.py

class ConnectionManager:
def __init__(self):
print(f"New ConnectionManager object created, id: {id(self)}")
self.caller_list = []

def use(self, caller):
self.caller_list.append(caller)
print(f"ConnectionManager object used by {caller}, id: {id(self)}. Callers = {self.caller_list}")


websocket_manager = ConnectionManager()


class ConnectionManager:
def __init__(self):
print(f"New ConnectionManager object created, id: {id(self)}")
self.caller_list = []

def use(self, caller):
self.caller_list.append(caller)
print(f"ConnectionManager object used by {caller}, id: {id(self)}. Callers = {self.caller_list}")


websocket_manager = ConnectionManager()

a.py
from websocket.ws import websocket_manager # = one import styleSource of the question:
https://stackoverflow.com/questions/7...

Question and source license information:
https://meta.stackexchange.com/help/l...
https://stackoverflow.com/

Комментарии

Информация по комментариям в разработке