0

Why I am getting the error that is given below:

lhs_production = self.lhs()  

NameError: global name 'self' is not defined

Below is the code that I have written:

class Grammar:
   def lhs(self):
      arrow_position = line.find('->')
      if arrow_position == -1:
         raise ValueError, 'No arrow position %s is found in %s' % (arrow_position, self.line)

      lhs_g = self.line[0:arrow_position].strip(' ')
      print "The Lhs for the line is: ", lhs_g

      check_space = re.search("\s", lhs, re.M)
      if check_space:
         raise ValueError, 'There is still some space in the lhs of the line'

      return self.lhs_g



def parse_line(line):
   if len(line) == 0:
      raise ValueError, 'No Line is found %s' % (line)
   lhs_production = self.lhs()
   rhs_predicates_production = rhs_predicates()
   pattern_list_production = pattern_list()
   return(lhs_production, rhs_predicates(), patterns())

3 Answers 3

2

Because self is not defined in the scope of that function :). Your indentation is off, you probably meant to make that a method (so indent all the lines) and then to add self as an argument, in which case the instance would take on the name self.

A few other things to look out for too, just by the by:

  • You should use if "->" in line: rather than .find() and checking if it's -1. For this, your first function seems to have a NameError, since line is not defined on its first line, not sure what you meant instead.

  • You should instantiate the exceptions, rather than making raise do it for you (so, raise ValueError("some stuff")

  • You can use if not line to check if it's a blank line.

  • return is a statement, not a function, so writing it like that is a bit confusing. Just use return lhs_production, bla, bla or put parens around that as long as there's a space there if you prefer.

Cheers :).

Sign up to request clarification or add additional context in comments.

Comments

0

self is not a global variable. It is passed in to class methods. The parse_line function is a global scope function, not a class method. Therefore, self does not exist in the scope of that function.

Any method that uses self needs to take self in as a parameter.

Comments

0

There is no self in that context, unless your indentation is wrong. You need to reference an instance of the object to call a method when outside of the object's scope. self is really just a label anyway; it only has special meaning by convention. You need a grammar=Grammar() somewhere in there.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.