Python3: Why does __spec__ work?

Where __spec__ variable __spec__ ?

 $ brew install python3 $ python3 Python 3.4.2 (default, Jan 5 2015, 11:57:21) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin Type "help", "copyright", "credits" or "license" for more information. # Under Python 2.7.x this gives a NameError >>> None is __spec__ True 
+5
source share
2 answers

From the Python Language Reference, Part 5: Import System (highlighted by me):

The __spec__ attribute must be set to the module specification that was used when importing the module. This is used primarily for introspection and during reboots. The __spec__ setting __spec__ equally to modules initialized during interpreter startup . The only exception is __main__ , where __spec__ is set to None in some cases .

New in version 3.4.

+5
source

According to Python 3 docs , __spec__ always None if you use interactive promt:

When Python starts with the -m option, __spec__ set to the module specification of the corresponding module or package. __spec__ also populated when the __main__ module is loaded as part of a directory, zipfile, or other sys.path file.

In other cases, __main__.__spec__ set to None , as the code used to fill __main__ , the directly imported module does not correspond:

  • interactive invitation
  • -c switch
  • works from stdin
  • executed directly from source file or bytecode
+1
source

Source: https://habr.com/ru/post/1210445/


All Articles