Python - Trouble when changing context (the first time) In the following script I am trying to create a material on the active object, then change the context to the shader node editor and then delete the existing default node setup:

import bpy

mat = bpy.data.materials.get("Material")
geom = bpy.context.active_object

if mat is None:
    # create material
    mat = bpy.data.materials.new(name="Material")
# Assign it to object
if geom.data.materials:
    # assign to 1st material slot
    geom.data.materials[0] = mat
else:
    # no slots
    geom.data.materials.append(mat)

bpy.context.area.type = 'NODE_EDITOR'
bpy.ops.node.select_all(action='TOGGLE')
bpy.ops.node.delete()


When I first run this script (from the text editor) on my scene I get the following:

RuntimeError: Operator bpy.ops.node.select_all.poll() failed, context is incorrect


Although, curiously, when I run it a second time (again from the text editor), the context is successfully changed to the shader node editor but no nodes are deleted.

And finally, when I run it a third time, it successfully deletes the existing nodes in the shader node editor.

Why does this script apparently work better each time it is run?

(I am using Blender 2.8)
To delete the nodes you should override the context of operator bpy.ops.node.select_all. 
And the reason of error you see is mentioned here.

Actually to delete the nodes, instead of using operator I would use next piece of code:

for node in mat.node_tree.nodes:
    mat.node_tree.nodes.remove(node)

updated with your part:

import bpy

mat = bpy.data.materials.get("Material")
geom = bpy.context.active_object

if mat is None:
    # create material
    mat = bpy.data.materials.new(name="Material")
# Assign it to object
if geom.data.materials:
    # assign to 1st material slot
    geom.data.materials[0] = mat
else:
    # no slots
    geom.data.materials.append(mat)

# delete nodes
for node in mat.node_tree.nodes:
    mat.node_tree.nodes.remove(node)