importlib — A implementação de import¶
Adicionado na versão 3.1.
Código-fonte: Lib/importlib/__init__.py
Introdução¶
O pacote importlib tem três propósitos.
Uma é fornecer a implementação da instrução import (e, portanto, por extensão, a função __import__()) no código-fonte Python. Isso fornece uma implementação de import que é portável para qualquer interpretador Python. Isso também fornece uma implementação que é mais fácil de compreender do que aquela implementada em uma linguagem de programação diferente do Python.
Dois, os componentes para implementar import são expostos neste pacote, tornando mais fácil para os usuários criarem seus próprios objetos personalizados (conhecidos genericamente como importador) para participar do processo de importação.
Terceiro, o pacote contém módulos que expõem funcionalidades adicionais para gerenciar aspectos de pacotes Python:
importlib.metadataapresenta acesso a metadados de distribuições de terceiros.importlib.resourcesfornece rotinas para acessar “recursos” não codificados de pacotes Python.
Ver também
- A instrução import
A referência da linguagem para a instrução
import.- Especificação dos pacotes
Especificação original dos pacotes. Algumas semânticas mudaram desde a redação deste documento (por exemplo, redirecionamento baseado em
Noneemsys.modules).- A função
__import__() A instrução
importé um açúcar sintático para esta função.- A inicialização do caminho de pesquisa de módulos sys.path
A inicialização de
sys.path.- PEP 235
Importação em plataformas que diferenciam maiúsculo de minúsculo
- PEP 263
Definindo codificações do código-fonte do Python
- PEP 302
Novos ganchos de importação
- PEP 328
Importações: Multilinha e Absoluto/Relativo
- PEP 366
Importações relativas explícitas do módulo principal
- PEP 420
Pacotes de espaço de nomes implícitos
- PEP 451
Um tipo de ModuleSpec para o sistema de importação
- PEP 488
Eliminação de arquivos PYO
- PEP 489
Inicialização de módulo extensão multifase
- PEP 552
pycs determinísticos
- PEP 3120
Usando UFT-8 como fonte padrão de codificação
- PEP 3147
Diretórios de repositório de PYC
Funções¶
- importlib.__import__(name, globals=None, locals=None, fromlist=(), level=0)¶
Uma implementação da função embutida
__import__().Nota
A importação programática de módulos deve usar
import_module()em vez desta função.
- importlib.import_module(name, package=None)¶
Importa um módulo. O argumento name especifica qual módulo importar em termos absolutos ou relativos (por exemplo,
pkg.modou..mod). Se o nome for especificado em termos relativos, então o argumento package deve ser definido como o nome do pacote que atuará como âncora para resolver o nome do pacote (por exemplo,import_module('..mod', 'pkg.subpkg')importarápkg.mod).A função
import_module()atua como um wrapper simplificador em torno deimportlib.__import__(). Isso significa que toda a semântica da função é derivada deimportlib.__import__(). A diferença mais importante entre essas duas funções é queimport_module()retorna o pacote ou módulo especificado (por exemplo,pkg.mod), enquanto__import__()retorna o pacote ou módulo de nível superior (por exemplo,pkg).Se você estiver importando dinamicamente um módulo que foi criado desde que o interpretador iniciou a execução (por exemplo, criou um arquivo fonte Python), você pode precisar chamar
invalidate_caches()para que o novo módulo seja notado pelo sistema de importação.Alterado na versão 3.3: Os pacotes pai são importados automaticamente.
- importlib.invalidate_caches()¶
Invalida os caches internos dos localizadores armazenados em
sys.meta_path. Se um localizador implementarinvalidate_caches()então ele será chamado para realizar a invalidação. Esta função deve ser chamada se algum módulo for criado/instalado enquanto seu programa estiver em execução para garantir que todos os localizadores notarão a existência do novo módulo.Adicionado na versão 3.3.
Alterado na versão 3.10: Pacotes de espaço de nomes criados/instalados em um local
sys.pathdiferente após o mesmo espaço de nomes já ter sido importado são notados.
- importlib.reload(module)¶
Recarrega um module importado anteriormente. O argumento deve ser um objeto módulo, portanto deve ter sido importado com êxito antes. Isso é útil se você editou o arquivo fonte do módulo usando um editor externo e deseja experimentar a nova versão sem sair do interpretador Python. O valor de retorno é o objeto módulo (que pode ser diferente se a reimportação fizer com que um objeto diferente seja colocado em
sys.modules).Quando
reload()é executado:O código do módulo Python é recompilado e o código em nível de módulo é reexecutado, definindo um novo conjunto de objetos que são vinculados a nomes no dicionário do módulo reutilizando o carregador que originalmente carregou o módulo. A função
initdos módulos de extensão não é chamada uma segunda vez.Tal como acontece com todos os outros objetos em Python, os objetos antigos só são recuperados depois que suas contagens de referências caem para zero.
Os nomes no espaço de nomes do módulo são atualizados para apontar para quaisquer objetos novos ou alterados.
Outras referências aos objetos antigos (como nomes externos ao módulo) não são religadas para se referir aos novos objetos e devem ser atualizadas em cada espaço de nomes onde ocorrem, se isso for desejado.
Existem várias outras ressalvas:
Quando um módulo é recarregado, seu dicionário (contendo as variáveis globais do módulo) é retido. As redefinições de nomes vão substituir as definições antigas, portanto isso geralmente não é um problema. Se a nova versão de um módulo não definir um nome definido pela versão antiga, a definição antiga permanecerá. Este recurso pode ser usado para vantagem do módulo se ele mantiver uma tabela global ou cache de objetos – com uma instrução
tryele pode testar a presença da tabela e pular sua inicialização se desejar:try: cache except NameError: cache = {}
Geralmente não é muito útil recarregar módulos embutidos ou carregados dinamicamente. Recarregar
sys,__main__,builtinse outros módulos principais não é recomendado. Em muitos casos, os módulos de extensão não são projetados para serem inicializados mais de uma vez e podem falhar de maneiras arbitrárias quando recarregados.Se um módulo importa objetos de outro módulo usando
from…import…, chamarreload()para o outro módulo não redefine os objetos importados dele – uma maneira de contornar isso é executar novamente a instruçãofrom, outra é usarimporte nomes qualificados (module.name).Se um módulo instancia instâncias de uma classe, recarregar o módulo que define a classe não afeta as definições de método das instâncias – elas continuam a usar a definição de classe antiga. O mesmo se aplica às classes derivadas.
Adicionado na versão 3.4.
Alterado na versão 3.7:
ModuleNotFoundErroré levantada quando o módulo que está sendo recarregado não possui umModuleSpec.
importlib.abc – classes base abstratas relacionadas a importação¶
Código-fonte: Lib/importlib/abc.py
O módulo importlib.abc contém todas as principais classes base abstratas usadas por import. Algumas subclasses das classes base abstratas principais também são fornecidas para ajudar na implementação dss ABCs principais.
Hierarquia de ABC:
object
+-- MetaPathFinder
+-- PathEntryFinder
+-- Loader
+-- ResourceLoader --------+
+-- InspectLoader |
+-- ExecutionLoader --+
+-- FileLoader
+-- SourceLoader
- class importlib.abc.MetaPathFinder¶
Uma classe base abstrata que representa um localizador de metacaminho.
Adicionado na versão 3.3.
Alterado na versão 3.10: Não é mais uma subclasse de
Finder.- find_spec(fullname, path, target=None)¶
Um método abstrato para encontrar um spec para o módulo especificado. Se esta for uma importação de nível superior, path será
None. Caso contrário, esta é uma busca por um subpacote ou módulo e path será o valor de__path__do pacote pai. Se uma especificação não puder ser encontrada,Noneserá retornado. Quando passado,targeté um objeto de módulo que o localizador pode usar para fazer uma estimativa mais informada sobre qual especificação retornar.importlib.util.spec_from_loader()pode ser útil para implementarMetaPathFindersconcretos.Adicionado na versão 3.4.
- invalidate_caches()¶
Um método opcional que, quando chamado, deve invalidar qualquer cache interno usado pelo localizador. Usado por
importlib.invalidate_caches()ao invalidar os caches de todos os localizadores emsys.meta_path.Alterado na versão 3.4: Retorna
Nonequando chamado em vez deNotImplemented.
- class importlib.abc.PathEntryFinder¶
Uma classe base abstrata que representa um localizador de entrada de caminho. Embora tenha algumas semelhanças com
MetaPathFinder,PathEntryFinderdeve ser usado apenas dentro do subsistema de importação baseado em caminho fornecido porimportlib.machinery.PathFinder.Adicionado na versão 3.3.
Alterado na versão 3.10: Não é mais uma subclasse de
Finder.- find_spec(fullname, target=None)¶
Um método abstrato para encontrar um spec para o módulo especificado. O localizador irá procurar pelo módulo apenas dentro do entrada de caminho ao qual ele está atribuído. Se uma especificação não puder ser encontrada,
Noneserá retornado. Quando passado,targeté um objeto de módulo que o localizador pode usar para fazer uma estimativa mais informada sobre qual especificação retornar.importlib.util.spec_from_loader()pode ser útil para implementarPathEntryFindersconcretos.Adicionado na versão 3.4.
- invalidate_caches()¶
Um método opcional que, quando chamado, deve invalidar qualquer cache interno usado pelo localizador. Usado por
importlib.machinery.PathFinder.invalidate_caches()ao invalidar os caches de todos os localizadores em cache.
- class importlib.abc.Loader¶
Uma classe base abstrata para um carregador. Veja PEP 302 para a definição exata de um carregador.
Carregadores que desejam oferecer suporte a leitura de recursos devem implementar um método
get_resource_reader()conforme especificado porimportlib.resources.abc.ResourceReader.Alterado na versão 3.7: Introduzido o método opcional
get_resource_reader().- create_module(spec)¶
Um método que retorna o objeto do módulo a ser usado ao importar um módulo. Este método pode retornar
None, indicando que a semântica padrão de criação do módulo deve ocorrer.Adicionado na versão 3.4.
Alterado na versão 3.6: Este método não é mais opcional quando
exec_module()é definido.
- exec_module(module)¶
Um método abstrato que executa o módulo em seu próprio espaço de nomes quando um módulo é importado ou recarregado. O módulo já deve estar inicializado quando
exec_module()for chamado. Quando este método existir,create_module()deve ser definido.Adicionado na versão 3.4.
Alterado na versão 3.6:
create_module()deve ser definido.
- load_module(fullname)¶
Um método legado para carregar um módulo. Se o módulo não puder ser carregado,
ImportErrorserá levantada, caso contrário, o módulo carregado será retornado.Se o módulo solicitado já existir em
sys.modules, esse módulo deverá ser usado e recarregado. Caso contrário, o carregador deve criar um novo módulo e inseri-lo emsys.modulesantes de qualquer carregamento começar, para evitar a recursão da importação. Se o carregador inseriu um módulo e o carregamento falhar, ele deverá ser removido pelo carregador desys.modules; módulos já emsys.modulesantes do carregador iniciar a execução devem ser deixados sozinhos.O carregador deve definir vários atributos no módulo (observe que alguns desses atributos podem mudar quando um módulo é recarregado):
__name__O nome totalmente qualificado do módulo. É
'__main__'para um módulo executado.
__file__O local que o carregador usou para carregar o módulo. Por exemplo, para módulos carregados de um arquivo .py, este é o nome do arquivo. Não está definido em todos os módulos (por exemplo, módulos embutidos).
__cached__O nome do arquivo de uma versão compilada do código do módulo. Não está definido em todos os módulos (por exemplo, módulos embutido).
__path__A lista de locais onde os submódulos do pacote serão encontrados. Na maioria das vezes, este é um único diretório. O sistema de importação passa este atributo para
__import__()e para os localizadores da mesma forma quesys.pathmas apenas para o pacote. Não é definido em módulos que não são de pacote, portanto pode ser usado como um indicador de que o módulo é um pacote.
__package__O nome totalmente qualificado do pacote em que o módulo está (ou a string vazia para um módulo de nível superior). Se o módulo for um pacote então é o mesmo que
__name__.
__loader__O carregador usado para carregar o módulo.
Quando
exec_module()está disponível, então a funcionalidade compatível com versões anteriores é fornecida.Alterado na versão 3.4: Levanta
ImportErrorquando chamado em vez deNotImplementedError. Funcionalidade fornecida quandoexec_module()está disponível.Obsoleto desde a versão 3.4: A API recomendada para carregar um módulo é
exec_module()(ecreate_module()). Os carregadores devem implementá-lo em vez deload_module(). O mecanismo de importação cuida de todas as outras responsabilidades deload_module()quandoexec_module()é implementado.
- class importlib.abc.ResourceLoader¶
Uma classe base abstrata para um carregador que implementa o protocolo opcional PEP 302 para carregar recursos arbitrários do back-end de armazenamento.
Obsoleto desde a versão 3.7: Este ABC foi descontinuado em favor do suporte ao carregamento de recursos por meio de
importlib.resources.abc.ResourceReader.- abstractmethod get_data(path)¶
Um método abstrato para retornar os bytes dos dados localizados em path. Carregadores que possuem um backend de armazenamento arquivo ou similar que permite o armazenamento de dados arbitrários podem implementar esse método abstrato para fornecer acesso direto aos dados armazenados.
OSErrordeve ser levantada se o path não puder ser encontrado. Espera-se que o path seja construído usando o atributo__file__de um módulo ou um item de__path__de um pacote.Alterado na versão 3.4: Levanta
OSErrorem vez deNotImplementedError.
- class importlib.abc.InspectLoader¶
Uma classe base abstrata para um carregador que implementa o protocolo opcional da PEP 302 para carregadores que inspecionam módulos.
- get_code(fullname)¶
Retorna o objeto de código para um módulo, ou
Nonese o módulo não tiver um objeto código (como seria o caso, por exemplo, para um módulo embutido). Levanta umImportErrorse o carregador não conseguir encontrar o módulo solicitado.Nota
Embora o método tenha uma implementação padrão, sugere-se que ele seja substituído, se possível, para desempenho.
Alterado na versão 3.4: No longer abstract and a concrete implementation is provided.
- abstractmethod get_source(fullname)¶
An abstract method to return the source of a module. It is returned as a text string using universal newlines, translating all recognized line separators into
'\n'characters. ReturnsNoneif no source is available (e.g. a built-in module). RaisesImportErrorif the loader cannot find the module specified.Alterado na versão 3.4: Raises
ImportErrorinstead ofNotImplementedError.
- is_package(fullname)¶
An optional method to return a true value if the module is a package, a false value otherwise.
ImportErroris raised if the loader cannot find the module.Alterado na versão 3.4: Raises
ImportErrorinstead ofNotImplementedError.
- static source_to_code(data, path='<string>')¶
Create a code object from Python source.
The data argument can be whatever the
compile()function supports (i.e. string or bytes). The path argument should be the “path” to where the source code originated from, which can be an abstract concept (e.g. location in a zip file).With the subsequent code object one can execute it in a module by running
exec(code, module.__dict__).Adicionado na versão 3.4.
Alterado na versão 3.5: Made the method static.
- exec_module(module)¶
Implementation of
Loader.exec_module().Adicionado na versão 3.4.
- load_module(fullname)¶
Implementation of
Loader.load_module().Obsoleto desde a versão 3.4: use
exec_module()instead.
- class importlib.abc.ExecutionLoader¶
An abstract base class which inherits from
InspectLoaderthat, when implemented, helps a module to be executed as a script. The ABC represents an optional PEP 302 protocol.- abstractmethod get_filename(fullname)¶
An abstract method that is to return the value of
__file__for the specified module. If no path is available,ImportErroris raised.If source code is available, then the method should return the path to the source file, regardless of whether a bytecode was used to load the module.
Alterado na versão 3.4: Raises
ImportErrorinstead ofNotImplementedError.
- class importlib.abc.FileLoader(fullname, path)¶
An abstract base class which inherits from
ResourceLoaderandExecutionLoader, providing concrete implementations ofResourceLoader.get_data()andExecutionLoader.get_filename().The fullname argument is a fully resolved name of the module the loader is to handle. The path argument is the path to the file for the module.
Adicionado na versão 3.3.
- name¶
The name of the module the loader can handle.
- path¶
Caminho para o arquivo do módulo
- load_module(fullname)¶
Calls super’s
load_module().Obsoleto desde a versão 3.4: Use
Loader.exec_module()instead.
- abstractmethod get_data(path)¶
Reads path as a binary file and returns the bytes from it.
- class importlib.abc.SourceLoader¶
An abstract base class for implementing source (and optionally bytecode) file loading. The class inherits from both
ResourceLoaderandExecutionLoader, requiring the implementation of:ExecutionLoader.get_filename()Should only return the path to the source file; sourceless loading is not supported.
The abstract methods defined by this class are to add optional bytecode file support. Not implementing these optional methods (or causing them to raise
NotImplementedError) causes the loader to only work with source code. Implementing the methods allows the loader to work with source and bytecode files; it does not allow for sourceless loading where only bytecode is provided. Bytecode files are an optimization to speed up loading by removing the parsing step of Python’s compiler, and so no bytecode-specific API is exposed.- path_stats(path)¶
Optional abstract method which returns a
dictcontaining metadata about the specified path. Supported dictionary keys are:'mtime'(mandatory): an integer or floating-point number representing the modification time of the source code;'size'(optional): the size in bytes of the source code.
Any other keys in the dictionary are ignored, to allow for future extensions. If the path cannot be handled,
OSErroris raised.Adicionado na versão 3.3.
Alterado na versão 3.4: Raise
OSErrorinstead ofNotImplementedError.
- path_mtime(path)¶
Optional abstract method which returns the modification time for the specified path.
Obsoleto desde a versão 3.3: This method is deprecated in favour of
path_stats(). You don’t have to implement it, but it is still available for compatibility purposes. RaiseOSErrorif the path cannot be handled.Alterado na versão 3.4: Raise
OSErrorinstead ofNotImplementedError.
- set_data(path, data)¶
Optional abstract method which writes the specified bytes to a file path. Any intermediate directories which do not exist are to be created automatically.
When writing to the path fails because the path is read-only (
errno.EACCES/PermissionError), do not propagate the exception.Alterado na versão 3.4: No longer raises
NotImplementedErrorwhen called.
- get_code(fullname)¶
Concrete implementation of
InspectLoader.get_code().
- exec_module(module)¶
Concrete implementation of
Loader.exec_module().Adicionado na versão 3.4.
- load_module(fullname)¶
Concrete implementation of
Loader.load_module().Obsoleto desde a versão 3.4: Use
exec_module()instead.
- get_source(fullname)¶
Concrete implementation of
InspectLoader.get_source().
- is_package(fullname)¶
Concrete implementation of
InspectLoader.is_package(). A module is determined to be a package if its file path (as provided byExecutionLoader.get_filename()) is a file named__init__when the file extension is removed and the module name itself does not end in__init__.
- class importlib.abc.ResourceReader¶
Substituída por TraversableResources
Uma classe base abstrata para fornecer a capacidade de ler recursos.
Da perspectiva deste ABC, um recurso é um artefato binário que é enviado dentro de um pacote. Normalmente isso é algo como um arquivo de dados que fica próximo ao arquivo
__init__.pydo pacote. O objetivo desta classe é ajudar a abstrair o acesso a tais arquivos de dados para que não importe se o pacote e seu(s) arquivo(s) de dados estão armazenados em um arquivo, por exemplo, zip versus no sistema de arquivos.Para qualquer um dos métodos desta classe, espera-se que o argumento resource seja um objeto caminho ou similar que representa conceitualmente apenas um nome de arquivo. Isso significa que nenhum caminho de subdiretório deve ser incluído no argumento resource. Isso ocorre porque a localização do pacote para o qual o leitor se destina, atua como o “diretório”. Portanto, a metáfora para diretórios e nomes de arquivos são pacotes e recursos, respectivamente. É também por isso que se espera que as instâncias dessa classe se correlacionem diretamente a um pacote específico (em vez de representar potencialmente vários pacotes ou um módulo).
Carregadores que desejam oferecer suporte à leitura de recursos devem fornecer um método chamado
get_resource_reader(nomecompleto)que retorna um objeto implementando esta interface ABC. Se o módulo especificado por nomecompleto não for um pacote, este método deve retornarNone. Um objeto compatível com este ABC só deve ser retornado quando o módulo especificado for um pacote.Adicionado na versão 3.7.
Descontinuado desde a versão 3.12, será removido na versão 3.14: Use
importlib.resources.abc.TraversableResources.- abstractmethod open_resource(resource)¶
Retorna um objeto arquivo ou similar aberto para leitura binária de resource.
Se o recurso não puder ser encontrado,
FileNotFoundErroré levantada.
- abstractmethod resource_path(resource)¶
Retorna o caminho do sistema de arquivos para resource.
Se o recurso não existir concretamente no sistema de arquivos, levanta
FileNotFoundError.
- abstractmethod is_resource(name)¶
Retorna
Truese o name nomeado for considerado um recurso.FileNotFoundErroré levantada se name não existir.
- abstractmethod contents()¶
Retorna um iterável de strings sobre o conteúdo do pacote. Observe que não é necessário que todos os nomes retornados pelo iterador sejam recursos reais, por exemplo, é aceitável retornar nomes para os quais
is_resource()seria falso.Permitir que nomes que não são recursos sejam retornados é permitir situações em que a forma como um pacote e seus recursos são armazenados é conhecida a priori e os nomes que não são recursos seriam úteis. Por exemplo, o retorno de nomes de subdiretórios é permitido para que, quando se souber que o pacote e os recursos estão armazenados no sistema de arquivos, esses nomes de subdiretórios possam ser usados diretamente.
O método abstrato retorna um iterável sem itens.
- class importlib.abc.Traversable¶
Um objeto com um subconjunto de métodos de
pathlib.Pathadequados para percorrer diretórios e abrir arquivos.Para uma representação do objeto no sistema de arquivos, use
importlib.resources.as_file().Adicionado na versão 3.9.
Descontinuado desde a versão 3.12, será removido na versão 3.14: Use
importlib.resources.abc.Traversable.- name¶
Abstrato. O nome base deste objeto sem nenhuma referência pai.
- abstractmethod iterdir()¶
Yield
Traversableobjects inself.
- abstractmethod is_dir()¶
Return
Trueifselfis a directory.
- abstractmethod is_file()¶
Return
Trueifselfis a file.
- abstractmethod joinpath(child)¶
Return Traversable child in
self.
- abstractmethod __truediv__(child)¶
Return
Traversablechild inself.
- abstractmethod open(mode='r', *args, **kwargs)¶
mode pode ser ‘r’ ou ‘rb’ para abrir como texto ou binário. Retorna um manipulador adequado para leitura (o mesmo que
pathlib.Path.open).Ao abrir como texto, aceita parâmetros de codificação como os aceitos por
io.TextIOWrapper.
- read_bytes()¶
Read contents of
selfas bytes.
- read_text(encoding=None)¶
Read contents of
selfas text.
- class importlib.abc.TraversableResources¶
Uma classe base abstrata para leitores de recursos capaz de servir a interface
importlib.resources.files(). Subclasseimportlib.resources.abc.ResourceReadere fornece implementações concretas dos métodos abstratos deimportlib.resources.abc.ResourceReader. Portanto, qualquer carregador que forneçaimportlib.abc.TraversableResourcestambém fornece ResourceReader.Espera-se que os carregadores que desejam oferecer suporte à leitura de recursos implementem essa interface.
Adicionado na versão 3.9.
Descontinuado desde a versão 3.12, será removido na versão 3.14: Use
importlib.resources.abc.TraversableResources.- abstractmethod files()¶
Retorna um objeto
importlib.resources.abc.Traversablepara o pacote carregado.
importlib.machinery – Importers and path hooks¶
Source code: Lib/importlib/machinery.py
This module contains the various objects that help import
find and load modules.
- importlib.machinery.SOURCE_SUFFIXES¶
A list of strings representing the recognized file suffixes for source modules.
Adicionado na versão 3.3.
- importlib.machinery.DEBUG_BYTECODE_SUFFIXES¶
A list of strings representing the file suffixes for non-optimized bytecode modules.
Adicionado na versão 3.3.
Obsoleto desde a versão 3.5: Use
BYTECODE_SUFFIXESinstead.
- importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES¶
A list of strings representing the file suffixes for optimized bytecode modules.
Adicionado na versão 3.3.
Obsoleto desde a versão 3.5: Use
BYTECODE_SUFFIXESinstead.
- importlib.machinery.BYTECODE_SUFFIXES¶
A list of strings representing the recognized file suffixes for bytecode modules (including the leading dot).
Adicionado na versão 3.3.
Alterado na versão 3.5: The value is no longer dependent on
__debug__.
- importlib.machinery.EXTENSION_SUFFIXES¶
A list of strings representing the recognized file suffixes for extension modules.
Adicionado na versão 3.3.
- importlib.machinery.all_suffixes()¶
Returns a combined list of strings representing all file suffixes for modules recognized by the standard import machinery. This is a helper for code which simply needs to know if a filesystem path potentially refers to a module without needing any details on the kind of module (for example,
inspect.getmodulename()).Adicionado na versão 3.3.
- class importlib.machinery.BuiltinImporter¶
An importer for built-in modules. All known built-in modules are listed in
sys.builtin_module_names. This class implements theimportlib.abc.MetaPathFinderandimportlib.abc.InspectLoaderABCs.Only class methods are defined by this class to alleviate the need for instantiation.
Alterado na versão 3.5: As part of PEP 489, the builtin importer now implements
Loader.create_module()andLoader.exec_module()
- class importlib.machinery.FrozenImporter¶
An importer for frozen modules. This class implements the
importlib.abc.MetaPathFinderandimportlib.abc.InspectLoaderABCs.Only class methods are defined by this class to alleviate the need for instantiation.
Alterado na versão 3.4: Gained
create_module()andexec_module()methods.
- class importlib.machinery.WindowsRegistryFinder¶
Finder for modules declared in the Windows registry. This class implements the
importlib.abc.MetaPathFinderABC.Only class methods are defined by this class to alleviate the need for instantiation.
Adicionado na versão 3.3.
Obsoleto desde a versão 3.6: Use
siteconfiguration instead. Future versions of Python may not enable this finder by default.
- class importlib.machinery.PathFinder¶
A Finder for
sys.pathand package__path__attributes. This class implements theimportlib.abc.MetaPathFinderABC.Only class methods are defined by this class to alleviate the need for instantiation.
- classmethod find_spec(fullname, path=None, target=None)¶
Class method that attempts to find a spec for the module specified by fullname on
sys.pathor, if defined, on path. For each path entry that is searched,sys.path_importer_cacheis checked. If a non-false object is found then it is used as the path entry finder to look for the module being searched for. If no entry is found insys.path_importer_cache, thensys.path_hooksis searched for a finder for the path entry and, if found, is stored insys.path_importer_cachealong with being queried about the module. If no finder is ever found thenNoneis both stored in the cache and returned.Adicionado na versão 3.4.
Alterado na versão 3.5: If the current working directory – represented by an empty string – is no longer valid then
Noneis returned but no value is cached insys.path_importer_cache.
- classmethod invalidate_caches()¶
Calls
importlib.abc.PathEntryFinder.invalidate_caches()on all finders stored insys.path_importer_cachethat define the method. Otherwise entries insys.path_importer_cacheset toNoneare deleted.Alterado na versão 3.7: Entries of
Noneinsys.path_importer_cacheare deleted.
Alterado na versão 3.4: Calls objects in
sys.path_hookswith the current working directory for''(i.e. the empty string).
- class importlib.machinery.FileFinder(path, *loader_details)¶
A concrete implementation of
importlib.abc.PathEntryFinderwhich caches results from the file system.The path argument is the directory for which the finder is in charge of searching.
The loader_details argument is a variable number of 2-item tuples each containing a loader and a sequence of file suffixes the loader recognizes. The loaders are expected to be callables which accept two arguments of the module’s name and the path to the file found.
The finder will cache the directory contents as necessary, making stat calls for each module search to verify the cache is not outdated. Because cache staleness relies upon the granularity of the operating system’s state information of the file system, there is a potential race condition of searching for a module, creating a new file, and then searching for the module the new file represents. If the operations happen fast enough to fit within the granularity of stat calls, then the module search will fail. To prevent this from happening, when you create a module dynamically, make sure to call
importlib.invalidate_caches().Adicionado na versão 3.3.
- path¶
The path the finder will search in.
- find_spec(fullname, target=None)¶
Attempt to find the spec to handle fullname within
path.Adicionado na versão 3.4.
- invalidate_caches()¶
Clear out the internal cache.
- classmethod path_hook(*loader_details)¶
A class method which returns a closure for use on
sys.path_hooks. An instance ofFileFinderis returned by the closure using the path argument given to the closure directly and loader_details indirectly.If the argument to the closure is not an existing directory,
ImportErroris raised.
- class importlib.machinery.SourceFileLoader(fullname, path)¶
A concrete implementation of
importlib.abc.SourceLoaderby subclassingimportlib.abc.FileLoaderand providing some concrete implementations of other methods.Adicionado na versão 3.3.
- name¶
The name of the module that this loader will handle.
- path¶
The path to the source file.
- path_stats(path)¶
Concrete implementation of
importlib.abc.SourceLoader.path_stats().
- set_data(path, data)¶
Concrete implementation of
importlib.abc.SourceLoader.set_data().
- load_module(name=None)¶
Concrete implementation of
importlib.abc.Loader.load_module()where specifying the name of the module to load is optional.Obsoleto desde a versão 3.6: Use
importlib.abc.Loader.exec_module()instead.
- class importlib.machinery.SourcelessFileLoader(fullname, path)¶
A concrete implementation of
importlib.abc.FileLoaderwhich can import bytecode files (i.e. no source code files exist).Please note that direct use of bytecode files (and thus not source code files) inhibits your modules from being usable by all Python implementations or new versions of Python which change the bytecode format.
Adicionado na versão 3.3.
- name¶
The name of the module the loader will handle.
- path¶
The path to the bytecode file.
- get_source(fullname)¶
Returns
Noneas bytecode files have no source when this loader is used.
- load_module(name=None)¶
Concrete implementation of
importlib.abc.Loader.load_module()where specifying the name of the module to load is optional.Obsoleto desde a versão 3.6: Use
importlib.abc.Loader.exec_module()instead.
- class importlib.machinery.ExtensionFileLoader(fullname, path)¶
A concrete implementation of
importlib.abc.ExecutionLoaderfor extension modules.The fullname argument specifies the name of the module the loader is to support. The path argument is the path to the extension module’s file.
Note that, by default, importing an extension module will fail in subinterpreters if it doesn’t implement multi-phase init (see PEP 489), even if it would otherwise import successfully.
Adicionado na versão 3.3.
Alterado na versão 3.12: Multi-phase init is now required for use in subinterpreters.
- name¶
Name of the module the loader supports.
- path¶
Path to the extension module.
- create_module(spec)¶
Creates the module object from the given specification in accordance with PEP 489.
Adicionado na versão 3.5.
- exec_module(module)¶
Initializes the given module object in accordance with PEP 489.
Adicionado na versão 3.5.
- is_package(fullname)¶
Returns
Trueif the file path points to a package’s__init__module based onEXTENSION_SUFFIXES.
- get_code(fullname)¶
Returns
Noneas extension modules lack a code object.
- get_source(fullname)¶
Returns
Noneas extension modules do not have source code.
- class importlib.machinery.NamespaceLoader(name, path, path_finder)¶
A concrete implementation of
importlib.abc.InspectLoaderfor namespace packages. This is an alias for a private class and is only made public for introspecting the__loader__attribute on namespace packages:>>> from importlib.machinery import NamespaceLoader >>> import my_namespace >>> isinstance(my_namespace.__loader__, NamespaceLoader) True >>> import importlib.abc >>> isinstance(my_namespace.__loader__, importlib.abc.Loader) True
Adicionado na versão 3.11.
- class importlib.machinery.ModuleSpec(name, loader, *, origin=None, loader_state=None, is_package=None)¶
A specification for a module’s import-system-related state. This is typically exposed as the module’s
__spec__attribute. In the descriptions below, the names in parentheses give the corresponding attribute available directly on the module object, e.g.module.__spec__.origin == module.__file__. Note, however, that while the values are usually equivalent, they can differ since there is no synchronization between the two objects. For example, it is possible to update the module’s__file__at runtime and this will not be automatically reflected in the module’s__spec__.origin, and vice versa.Adicionado na versão 3.4.
- name¶
(
__name__)The module’s fully qualified name. The finder should always set this attribute to a non-empty string.
- loader¶
The loader used to load the module. The finder should always set this attribute.
- origin¶
(
__file__)The location the loader should use to load the module. For example, for modules loaded from a .py file this is the filename. The finder should always set this attribute to a meaningful value for the loader to use. In the uncommon case that there is not one (like for namespace packages), it should be set to
None.- submodule_search_locations¶
(
__path__)The list of locations where the package’s submodules will be found. Most of the time this is a single directory. The finder should set this attribute to a list, even an empty one, to indicate to the import system that the module is a package. It should be set to
Nonefor non-package modules. It is set automatically later to a special object for namespace packages.- loader_state¶
The finder may set this attribute to an object containing additional, module-specific data to use when loading the module. Otherwise it should be set to
None.- cached¶
The filename of a compiled version of the module’s code. The finder should always set this attribute but it may be
Nonefor modules that do not need compiled code stored.- parent¶
(Read-only) The fully qualified name of the package the module is in (or the empty string for a top-level module). If the module is a package then this is the same as
name.- has_location¶
- class importlib.machinery.AppleFrameworkLoader(name, path)¶
A specialization of
importlib.machinery.ExtensionFileLoaderthat is able to load extension modules in Framework format.For compatibility with the iOS App Store, all binary modules in an iOS app must be dynamic libraries, contained in a framework with appropriate metadata, stored in the
Frameworksfolder of the packaged app. There can be only a single binary per framework, and there can be no executable binary material outside the Frameworks folder.To accomodate this requirement, when running on iOS, extension module binaries are not packaged as
.sofiles onsys.path, but as individual standalone frameworks. To discover those frameworks, this loader is be registered against the.fworkfile extension, with a.fworkfile acting as a placeholder in the original location of the binary onsys.path. The.fworkfile contains the path of the actual binary in theFrameworksfolder, relative to the app bundle. To allow for resolving a framework-packaged binary back to the original location, the framework is expected to contain a.originfile that contains the location of the.fworkfile, relative to the app bundle.Por exemplo, considere o caso de uma importação
from foo.bar import _whiz, onde_whizé implementado com o módulo bináriosources/foo/bar/_whiz.abi3.so, comsourcessendo o local registrado emsys.path, relativo ao pacote da aplicação. Este módulo deve ser distribuído comoFrameworks/foo.bar._whiz.framework/foo.bar._whiz(criando o nome do framework a partir do caminho completo de importação do módulo), com um arquivoInfo.plistno diretório.frameworkidentificando o binário como um framework. O módulofoo.bar._whizseria representado no local original com um arquivo marcadorsources/foo/bar/_whiz.abi3.fwork, contendo o caminhoFrameworks/foo.bar._whiz/foo.bar._whiz. O framework também conteriaFrameworks/foo.bar._whiz.framework/foo.bar._whiz.origin, contendo o caminho para o arquivo.fwork.When a module is loaded with this loader, the
__file__for the module will report as the location of the.fworkfile. This allows code to use the__file__of a module as an anchor for file system traveral. However, the spec origin will reference the location of the actual binary in the.frameworkfolder.The Xcode project building the app is responsible for converting any
.sofiles from wherever they exist in thePYTHONPATHinto frameworks in theFrameworksfolder (including stripping extensions from the module file, the addition of framework metadata, and signing the resulting framework), and creating the.fworkand.originfiles. This will usually be done with a build step in the Xcode project; see the iOS documentation for details on how to construct this build step.Adicionado na versão 3.13.
Availability: iOS.
- name¶
Name of the module the loader supports.
- path¶
Path to the
.fworkfile for the extension module.
importlib.util – Utility code for importers¶
Source code: Lib/importlib/util.py
This module contains the various objects that help in the construction of an importer.
- importlib.util.MAGIC_NUMBER¶
The bytes which represent the bytecode version number. If you need help with loading/writing bytecode then consider
importlib.abc.SourceLoader.Adicionado na versão 3.4.
- importlib.util.cache_from_source(path, debug_override=None, *, optimization=None)¶
Return the PEP 3147/PEP 488 path to the byte-compiled file associated with the source path. For example, if path is
/foo/bar/baz.pythe return value would be/foo/bar/__pycache__/baz.cpython-32.pycfor Python 3.2. Thecpython-32string comes from the current magic tag (seeget_tag(); ifsys.implementation.cache_tagis not defined thenNotImplementedErrorwill be raised).The optimization parameter is used to specify the optimization level of the bytecode file. An empty string represents no optimization, so
/foo/bar/baz.pywith an optimization of''will result in a bytecode path of/foo/bar/__pycache__/baz.cpython-32.pyc.Nonecauses the interpreter’s optimization level to be used. Any other value’s string representation is used, so/foo/bar/baz.pywith an optimization of2will lead to the bytecode path of/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc. The string representation of optimization can only be alphanumeric, elseValueErroris raised.The debug_override parameter is deprecated and can be used to override the system’s value for
__debug__. ATruevalue is the equivalent of setting optimization to the empty string. AFalsevalue is the same as setting optimization to1. If both debug_override an optimization are notNonethenTypeErroris raised.Adicionado na versão 3.4.
Alterado na versão 3.5: The optimization parameter was added and the debug_override parameter was deprecated.
Alterado na versão 3.6: Aceita um objeto caminho ou similar.
- importlib.util.source_from_cache(path)¶
Given the path to a PEP 3147 file name, return the associated source code file path. For example, if path is
/foo/bar/__pycache__/baz.cpython-32.pycthe returned path would be/foo/bar/baz.py. path need not exist, however if it does not conform to PEP 3147 or PEP 488 format, aValueErroris raised. Ifsys.implementation.cache_tagis not defined,NotImplementedErroris raised.Adicionado na versão 3.4.
Alterado na versão 3.6: Aceita um objeto caminho ou similar.
- importlib.util.decode_source(source_bytes)¶
Decode the given bytes representing source code and return it as a string with universal newlines (as required by
importlib.abc.InspectLoader.get_source()).Adicionado na versão 3.4.
- importlib.util.resolve_name(name, package)¶
Resolve a relative module name to an absolute one.
If name has no leading dots, then name is simply returned. This allows for usage such as
importlib.util.resolve_name('sys', __spec__.parent)without doing a check to see if the package argument is needed.ImportErroris raised if name is a relative module name but package is a false value (e.g.Noneor the empty string).ImportErroris also raised if a relative name would escape its containing package (e.g. requesting..baconfrom within thespampackage).Adicionado na versão 3.3.
Alterado na versão 3.9: To improve consistency with import statements, raise
ImportErrorinstead ofValueErrorfor invalid relative import attempts.
- importlib.util.find_spec(name, package=None)¶
Find the spec for a module, optionally relative to the specified package name. If the module is in
sys.modules, thensys.modules[name].__spec__is returned (unless the spec would beNoneor is not set, in which caseValueErroris raised). Otherwise a search usingsys.meta_pathis done.Noneis returned if no spec is found.If name is for a submodule (contains a dot), the parent module is automatically imported.
name and package work the same as for
import_module().Adicionado na versão 3.4.
Alterado na versão 3.7: Raises
ModuleNotFoundErrorinstead ofAttributeErrorif package is in fact not a package (i.e. lacks a__path__attribute).
- importlib.util.module_from_spec(spec)¶
Create a new module based on spec and
spec.loader.create_module.If
spec.loader.create_moduledoes not returnNone, then any pre-existing attributes will not be reset. Also, noAttributeErrorwill be raised if triggered while accessing spec or setting an attribute on the module.This function is preferred over using
types.ModuleTypeto create a new module as spec is used to set as many import-controlled attributes on the module as possible.Adicionado na versão 3.5.
- importlib.util.spec_from_loader(name, loader, *, origin=None, is_package=None)¶
A factory function for creating a
ModuleSpecinstance based on a loader. The parameters have the same meaning as they do for ModuleSpec. The function uses available loader APIs, such asInspectLoader.is_package(), to fill in any missing information on the spec.Adicionado na versão 3.4.
- importlib.util.spec_from_file_location(name, location, *, loader=None, submodule_search_locations=None)¶
A factory function for creating a
ModuleSpecinstance based on the path to a file. Missing information will be filled in on the spec by making use of loader APIs and by the implication that the module will be file-based.Adicionado na versão 3.4.
Alterado na versão 3.6: Aceita um objeto caminho ou similar.
- importlib.util.source_hash(source_bytes)¶
Return the hash of source_bytes as bytes. A hash-based
.pycfile embeds thesource_hash()of the corresponding source file’s contents in its header.Adicionado na versão 3.7.
- importlib.util._incompatible_extension_module_restrictions(*, disable_check)¶
A context manager that can temporarily skip the compatibility check for extension modules. By default the check is enabled and will fail when a single-phase init module is imported in a subinterpreter. It will also fail for a multi-phase init module that doesn’t explicitly support a per-interpreter GIL, when imported in an interpreter with its own GIL.
Note that this function is meant to accommodate an unusual case; one which is likely to eventually go away. There’s is a pretty good chance this is not what you were looking for.
You can get the same effect as this function by implementing the basic interface of multi-phase init (PEP 489) and lying about support for multiple interpreters (or per-interpreter GIL).
Aviso
Using this function to disable the check can lead to unexpected behavior and even crashes. It should only be used during extension module development.
Adicionado na versão 3.12.
- class importlib.util.LazyLoader(loader)¶
A class which postpones the execution of the loader of a module until the module has an attribute accessed.
This class only works with loaders that define
exec_module()as control over what module type is used for the module is required. For those same reasons, the loader’screate_module()method must returnNoneor a type for which its__class__attribute can be mutated along with not using slots. Finally, modules which substitute the object placed intosys.moduleswill not work as there is no way to properly replace the module references throughout the interpreter safely;ValueErroris raised if such a substitution is detected.Nota
For projects where startup time is critical, this class allows for potentially minimizing the cost of loading a module if it is never used. For projects where startup time is not essential then use of this class is heavily discouraged due to error messages created during loading being postponed and thus occurring out of context.
Adicionado na versão 3.5.
Alterado na versão 3.6: Began calling
create_module(), removing the compatibility warning forimportlib.machinery.BuiltinImporterandimportlib.machinery.ExtensionFileLoader.- classmethod factory(loader)¶
A class method which returns a callable that creates a lazy loader. This is meant to be used in situations where the loader is passed by class instead of by instance.
suffixes = importlib.machinery.SOURCE_SUFFIXES loader = importlib.machinery.SourceFileLoader lazy_loader = importlib.util.LazyLoader.factory(loader) finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
Exemplos¶
Importing programmatically¶
To programmatically import a module, use importlib.import_module().
import importlib
itertools = importlib.import_module('itertools')
Checando se o módulo pode ser importado¶
If you need to find out if a module can be imported without actually doing the
import, then you should use importlib.util.find_spec().
Note that if name is a submodule (contains a dot),
importlib.util.find_spec() will import the parent module.
import importlib.util
import sys
# For illustrative purposes.
name = 'itertools'
if name in sys.modules:
print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
# If you chose to perform the actual import ...
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
print(f"{name!r} has been imported")
else:
print(f"can't find the {name!r} module")
Importa o arquivo de origem diretamente¶
To import a Python source file directly, use the following recipe:
import importlib.util
import sys
# For illustrative purposes.
import tokenize
file_path = tokenize.__file__
module_name = tokenize.__name__
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
Implementing lazy imports¶
The example below shows how to implement lazy imports:
>>> import importlib.util
>>> import sys
>>> def lazy_import(name):
... spec = importlib.util.find_spec(name)
... loader = importlib.util.LazyLoader(spec.loader)
... spec.loader = loader
... module = importlib.util.module_from_spec(spec)
... sys.modules[name] = module
... loader.exec_module(module)
... return module
...
>>> lazy_typing = lazy_import("typing")
>>> #lazy_typing is a real module object,
>>> #but it is not loaded in memory yet.
>>> lazy_typing.TYPE_CHECKING
False
Setting up an importer¶
For deep customizations of import, you typically want to implement an
importer. This means managing both the finder and loader
side of things. For finders there are two flavours to choose from depending on
your needs: a meta path finder or a path entry finder. The
former is what you would put on sys.meta_path while the latter is what
you create using a path entry hook on sys.path_hooks which works
with sys.path entries to potentially create a finder. This example will
show you how to register your own importers so that import will use them (for
creating an importer for yourself, read the documentation for the appropriate
classes defined within this package):
import importlib.machinery
import sys
# For illustrative purposes only.
SpamMetaPathFinder = importlib.machinery.PathFinder
SpamPathEntryFinder = importlib.machinery.FileFinder
loader_details = (importlib.machinery.SourceFileLoader,
importlib.machinery.SOURCE_SUFFIXES)
# Setting up a meta path finder.
# Make sure to put the finder in the proper location in the list in terms of
# priority.
sys.meta_path.append(SpamMetaPathFinder)
# Setting up a path entry finder.
# Make sure to put the path hook in the proper location in the list in terms
# of priority.
sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))
Approximating importlib.import_module()¶
Import itself is implemented in Python code, making it possible to
expose most of the import machinery through importlib. The following
helps illustrate the various APIs that importlib exposes by providing an
approximate implementation of
importlib.import_module():
import importlib.util
import sys
def import_module(name, package=None):
"""An approximate implementation of import."""
absolute_name = importlib.util.resolve_name(name, package)
try:
return sys.modules[absolute_name]
except KeyError:
pass
path = None
if '.' in absolute_name:
parent_name, _, child_name = absolute_name.rpartition('.')
parent_module = import_module(parent_name)
path = parent_module.__spec__.submodule_search_locations
for finder in sys.meta_path:
spec = finder.find_spec(absolute_name, path)
if spec is not None:
break
else:
msg = f'No module named {absolute_name!r}'
raise ModuleNotFoundError(msg, name=absolute_name)
module = importlib.util.module_from_spec(spec)
sys.modules[absolute_name] = module
spec.loader.exec_module(module)
if path is not None:
setattr(parent_module, child_name, module)
return module