简体   繁体   中英

Why is my variable not defined even if I used “global”?

I'm trying to do a COOL compiler in Python, but by the time that I try to set a global variable it says "NameError: name 'comm_reg' is not defined". I'm defining the variable in the beginning, and then I use it as global so I don't understand why it's not working.

Any ideas? Thank you.

class CoolLexer(Lexer):

    comm_reg = False
    comm_line = False

    @_(r'[(][\*]')
    def COMMENT(self, t):
        global comm_reg
        comm_reg = True

    @_(r'[*][)]')
    def CLOSE_COMMENT(self, t):
        global comm_reg
        if comm_reg:
            comm_reg = False
        else:
            return t

    @_(r'[-][-].*')
    def ONE_LINE_COMMENT(self, t):
        global comm_line
        comm_line = True

    def salida(self, texto):
        list_strings = []
        for token in lexer.tokenize(texto):
            global comm_line
            global comm_reg
            if comm_reg:
                continue
            elif comm_line:
                comm_line = False
                continue
            result = f'#{token.lineno} {token.type} '

It looks like you want something like this:

class CoolLexer(Lexer):

    def __init__(self):
        self.comm_reg = False
        self.comm_line = False

    @_(r'[(][\*]')
    def COMMENT(self, t):
        self.comm_reg = True

    @_(r'[*][)]')
    def CLOSE_COMMENT(self, t):
        if self.comm_reg:
            self.comm_reg = False
        else:
            return t

    @_(r'[-][-].*')
    def ONE_LINE_COMMENT(self, t):
        self.comm_line = True

    def salida(self, texto):
        list_strings = []
        for token in self.tokenize(texto):
            if self.comm_reg:
                continue
            elif self.comm_line:
                self.comm_line = False
                continue
            result = f'#{token.lineno} {token.type} '

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