简体   繁体   中英

__name__ vs __package__ in python

If my understanding is correct, the difference between the __package__ and __name__ variable is:

  • They are both the same for an __init__.py file.
  • For any other files, __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.
  • An implicit namespace package , which exists across multiple directories, still has a single value of __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.
  • If you have a directory 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM