If my understanding is correct, the difference between the __package__
and __name__
variable is:
__init__.py
file.__name__
will be the full path, and __package__
will be the directory of it. Is this correct? If so, why is it necessary for python to add an additional variable in the scope for the __package__
when someone could just as well get it from __name__
?
Example, for a models.py
file:
__name__
==> apps.main.models __module__
==> apps.main __package__
and __name__
are not about files, paths, or directories. If you want information about files, paths, and directories, that's given by __file__
, which stores the relative or absolute filesystem path by which Python found the file for a module.
As documented in the import system documentation , __name__
stores the fully qualified name of a module, and __package__
is used to support relative imports for main modules. Whatever module is run as Python's entry point gets the name '__main__'
, so __name__
is useless for relative imports there. __package__
says what package to base relative imports from in that case.
For example,
random.__package__
is ''
, not a directory, because random
is a (non-package) top-level module, and relative imports inside random
are disallowed. __package__
and __name__
, because __package__
and __name__
aren't about the file system. It has no __file__
, because there is no file in the file system for an implicit namespace package.foo
and files __init__.py
and bar.py
inside foo
, and you run python -m foo.bar
from the directory above foo
, then foo/bar
will be run as a module with __name__ == '__main__'
and __package__ == 'foo'
.
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.