Importing and using class from .py into a custom scripted module

Hello,

I am using Slicer 4.11.0 on a Windows 10 computer and developing a Python scripted module.

I want to import a class (TripleMRNet from TripleMRNet.py) from my scripted module, so that I can use it in the module. This TripleMRNet.py is in the same directory as the scripted module.

I have tried to import the class directly in the Python Console and it runs well:

However, when I tried to use it in my scripted module I get the following error:
AttributeError: Can’t get attribute ‘TripleMRNet’ on <module ‘main’ (built-in)>

load_fromScriptedModule

Any help is appreciated.

Thanks in advance

Slicer expects all .py files in a scripted module folder to be Slicer module, so you need to put all additional files into regular Python packages in subfolders. See Extension wizard module and its ExtensionWizardLib package as an example.

The only complication is that you need to implement dynamic reloading of custom packages, if you want to reload your module without restarting Slicer. See this post for details: Python scripted module development reload feature for multiple files - #4 by lassoan

Thank you so much, now it works perfectly.

1 Like