Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3: Why does __spec__ work?

Where does the variable __spec__ come from?

$ 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
like image 518
pzrq Avatar asked Jan 06 '15 06:01

pzrq


People also ask

What is __ module __ in Python?

A module in Python is a file (ending in .py ) that contains a set of definitions (variables and functions) that you can use when they are imported.

Why I Cannot import module in Python?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

How do you prevent names from being imported with from import * statement in Python?

There is no easy way to forbid importing a global name from a module; Python simply is not built that way. While you could possibly achieve the forbidding goal if you wrote your own __import__ function and shadowed the built-in one, but I doubt the cost in time and testing would be worth it nor completely effective.

What is a Python module spec?

machinery called “ModuleSpec”. It will provide all the import-related information used to load a module and will be available without needing to load the module first. Finders will directly provide a module's spec instead of a loader (which they will continue to provide indirectly).


2 Answers

From the Python Language Reference, Part 5: The Import System (emphasis mine):

The __spec__ attribute must be set to the module spec that was used when importing the module. This is used primarily for introspection and during reloading. Setting __spec__ appropriately applies equally to modules initialized during interpreter startup. The one exception is __main__, where __spec__ is set to None in some cases.

New in version 3.4.

like image 84
agf Avatar answered Sep 28 '22 03:09

agf


According to Python 3 docs, __spec__ is always None if you are using interactive promt:

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

In the remaining cases __main__.__spec__ is set to None, as the code used to populate the __main__ does not correspond directly with an importable module:

  • interactive prompt
  • -c switch
  • running from stdin
  • running directly from a source or bytecode file
like image 26
awesoon Avatar answered Sep 28 '22 05:09

awesoon