Python Type is not defined

时间:2017-10-12 09:50:13

标签: python-3.x antlr4

I want to do the semantic checking for a language and i use ANTLR4 to generate parser and visitor class. However i met a problem. If i use this method print(type(newList[0].expression()))
I will get a type like this <class 'IDILParser.IDILParser.IdenetExpressionContext'>
However, if i run the code below, i will get a error like this NameError: name 'IDILParser' is not defined
Can i ask how to fix this problem? Thanks!

from antlr4 import *
if __name__ is not None and "." in __name__:    
    from .IDILParser import IDILParser
else:
    from IDILParser import IDILParser

class IDILVisitor(ParseTreeVisitor):
    def visitAssign(self, ctx:IDILParser.AssignContext):
        if type(newList[0].expression()) is IDILParser.IDILParser.IdenetExpressionContext:
        ...

1 个答案:

答案 0 :(得分:0)

You did from IDILParser import IDILParser, which means the IDILParser in your code already acutally refers to IDILParser.IDILParser.

So try taking away that one layer:

if type(newList[0].expression()) is IDILParser.IdenetExpressionContext:
    ...

Btw, when in doubt if your code is being run as a module or as a script (aka relative imports do work or not), you could also do the following:

try:
    from .IDILParser import IDILParser
except ImportError:
    from IDILParser import IDILParser