Reputation: 19
def toktok(self) -> object:
tokens = []
while self.current is not None:
if self.current == " ":
self.next()
elif self.current == '=':
tokens.append(Token(TT_equal))
print("C1:", tokens[0], self.current, "C2")
self.next()
elif self.current == '+':
tokens.append(Token(self.current))
self.Methods()
elif self.current == '-':
tokens.append(Token(TT_subtraction))
self.Methods()
elif self.current == '*':
tokens.append(Token(TT_multiplication))
self.Methods()
elif self.current == '/':
tokens.append(Token(TT_division))
self.Methods()
elif self.current == '(':
tokens.append(Token(TT_parenthesis_left))
self.Methods()
elif self.current == ')':
tokens.append(Token(TT_parenthesis_right))
self.next()
elif self.current in TT_identifier:
tokens.append(Token(self.current))
self.next()
elif self.current in TT_numbers:
tokens.append(self.digitm())
else:
char = self.current
self.next()
print("Not found: ", char)
return tokens
is there any way I can shorten this or make it cleaner looking? I think it looks funky so if there is a way to shorten that would be greatly appreciated!
Upvotes: 0
Views: 39
Reputation: 16081
You can use dictionary
to avoid the chain if-else conditions.
def toktok(self) -> object:
tokens = []
mapping = {
'+': Token(TT_addition),
'-': Token(TT_subtraction),
'*': Token(TT_multiplication),
'/': Token(TT_division),
'(': Token(TT_parenthesis_left),
}
mapping_2 = {
'=': Token(TT_equal),
')': Token(TT_parenthesis_right)
}
while self.current is not None:
if self.current == " ":
self.next()
elif self.current in mapping:
tokens.append(mapping.get(self.current))
self.Methods()
elif self.current in mapping_2:
tokens.append(mapping_2.get(self.current))
self.next()
elif self.current in TT_identifier:
tokens.append(Token(self.current))
self.next()
elif self.current in TT_numbers:
tokens.append(self.digitm())
else:
char = self.current
self.next()
print("Not found: ", char)
return tokens
Upvotes: 1