Search code examples
pythonantlr4

Confusion regarding Relative Import in ANTLR


I came across this line of code, if __name__ is not None and "." in __name__: which is included in some auto-generated files in ANTLR such as ExprParser.py

# Generated from Expr.g by ANTLR 4.7.2
from antlr4 import *
if __name__ is not None and "." in __name__:
    from .ExprParser import ExprParser
else:
    from ExprParser import ExprParser

From what I have heard __name__ is automatically set by python, so how can it be None and also __name__ can only consists of module name or string "__main__" so how could it contain dot (.). So, isn't this line of code unnecessary or I am missing something?


Solution

  • how can it be None

    To the best of my knowledge, there's no way it could end up None under normal circumstances (i.e. outside of the programmer messing with __name__'s value), so that check indeed seems redundant.

    can only consists of module name or string "__main__" so how could it contain dot (.)

    The names of nested modules contain dots, so it's checking whether it's a nested module.