QGIS Error while executing Python function in openProject() Macro: "QgsMapLayerRegistry is not defined"

To fix the error:

NameError: global name 'QgsMapLayerRegistry' is not defined

Just add the following at the top of your script:

from qgis.core import QgsMapLayerRegistry

Tip:

What I do normally when I receive similar errors is to type the class into the Python Console. It will then provide you with a list of classes and libraries in which they belong to:

Typing in class

Or you can just type it in the console and press 'Enter':

Class

In both cases, we can see that we need to call qgis.core in order to import the QgsMapLayerRegistry class.


Within QGIS 3.0 and above updates took place within the API, QgsMapLayerRegistry has been removed and its functionality has been moved to QgsProject.

As a beginner, I found it confusing because they didn't make an update for the Developer Cookbook pdf version. This has also been answered in Is QgsMapLayerRegistry removed in QGIS3?