Sharing python code between (scripted loadable) modules


I’m trying to add some functionality to Slicer, and I want to make a couple of separate modules which will use the same underlying libraries. It’s not clear to me if there’s a nice way to do this without explicit sys.path manipulation.

I’ve seen Importing custom python module into scripted extension and Python scripted module code organization which seem to imply that code to be imported into a module needs to sit in a sub-folder in the module, but that is not suitable for sharing code between modules; and I’ve seen Specifying dependencies of a custom extension in the .s4ext file - #2 by jamesobutler which seems to imply that modules can depend on other modules to provide importables, but the example module there does not seem to import anything from its named dependencies…

Am I missing anything?

My hope is to be able to include both the separate modules, and their common infrastructure, in a single extension, but that is not a hard requirement.


If one module provides a set of libraries it should be available to other modules that are loaded in the same Slicer session (e.g. import the Logic class from another module). You should never need to duplicate code or manipulate any python path variables manually.

1 Like

I should chime-in since you referenced a topic I posted previously. In my case I have a custom library that was shared by two separate applications - a TCP/IP socket class. Let’s call it
to use in a slicer scripted module I had to setup the directory structure as so

 | -
 | - subdirectory
      | -
      | - contains

from .sock import *

And imports as so

from subdirectory import sock

If you need to access another slicer module this is a clean way of doing so Setting widget variable from --python-code on Slicer.exe start - #13 by talmazov

I hope this helps

~ Georgi

1 Like