1
$\begingroup$

I have several operators that import different file types like this example:

import bpy

class IMPORT_OT_xxx_file_type(bpy.types.Operator):
    bl_idname = "import.my_xxx_file_importer"
    bl_label = "xxx file (.xxx)"
    bl_description = "Import xxx file format (.xxx)"

    filename_ext: str = ".xxx"

    filter_glob: bpy.props.StringProperty(
        default="*.xxx",
        options={'HIDDEN'},
        maxlen=255,
    ) # type: ignore

As I progress in developing my addon, I've reached a stage where I need to verify if an operator is registered before displaying it in my panel. This is because I've implemented functionality in the preferences to enable or disable certain options, affecting what gets shown in the panel. I've found only this method to check if an operator is already registered but that requires me to use an ugly eval function:

def is_class_registered(self, cls: bpy.types.Operator) -> bool:
    idname: str = eval(f"bpy.ops.{cls.bl_idname}.idname()")
    return hasattr(bpy.types, idname)

def draw(self, _: bpy_types.Context) -> None:
    for cls in CLASSES:
        if is_class_registered(cls):
            self.layout.operator(cls.bl_idname, text=cls.bl_label)

But I stumbled upon this problem where bpy.ops.import is invalid syntax so is_class_registered will fail because it's accessing bpy.ops.import which I tested and verified in the Python console:

>>> bpy.ops.import
  File "<blender_console>", line 1
    bpy.ops.import
            ^
SyntaxError: invalid syntax

But bpy.ops.export works fine

>>> bpy.ops.export
<module 'bpy.ops.export'>

So I thought that everything that was related to importing objects should be under the import category (i.e. import.my_importer_operator) and everything related to exporting be under export. The operators work perfectly, it's just that script fails when I need to use the name strings in a way so that I can check if the operator is registered. How can I resolve this issue? I would prefer not changing the category from import to something else. Or am I categorizing these types of operators incorrectly? Or perhaps another way to check if the operator is registered?

$\endgroup$

1 Answer 1

0
$\begingroup$

I found a way from this thread on how to properly check if an operator has been registered:

def is_class_registered(cls) -> bool:
    idname_py = cls.bl_idname
    module, op = idname_py.split(".")
    idname = module.upper() + "_" + "OT" + "_" + op
    return hasattr(bpy.types, idname)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .