0

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?

3
  • 1
    Could you create a minimal reproducible example for this, rather than two disembodied lines, and give the full traceback? Commented Nov 10, 2015 at 16:46
  • it looks like the new method is trying to implement some sort of singleton - however, if that really is the total of the new method it's not doing it very well. As @jonrsharpe says - a proper example is needed for this: Commented Nov 10, 2015 at 17:04
  • See method 3 for creating a singleton, and a possible duplicate: stackoverflow.com/q/17237857/3001761 Commented Nov 10, 2015 at 17:13

1 Answer 1

1

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):
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.