Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: NameError: 'self' is not defined

I must be doing something stupid. I'm running this in Google App Engine:

class MainHandler(webapp.RequestHandler):

    def render(self, template_name, template_data):
        path = os.path.join(os.path.dirname(__file__), 'static/templates/%s.html' % template_name)
        self.response.out.write(template.render(path, template_data)) # error here

    def get(self):
        self.response.out.write("hi")

def main():
    application = webapp.WSGIApplication([('/', MainHandler)],
                                        debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()

This gives an error:

Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3192, in _HandleRequest
    self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3135, in _Dispatch
    base_env_dict=env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 516, in Dispatch
    base_env_dict=base_env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2394, in Dispatch
    self._module_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2304, in ExecuteCGI
    reset_modules = exec_script(handler_path, cgi_path, hook)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2200, in ExecuteOrImportScript
    exec module_code in script_module.__dict__
  File "main.py", line 22, in <module>
    class MainHandler(webapp.RequestHandler):
  File "main.py", line 38, in MainHandler
    self.writeOut(template.render(path, template_data))
NameError: name 'self' is not defined

What am I doing wrong?

like image 397
Nick Heiner Avatar asked Jun 03 '10 06:06

Nick Heiner


2 Answers

The exception is happening while the class is being defined, which means that your indentation is off. Tabs in Python are equivalent to 8 spaces, so if all the preceding lines are using tabs and your tabstop is set to 4 spaces then the indentation only looks correct.

like image 60
Ignacio Vazquez-Abrams Avatar answered Sep 27 '22 23:09

Ignacio Vazquez-Abrams


Just in case someone happens upon this and is looking for a solution not having to do with indentation, this is a good reference for how / when to use self.

NameError: name 'self' is not defined

like image 20
nihiser Avatar answered Sep 27 '22 23:09

nihiser