Skip to content Skip to sidebar Skip to footer

Getter Setter As Function In Python Class Giving "no Attribute Found" Error

import operator import re from ply import lex, yacc class Lexer(object): tokens = [ 'COMMA', 'TILDE', 'PARAM', 'LP', 'RP', 'FU

Solution 1:

In your constructor (__init__) for the Parser object, you ask Ply to generate a parser before the Parser object is fully constructed:

def__init__(self, **kwargs):
    self.parser = yacc.yacc(module=self, **kwargs)
    # This is the critical line:
    self._dict_obj = None

In order to construct a parser from the object (yacc.yacc(module=self)), Ply needs to iterate over all the object's attributes. For example, it needs to find all the parser functions in order to extract their docstrings in order to determine the grammar.

Ply uses the dir built-in function to make a dictionary of all the object's attributes. Because your Parser object has a custom attribute dict_obj, that key is returned from dir and so Ply tries to cache that attribute with its value. But when it calls gettattr(module, 'dict_obj'), the getter is called, and the getter tries to return self._dict_obj. However, self._dict_obj has not yet been defined, so that ends up throwing an error:

AttributeError: 'Parser'object has no attribute '_dict_obj'

Note that this is not the error message you reported in your question; that error says that there is no attribute dict_obj. Perhaps that was a copy-and-paste error.

If you move the call to yacc.yacc to the end of the initialiser, that particular problem goes away:

def__init__(self, **kwargs):
    self.lexer = None
    self._dict_obj = None
    self.error = ""
    self.result = ""
    self.parser = yacc.yacc(module=self, **kwargs)

However, there are a number of other problems in the code excerpt which make it difficult to verify this solution. These include:

  1. There is no LexerNmsysSearch. I assumed you meant Lexer.

  2. There is no node_expression. I have no idea what that is supposed to be so I just removed the test.

  3. Your grammar does not match the input you are testing, so the parser immediately throws a syntax error. I changed the input to "(~hello)" in an attempt to produce something parseable.

  4. The parser actions do not set semantic values, so self.parse.parse() doesn't return any value. This causes get_result to throw an error.

At that point, I gave up on trying to produce anything sensible out of the code. For future reference, please ensure that error messages are quoted exactly and that sample code included in the question can be run.

Post a Comment for "Getter Setter As Function In Python Class Giving "no Attribute Found" Error"