What is the default binding to the `__import__` attribute of the module `builtin`?

时光总嘲笑我的痴心妄想 提交于 2019-12-25 08:59:16

问题


From Python in a Nutshell

Custom Importers

An advanced, rarely needed functionality that Python offers is the ability to change the semantics of some or all import and from statements.

Rebinding __import__

You can rebind the __import__ attribute of the module builtin to your own custom importer function—for example, one using the generic built-in-wrapping technique shown in “Python built-ins” on page 174.

  1. In "You can rebind the __import__ attribute of the module builtin", should "the module builtin" be "the module builtins" instead?

  2. Is "the __import__ attribute of the module builtin" bound to importlib.__import__function by default? Or does "the module builtin" provide the default implementation bound to its __import__ attribute?


回答1:


  1. Yes, that's a typo in the book. In Python 2 the same module is named __builtin__ (no s), in Python 3 it is named builtins.

  2. builtins.__import__ is a distinct function from importlib.__import__. If you are going to rebind builtins.__import__, save a reference.

    • builtins.__import__ is implemented in C, and essentially calls the C-API PyImport_ImportModuleLevelObject function.

    • importlib.__import__ is a pure-Python function. The goal of importlib is to provide a pure-python implementation of the import machinery so it can be hacked on more easily, and this function is no exception.



来源:https://stackoverflow.com/questions/44655446/what-is-the-default-binding-to-the-import-attribute-of-the-module-builtin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!