# Strange shading after running python script

I've written a pretty complicated script which chops up, joins and transforms parts of 1 giant 'world' mesh for better handling in a game engine.

It all works as I'd expect, except for one thing...

Some operations cause strange dark shading to appear on parts of the mesh:

But when I go into edit mode... they disappear! Very odd. There are other examples of weird shading after running my script, which also disappear upon entering edit mode. If I export the mesh before entering edit mode, the problematic shading is exported as is.

Unfortunately, this method of toggling in and out of editmode just doesn't work for my purpose. The script mentioned above runs a secondary instance of blender in background mode, and for some reason this solution doesn't work when blender is running in background mode.

I've tried calling Mesh.update, Mesh.calc_normals, Mesh.validate, Scene.update, or regenerating the mesh with a bmesh. Nothing makes the slightest bit of difference.

Any ideas how to fix this besides the editmode toggle trick (which unfortunately doesn't work in my particular setup)

Here's a copy so you can see for yourself.

bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.02)