Running a script from the command line, the __name__
attribute of that script will be '__main__'
. But import
ing that script from a different location, the __name__
attribute of that module will be the name of the script.
How does python know what the value of __name__
should be? Can a script tell that it's being imported, and set the __name__
attribute accordingly?
The import machinery fills in these attributes on each module object during loading, based on the module's spec, before the loader executes the module.
__name__
The__name__
attribute must be set to the fully-qualified name of the module. This name is used to uniquely identify the module in the import system.
So these magic attributes are assigned during the so-called "import machinery". You can read more details about that system in the docs as well.
Q: How does python know what the value of
__name__
should be?
Well, if you write import foo
Python will look for a module named 'foo' and set its name to 'foo'.
Q: Can a module tell that it's being imported, ...
Yes, it can. Usually people do that with if __name__ == '__main__'
-- if the test passes, it generally means that the module is being executed, if it fails it generally means that it is being imported.
A particular case where this test will fail is when you have a module named __main__
(in a file named __main__.py
).
If you want to be 100% more sure, you can inspect the frames and see if the module is on top of the stack:
f = sys._getframe()
if f.f_back is None:
# We're at the top of the stack: this module is being executed.
else:
# There's a frame on top of us: this module has been imported.
Q: ... and set the
__name__
attribute accordingly?
And yes, you can change __name__
to whatever you want by simply setting it:
__name__ = 'bar'
Although there's no reason to do so, other than generating confusion and possibly introducing bugs.
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.