2

I am using Python 2.7.2+, and when trying to see if a dictionary holds a given string value (named func) I get this exception:

Traceback (most recent call last):
  File "Translator.py", line 125, in <module>
    elif type == Parser.C_ARITHMETIC : parseFunc()
  File "Translator.py", line 95, in parseFunc
    if unary.has_key(func) : 
AttributeError: 'function' object has no attribute 'has_key'

This is where I define the dictionaries:

binary = {"add":'+', "sub":'-', "and":'&', "or":'|'}
relational = {"eq":"JEQ" , "lt":"JLT", "gt":"JGT"}
unary = {"neg":'-'}

Here's the function where the exception is raised:

def parseFunc():
    func = parser.arg1 
    print func  
    output.write("//pop to var1" + endLine)
    pop(var1)
    if unary.has_key(func) : // LINE 95
        unary()
        return
    output.write("//pop to var2" + endLine)
    pop(var2)
    result = "//"+func + endLine
    result += "@" + var1 + endLine
    result += "D=M" + endLine
    result += "@" + var2 + endLine
    output.write(result)
    if binary.has_key(func) : 
        binary()
    else : relational()

Also, I tried changing if unary.has_key(func) to if func in unary but then I got

Traceback (most recent call last):
  File "Translator.py", line 126, in <module>
    elif type == Parser.C_ARITHMETIC : parseFunc()
  File "Translator.py", line 95, in parseFunc
    if func in unary:
TypeError: argument of type 'function' is not iterable

P.s I tired it also using python 3.2

Any ideas? Thanks

2 Answers 2

5

In Python 3, dict.has_key() is gone (and it has been deprecated for quite some time). Use x in my_dict instead.

Your problem is a different one, though. While your definition shows unary should be a dictionary, the traceback shows it actually is a function. So somewhere in the code you did not show, unary is redefined.

And even if unary was a dictionary, you would not be able to call it.

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

2 Comments

even if python 2.7.2+ is ambiguous - I don't think the issue lies in your first part of the answer, though it's correct.
@luke14free: Did you read the penultimate line of the original post?
1

It seems from your trace that you override the value of unary with a function (do you have any function called "unary"?). Therefore you are trying to call "has_key" method on a function that obviously has no such method. Pay attention with variable names, variable x will override def x() if it's placed after it in your code, and vice versa.

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.