Avoiding duplicate vertices and edges

In my addon I’d like avoid duplicate vertices and edges.
Here is how I see it.

Suppose we need a vertex with coordinates x,y,z
We check if there is already a vertex with coordinates x,y,z with dictance tolerance d, where d is a small value (e.g. 0.00001)
If that vertex already exists, we simply take it and use it
Otherwise create a new vertex with coordinates x,y,z

Is there already existing code to solve that problem?
How would you implement it otherwise?

Bmesh module doesn’t create geometry elements if they already exist, not sure if there is a certain tolerance.

You can use a KDTree to find nearby vertices:
http://www.blender.org/documentation/blender_python_api_2_71_release/mathutils.kdtree.html
But it’s rather slow on heavy meshes

Can’t you run remove doubles afterwards?

The alternative would be to call bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0001) each time I need to ensure uniqueness of each vertex. So I’ll have to check if it’s faster than dealing with KDTree.

Strange. I use Bmesh only to generate a mesh and duplicate verts and edges are really produced

Do I need to call KDTree.balance after each KDTree.insert AND before any of the find methods?

You’re right, there seems to be no protection for vertices in bmesh module, there is however for edges:
ValueError: edges.new(): this edge exists

Do I need to call KDTree.balance after each KDTree.insert AND before any of the find methods?

You should bulk-insert coordinates, balance once, then use find as often as necessary. Anything else will spoil performance (like insert, balance, insert, balance, …)