Clearing custom normals not working as expected in add-on

I have a button in an add-on that is supposed to loop through your selected objects and clear custom split normals data, among other common mesh cleanup tasks. This code works perfectly fine in a standard Python script:

import bpy

selection = bpy.context.selected_objects
  
for ob in selection:
    if ob.type == 'MESH':
        bpy.context.view_layer.objects.active = ob
        bpy.ops.mesh.customdata_custom_splitnormals_clear()

But the same code does not work in the context of the add-on.

class ClearCustomNormalsOperator(bpy.types.Operator):
    bl_idname = "mesh_cleanup.test"
    bl_label = "Clear Custom Normals"
    
    def execute(self, context):
        selection = context.selected_objects
        
        for ob in selection:
            if ob.type == 'MESH':
                context.view_layer.objects.active = ob
                bpy.ops.mesh.customdata_custom_splitnormals_clear()
                
        return {'FINISHED'}

Pressing this button in the add-on only clears split normals data for the last active object it loops through (whatever the last object you selected basically). Is there something obvious I’m missing here, or are mesh operators treated differently within the context of add-ons?

I’m running into this same issue. Not sure why a similar script I’m using doesn’t work as an addon. Did you ever find a solution for this?

Sorry for the late reply! Honestly, I don’t think I did. If you end up finding one, please send it my way :wink:

When a script is executed in the text editor, all modules are already loaded. But addons are registered with the initialization. For example, the context is not available at this moment.

To register a script as an addon it needs information in a block called bl_info = {…} at the beginning of your code:

bl_info = {
    "name": "myaddon",              # required
    "blender": (2, 91, 1),          # required
    "category": "Object",
    "description": "just a test",
    "author": "no name",
    "version": (0, 0, 1),
    "location": "View3D > Sidebar",
    "warning": "",
    "wiki_url":  "",
    "tracker_url": "",
}

import bpy
from bpy.props import (StringProperty,
                       BoolProperty,
                       BoolVectorProperty,
... # and so on

These elements are displayed in Preferences. See Add-on Tutorial for more.

When done, maybe easiest way is to save complete code in a Text-File (.txt, text/plain) on your drive. Then rename the extension to .py

That´s it. Install this addon as usual in Peferences. File was placed to blender_user_resources. The path is shown in Preferences → Add-ons → expand[anyAddon] → File

Sorry mate, but you’re missing the point here. This is specifically about the custom normals operator not working within the addon. The addon itself works perfectly fine otherwise. It seems to be more of a Blender bug than anything.