ABC
ABC

Reputation: 665

How to add a dictionary attribute to python class object?

I have a bit of code I'm working with (specifically Parsetron) which was written for Python 2.7 which I'm trying to run using python 3.4 and unsurprisingly it's throwing errors.

The error I'm specifically looking at is this:

def __new__(cls):
    return cls.__dict__['_grammar_']

KeyError: '_grammar_'

cls is class object, which indeed does not have the key "_grammar_". My question is of course, how to get rid of this error and why it appears. In python 2.7, does __dict__ add a key value to the class object whereas Python 3.x doesn't? Running through the thread during debugging it doesn't seem to add this value anywhere. Anyone know what's going on?

Upvotes: 0

Views: 140

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122036

Looking at the code, you can see that the Grammar._grammar_ class attribute is actually set by the metaclass:

dct["_grammar_"] = GrammarImpl(name, dct)

However, Grammar uses the 2.x syntax for setting a metaclass:

__metaclass__ = MetaGrammar

To adapt this for Python 3.x, use the new syntax:

class Grammar(metaclass=MetaGrammar):

Upvotes: 1

Related Questions