Import Python modules best practice

Hello everyone!

I’m following some guides about how to import modules in Python and I was wondering about something:

Is it possible to import a module once and make it available to all the Text DAT inside a project?
I am asking this because I am willing to use some functions from an external library inside a CHOPExecute and I was asking myself where should I put the “import” statement (inside the CHOPExecute or not?).
It works but, in such a scenario, wouldn’t I be importing the module everytime a CHOP changes a value?
Thanks!

Simply put the import-statement on top of the executeDat.
The module will only be imported once. After the first time, every other DAT or module will refference the first imported. The import module looks in to sys.modules for imports. If it is not imported already, it will load the module, put it in there, and return it.
This also means that if you change something in an imported module, this change will translate to all other instanced refferencing it.

Also, every dat is also simply a module. Refferencing a DAT from several points results in changes being translated to all refferencees.

1 Like

That’s great! It works, thanks!
Here my specific scenario:

# Execute - execute1
from music21 import *

def onStart():
    ...
    return 
# midiin1_callbacks
from execute1 import * 

def onReceiveMIDI(...):
    print(note.Note("F5")) # note is part of music21
    return

It works only if I explicitly from execute1 import *. If I use import execute1 it doesn’t.
You said:

should I actually return something from onStart() or from execute1 itself? and if yes how do I return * from a module?

Thank you very very much

No need for the onStart. Simply put import music21 in your midiinDAT

this was exactly my point

In such a scenario wouldn’t I be importing music21 everytime a MIDI message is received?

No. The TextDAT gets only “compiled” once as a module. If you would put it inside the function, then yes, it would import it every time.

The TextDAT gets only “compiled” once as a module.

Of Course! Sure, it make totally sense. Thank you very much.