Search code examples
pythoninitnameerror

NameError: name is not defined in python init function


class HumidityServer(CoAP):
    def __init__(self, host, port, noOfSensors=10, multicast=False):
        CoAP.__init__(self, (host, port), multicast)

        for num in range(noOfSensors):
            self.add_resource('humidity'+num+'/', HumidityResource(num))

This excerpt is part of a program that generates:

Traceback (most recent call last):
  File "humidityserver.py", line 10, in <module>
    class HumidityServer(CoAP):
  File "humidityserver.py", line 14, in HumidityServer
    for num in range(noOfSensors):
NameError: name 'noOfSensors' is not defined

Why does this happen even though I've defined a default value for the variable?


Solution

  • You are mixing tabs and spaces in your code; this is your original code as pasted into the question:

    enter image description here

    The solid grey lines are tabs, the dots are spaces.

    Note how the for loop is indented to 8 spaces, buth def __init__ is indented by one tab? Python expands tabs to eight spaces, not four, so to Python your code looks like this instead:

    source code at 8 spaces per tab

    Now you can see that the for loop is outside the __init__ method, and the noOfSensors variable from the __init__ function signature is not defined there.

    Don't mix tabs and spaces in indentation, stick to just tabs or just spaces. The PEP 8 Python style guide strongly advises you to use only spaces for indentation. Your editor can easily be configured to insert spaces whenever you use the TAB key, for example.