Where / how is the name `posix` resolved using the import statement?

What happens behind the scenes (in CPython 3.6.0) when the code uses import posix? This module does not have an attribute __file__. When I start the interpreter in verbose mode, I see this line:

import 'posix' # <class '_frozen_importlib.BuiltinImporter'>

It is already present in sys.modulesthe newly opened interpreter, and importing it simply binds the name to the existing module.

I am trying to look at implementation details os.lstaton my platform to determine if it uses and when it uses os.stat.

+4
source share
1 answer

Here you have more details than you might need.


posix - . " ", , , C, posix , .

posix C, Modules/posixmodule.c. , C, C, .so .pyd , Python, posix Python.


CPython - PyImport_Inittab array:

extern struct _inittab _PyImport_Inittab[];

struct _inittab *PyImport_Inittab = _PyImport_Inittab;

struct _inittab s, C . , , .

_PyImport_Inittab, Modules/config.c ( PC/config.c , ). , Modules/config.c Modules/config.c.in Python, , , , :

struct _inittab _PyImport_Inittab[] = {

        {"_thread", PyInit__thread},
        {"posix", PyInit_posix},
        // ...

, posix PyInit_posix.


, Python sys.meta_path, finders. sys.path, , , , - _frozen_importlib.BuiltinImporter, , posix. Python , finder find_spec :

@classmethod
def find_spec(cls, fullname, path=None, target=None):
    if path is not None:
        return None
    if _imp.is_builtin(fullname):
        return spec_from_loader(fullname, cls, origin='built-in')
    else:
        return None

_imp.is_builtin PyImport_Inittab "posix". , find_spec , , . ( - spec_from_loader. cls, BuiltinImporter - , .)

Python create_module :

@classmethod
def create_module(self, spec):
    """Create a built-in module"""
    if spec.name not in sys.builtin_module_names:
        raise ImportError('{!r} is not a built-in module'.format(spec.name),
                          name=spec.name)
    return _call_with_frames_removed(_imp.create_builtin, spec)

_imp.create_builtin, PyImport_Inittab .

(_call_with_frames_removed(x, y) x(y), importlib , , .)


, Lib/importlib/_bootstrap.py, , Python/import.c, C- , Python/ceval.c, -, , , import, .

, PEP 451 302. , , , Python , PyImport_Inittab, sys.builtin_module_names.

+3
source

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


All Articles