Pcbnew python, problem creating a new net

I’m trying to create a net in pcbnew, unrelated to eeschema.

This code sometimes results in bizarre net numbers (noncontiguous or negative). After executing with a variety of net names, sometimes board.FindNet(netname).GetNet() will crash the program (4.0.7 stable, Windows 7)

def NEWNET(netname):
    """Create a new net with name netname."""

    board = pcbnew.GetBoard() 

    # First create a new NETINFO_ITEM instance.
    netinfo = pcbnew.NETINFO_ITEM(board, netname)

    # Add this net to 'board', this will assign a 'net code' to your net.
    board.AppendNet(netinfo)

    # return the net code
    return netinfo.GetNet()