Here is my class

class aClassName():
    def __init__(self):
        #do something...


        #do something

The class calls a number of methods from iface such as setActiveLayer, .mapCanvas().zoomToSelected() etc in different functions. It runs properly when it is called in the same file.

But when I tried to use the class by importing it into another file:

from theClassFile import aClassName

The error message showed up and said :

NameError: name 'iface' is not defined

even if adding from qgis.utils import iface to theClassFile with reference from here.

I just began to use PyQGIS last month.

Here is my QGIS version: enter image description here

  • Add from qgis.utils import iface to the import section of the file which contains class aClassName Dec 30, 2019 at 10:47

1 Answer 1


I tried in Python console, the following code works.

The content of the file theClassFile.py :

class aClassName():  
    def __init__(self):

        # Replace the name of your layer
        print('OK !')

The contents of the main script :

from qgis.utils import iface
from qgis.core import *

import sys 
# Path of theClassFile.py directory

from theClassFile import aClassName


I have two layers in my QGIS project. With this code, I change the active layer and I print a message. There are many bugs, if you modify theClassFile.py, QGIS will not take the changes into account. To solve this problem, sometimes think about restarting your QGIS.

Try this code and get back to me.

  • I tried the code by adding data=None at __init__ and . before the imported file. It shows ModuleNotFoundError: No module named '__console__' pointing to the first line of the main script.
    – Pete
    Dec 30, 2019 at 9:22
  • Maybe I made a mistake. Are you working in the Python console editor or are you in a plugin? Dec 30, 2019 at 9:25
  • I'm working in Python console in QGIS
    – Pete
    Dec 30, 2019 at 9:27
  • Sorry, my code is an exemple of plugin code. Dec 30, 2019 at 9:46
  • I edited my code. Dec 30, 2019 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.