简体   繁体   中英

Dictionary mapping not working python

I am writing a lexer for my compiler.There is a function to map appropriate values when we input a token.But getting the error:

[pylint] E0001:invalid syntax (, line 28)

Lexer.py

class Token(object):
    ILLEGAL_TOKEN = -1
    TOKEN_PLUS = 1
    TOKEN_MULT = 2
    TOKEN_DIV = 3
    TOKEN_SUB = 4
    TOKEN_OPEN_PAREN = 5
    TOKEN_CLOSE_PAREN = 6
    TOKEN_DOUBLE = 7
    TOKEN_NULL = 8

class Lexer(object):
    @classmethod
    def __init__(self, Expression):
        self.IExpression = Expression
        self.length = len(Expression)
        self.index = 0
        self.number = None
    @staticmethod
    def get_token(self):
        token = Token.ILLEGAL_TOKEN
        while self.index < self.length and (self.IExpression[self.index] == '' or self.IExpression[self.index] == '\t'):
            self.index += 1
        if self.index == self.length:
            return Token.TOKEN_NULL
        t = self.IExpression[self.index]

        switchCase = {
            '+' : token = Token.TOKEN_PLUS, self.index += 1,
            '-' : token = Token.TOKEN_SUB, self.index += 1,
            '*' : token = Token.TOKEN_MULT, self.index += 1,
            '/' : token = Token.TOKEN_DIV, self.index += 1,
            '(' : token = Token.TOKEN_OPEN_PAREN, self.index += 1,
            ')' : token = Token.TOKEN_CLOSE_PAREN, self.index += 1
        }
        return switchCase.get(t)

The value of a dictionary entry, like any value, has to be an expression which evaluates to a result (and the creators of Python made sure that you cannot assign and return a value at the same time). So assignment statements don't qualify.

You could put a function (like a lambda or like in this Q&A: Python switch case ) as value and call it when you get it, but in your case there's a better & simpler equivalent solution:

    switchCase = {
        '+' : Token.TOKEN_PLUS,
        '-' : Token.TOKEN_SUB,
        ...
    }
    token = switchCase.get(t)
    if token is not None:
       self.index += 1
    return token

So if the token is in the dict, you get your enumerate value and you can increase your index there (since you do it in all "cases" anyway)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM