Best way to import a module from python macro

Hi!
I am trying to launch a python macro from a button. But then this macro loads another py module.
The problem is that the second module has not access to XSCRIPTCONTEXT.

Right now I have 2 workarounds:

Workaround 1:
Using this in 1st module:

sys.modules['XSCRIPTCONTEXT'] = XSCRIPTCONTEXT

and this in 2nd module:

XSCRIPTCONTEXT = sys.modules.get('XSCRIPTCONTEXT')

Workaround 2:
Using this in 1st module:

imported_module.set_context(XSCRIPTCONTEXT)

and this in 2nd module:

def set_context(context):
	global XSCRIPTCONTEXT
	XSCRIPTCONTEXT = context

They both work. But is there a better and more direct and simpler way of doing this? What is the right way?
Thank you very much!

Why do you need XSCRIPTCONTEXT in the second module?

What do you “really” want to do?

Hi elmau
My intention is to be able to make modularly reusable libraries.
I give you an example, in the second module there could be:

def msg(message, title="LibreOffice", buttons=BUTTONS_OK, msg_type=MESSAGEBOX):
    doc = XSCRIPTCONTEXT.getDocument()
    parent = doc.CurrentController.Frame.ContainerWindow
    toolkit = parent.getToolkit()
    box = toolkit.createMessageBox(parent, msg_type, buttons, title, message)
    result = box.execute()
    return result

The idea is to be able to use functions like this one or more complex ones without rewriting the functions in each .py
Thank you!

Create a directoy pythonpath in the Scripts/python/ directory of your user profile.

This is what I have already been doing, that is why I can correctly import the module. But it does not give access to XSCRIPTCONTEXT

sys.path.append(my_module_folder) # add folder where my_module.py is
import my_module # works great -> import success
my_module.example_function() # ERROR -> can´t use function that uses XSCRIPTCONTEXT in my_module

Maybe I misunderstood you? or did you mean this?
Thank you!

When you call macro code (anything callable from menu:Tools>Macros… and any event dialog), XSCRIPTCONTEXT is already loaded.

Only for the called module. But if you call another module from this one, this is what I get:
(<class 'NameError'>: name 'XSCRIPTCONTEXT' is not defined

Well, then pass it over or use uno.getComponentContext()

Well, the reason I created this thread was to know If there was a better option, so I could avoid passing and writing this in every used module:

if __name__ != 'ooo_script_framework':
    if 'XSCRIPTCONTEXT' in sys.modules:
        XSCRIPTCONTEXT = sys.modules.get('XSCRIPTCONTEXT')

or this:

if __name__ != 'ooo_script_framework':
    XSCRIPTCONTEXT = None

def set_context(context):
    global XSCRIPTCONTEXT
    XSCRIPTCONTEXT = contexto

Writing this in every module is something I would like to avoid.

Did you try

globals()['XSCRIPTCONTEXT']

This time a KeyError:
<class 'KeyError'>: 'XSCRIPTCONTEXT'
So not working.