How to get board object using KiCAD pcbnew plugin Python API

When using KiCAD’s Python API for pcbnew, you can simply get a board object using pcbnew.GetBoard():

board: pcbnew.BOARD = pcbnew.GetBoard()

The : pcbnew.BOARD is optional but will tell your editor (such as visual studio code) which object to expect for better autocompletion.

Complete plugin example:

#!/usr/bin/env python
import pcbnew
import os

class SimplePlugin(pcbnew.ActionPlugin):
    def defaults(self):
        self.name = "Plugin Name as shown in Pcbnew: Tools->External Plugins"
        self.category = "A descriptive category name"
        self.description = "A description of the plugin and what it does"
        self.show_toolbar_button = False # Optional, defaults to False
        self.icon_file_name = os.path.join(os.path.dirname(__file__), 'simple_plugin.png') # Optional, defaults to ""

    def Run(self):
        board: pcbnew.BOARD = pcbnew.GetBoard()
        # TODO Do something useful with [board]
        print(board)

SimplePlugin().register() # Instantiate and register to Pcbnew