Possible values of python __name__ in different situations¶
In python, __name__ is a special variable that stores the name of a python module. The problem is, what exactly is the name of a module?
In different situations, the name is different.
When you run a file directly¶
For exmaple, you run a python file like this:
python /path/to/foo.py
Then, __name__ in foo.py is __main__.
When a file is imported¶
When a file is imported, value of __name__ in the imported file depneds on how you import the file.
| imported file | import statement | value of __name__ |
|---|---|---|
| foo.py | import foo | foo |
| foo/bar.py | from foo import bar | foo.bar |
| foo/bar/baz | import foo.bar.baz | foo.bar.baz |
| foo/__init__.py | import foo | foo |
Notice the last row. __name__ of __init__.py does not contain __init__.
This article is originally created by tooli.top. Please indicate the source when reprinting : https://www.tooli.top/posts/name
Posted on 2022-04-07
Mail to author