Search code examples
pythonpython-3.xshared-librariespython-module

How to share libraries across many files python


I checked few similiar questions and couldn't find satisfying answer. What is good practice if you want to reuse libraries across many different files. This is what I do right now:

# LIB.py
import sys
import platform
import socket

import mypyfile1
import mypyfile2


# RANDOM_PYFILE.py
import LIB

LIB.library.some_function()

Is this correct way to deal with this problem or is there better way?


Solution

  • Python is not like JavaScript where importing a script multiple times will cause multiple executions.

    Nor is it like C or CSS where importing/including a file multiple times will cause that file to be defined multiple times in your code. Python is smart enough to only import something once if it needs to.

    So go ahead and import everything you need in all the files that need it as many times as you want. Python will only ever load it in the process once.

    In fact this has created a specific issue with file reloading in Python where simply reimporting a file doesn't update your code. Python has a solution for this in the reload function. But you don't need that obviously.

    So don't worry. Import as many times as you want. That is the best practice in Python.