Best Practice for Add-ons using Third-Party Packages

As an alternative solution, according to Python documentation, you can directly import a local source file using spec_from_file_location function.

Let’s say pygments folder is located in libs folder as follows:

+---addons21
|   +---your_addon_root
|   |   +---libs
|   |   |   +---pygments

you can import it as follows:

import sys
import pathlib
import importlib.util

addon_root = pathlib.Path(__file__).resolve().parent
pygments_source = addon_root / 'libs' / 'pygments' / '__init__.py'
spec = importlib.util.spec_from_file_location('pygments', pygments_source)
module = importlib.util.module_from_spec(spec)
sys.modules['pygments'] = module
spec.loader.exec_module(module)

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

code = 'print("Hello World")'
print(highlight(code, PythonLexer(), HtmlFormatter()))
4 Likes