Skip to content

Commit e647403

Browse files
authored
Python: Avoid __main__.py files as entry points.
According to the official documentation, the purpose of `__main__.py` files is that their presence in a package (say, `foo`) means one can execute the package directly using `python -m foo` (which will run the aforementioned `foo/__main__.py` file). In principle this means that adding `if __name__ == "__main__"` in these files is superfluous, as they are only intended to be executed (and not imported by some other file). However, in practice people often _do_ include the above construct. Here are some instances of this on LGTM.com: https://lgtm.com/query/7521266095072095777/ In particular, 10 out of 33 files in `cpython` have this construct. This causes some confusion in our module naming, as we usually see the presence of `__name__ == "__main__"` as an indication that a file may be run directly (and hence with "absolute import" semantics). However, when run with `python -m`, the interpreter uses the usual package semantics, and this leads to modules getting multiple names. For this reason, I think it makes sense to simply exclude `__main__.py` files from consideration. Note that if there is a `#!` line mentioning the Python interpreter, then they will still be included as entry points.
1 parent 847faf5 commit e647403

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

python/ql/src/semmle/python/Files.qll

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,10 @@ class File extends Container {
8989
i.getTest().(Compare).compares(name, op, main) and
9090
name.getId() = "__name__" and
9191
main.getText() = "__main__"
92-
)
92+
) and
93+
// Exclude files named `__main__.py`. These are often _not_ meant to be run directly, but
94+
// contain this construct anyway.
95+
not this.getShortName() = "__main__.py"
9396
or
9497
// The file contains a `#!` line referencing the python interpreter
9598
exists(Comment c |

0 commit comments

Comments
 (0)