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:

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 None em sys.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.mod ou ..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 de importlib.__import__(). Isso significa que toda a semântica da função é derivada de importlib.__import__(). A diferença mais importante entre essas duas funções é que import_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 implementar invalidate_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.path diferente 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 init dos 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 try ele 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__, builtins e 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 fromimport …, chamar reload() para o outro módulo não redefine os objetos importados dele – uma maneira de contornar isso é executar novamente a instrução from, outra é usar import e 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 um ModuleSpec.

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, None será 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 implementar MetaPathFinders concretos.

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 em sys.meta_path.

Alterado na versão 3.4: Retorna None quando chamado em vez de NotImplemented.

class importlib.abc.PathEntryFinder

Uma classe base abstrata que representa um localizador de entrada de caminho. Embora tenha algumas semelhanças com MetaPathFinder, PathEntryFinder deve ser usado apenas dentro do subsistema de importação baseado em caminho fornecido por importlib.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, None será 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 implementar PathEntryFinders concretos.

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 por importlib.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, ImportError será 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 em sys.modules antes 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 de sys.modules; módulos já em sys.modules antes 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 que sys.path mas 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 ImportError quando chamado em vez de NotImplementedError. Funcionalidade fornecida quando exec_module() está disponível.

Obsoleto desde a versão 3.4: A API recomendada para carregar um módulo é exec_module() (e create_module()). Os carregadores devem implementá-lo em vez de load_module(). O mecanismo de importação cuida de todas as outras responsabilidades de load_module() quando exec_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. OSError deve 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 OSError em vez de NotImplementedError.

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 None se o módulo não tiver um objeto código (como seria o caso, por exemplo, para um módulo embutido). Levanta um ImportError se 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. Returns None if no source is available (e.g. a built-in module). Raises ImportError if the loader cannot find the module specified.

Alterado na versão 3.4: Raises ImportError instead of NotImplementedError.

is_package(fullname)

An optional method to return a true value if the module is a package, a false value otherwise. ImportError is raised if the loader cannot find the module.

Alterado na versão 3.4: Raises ImportError instead of NotImplementedError.

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 InspectLoader that, 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, ImportError is 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 ImportError instead of NotImplementedError.

class importlib.abc.FileLoader(fullname, path)

An abstract base class which inherits from ResourceLoader and ExecutionLoader, providing concrete implementations of ResourceLoader.get_data() and ExecutionLoader.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_filename(fullname)

Returns path.

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 ResourceLoader and ExecutionLoader, requiring the implementation of:

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 dict containing 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, OSError is raised.

Adicionado na versão 3.3.

Alterado na versão 3.4: Raise OSError instead of NotImplementedError.

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. Raise OSError if the path cannot be handled.

Alterado na versão 3.4: Raise OSError instead of NotImplementedError.

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 NotImplementedError when 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 by ExecutionLoader.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.

From the perspective of this ABC, a resource is a binary artifact that is shipped within a package. Typically this is something like a data file that lives next to the __init__.py file of the package. The purpose of this class is to help abstract out the accessing of such data files so that it does not matter if the package and its data file(s) are stored e.g. in a zip file versus on the file system.

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 retornar None. 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.

Deprecated since version 3.12, will be removed in version 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 True se 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.Path adequados 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.

Deprecated since version 3.12, will be removed in version 3.14: Use importlib.resources.abc.Traversable.

name

Abstrato. O nome base deste objeto sem nenhuma referência pai.

abstractmethod iterdir()

Yield Traversable objects in self.

abstractmethod is_dir()

Return True if self is a directory.

abstractmethod is_file()

Return True if self is a file.

abstractmethod joinpath(child)

Return Traversable child in self.

abstractmethod __truediv__(child)

Return Traversable child in self.

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 self as bytes.

read_text(encoding=None)

Read contents of self as text.

class importlib.abc.TraversableResources

Uma classe base abstrata para leitores de recursos capaz de servir a interface importlib.resources.files(). Subclasse importlib.resources.abc.ResourceReader e fornece implementações concretas dos métodos abstratos de importlib.resources.abc.ResourceReader. Portanto, qualquer carregador que forneça importlib.abc.TraversableResources também fornece ResourceReader.

Espera-se que os carregadores que desejam oferecer suporte à leitura de recursos implementem essa interface.

Adicionado na versão 3.9.

Deprecated since version 3.12, will be removed in version 3.14: Use importlib.resources.abc.TraversableResources.

abstractmethod files()

Retorna um objeto importlib.resources.abc.Traversable para 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_SUFFIXES instead.

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_SUFFIXES instead.

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 the importlib.abc.MetaPathFinder and importlib.abc.InspectLoader ABCs.

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() and Loader.exec_module()

class importlib.machinery.FrozenImporter

An importer for frozen modules. This class implements the importlib.abc.MetaPathFinder and importlib.abc.InspectLoader ABCs.

Only class methods are defined by this class to alleviate the need for instantiation.

Alterado na versão 3.4: Gained create_module() and exec_module() methods.

class importlib.machinery.WindowsRegistryFinder

Finder for modules declared in the Windows registry. This class implements the importlib.abc.MetaPathFinder ABC.

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 site configuration instead. Future versions of Python may not enable this finder by default.

class importlib.machinery.PathFinder

A Finder for sys.path and package __path__ attributes. This class implements the importlib.abc.MetaPathFinder ABC.

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.path or, if defined, on path. For each path entry that is searched, sys.path_importer_cache is 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 in sys.path_importer_cache, then sys.path_hooks is searched for a finder for the path entry and, if found, is stored in sys.path_importer_cache along with being queried about the module. If no finder is ever found then None is 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 None is returned but no value is cached in sys.path_importer_cache.

classmethod invalidate_caches()

Calls importlib.abc.PathEntryFinder.invalidate_caches() on all finders stored in sys.path_importer_cache that define the method. Otherwise entries in sys.path_importer_cache set to None are deleted.

Alterado na versão 3.7: Entries of None in sys.path_importer_cache are deleted.

Alterado na versão 3.4: Calls objects in sys.path_hooks with the current working directory for '' (i.e. the empty string).

class importlib.machinery.FileFinder(path, *loader_details)

A concrete implementation of importlib.abc.PathEntryFinder which 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 of FileFinder is 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, ImportError is raised.

class importlib.machinery.SourceFileLoader(fullname, path)

A concrete implementation of importlib.abc.SourceLoader by subclassing importlib.abc.FileLoader and 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.

is_package(fullname)

Return True if path appears to be for a package.

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.FileLoader which 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.

is_package(fullname)

Determines if the module is a package based on path.

get_code(fullname)

Returns the code object for name created from path.

get_source(fullname)

Returns None as 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.ExecutionLoader for 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 True if the file path points to a package’s __init__ module based on EXTENSION_SUFFIXES.

get_code(fullname)

Returns None as extension modules lack a code object.

get_source(fullname)

Returns None as extension modules do not have source code.

get_filename(fullname)

Returns path.

Adicionado na versão 3.4.

class importlib.machinery.NamespaceLoader(name, path, path_finder)

A concrete implementation of importlib.abc.InspectLoader for 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

(__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 None for 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

(__cached__)

The filename of a compiled version of the module’s code. The finder should always set this attribute but it may be None for modules that do not need compiled code stored.

parent

(__package__)

(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
True if the spec’s origin refers to a loadable location,

False otherwise. This value impacts how origin is interpreted and how the module’s __file__ is populated.

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.py the return value would be /foo/bar/__pycache__/baz.cpython-32.pyc for Python 3.2. The cpython-32 string comes from the current magic tag (see get_tag(); if sys.implementation.cache_tag is not defined then NotImplementedError will 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.py with an optimization of '' will result in a bytecode path of /foo/bar/__pycache__/baz.cpython-32.pyc. None causes the interpreter’s optimization level to be used. Any other value’s string representation is used, so /foo/bar/baz.py with an optimization of 2 will lead to the bytecode path of /foo/bar/__pycache__/baz.cpython-32.opt-2.pyc. The string representation of optimization can only be alphanumeric, else ValueError is raised.

The debug_override parameter is deprecated and can be used to override the system’s value for __debug__. A True value is the equivalent of setting optimization to the empty string. A False value is the same as setting optimization to 1. If both debug_override an optimization are not None then TypeError is 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.pyc the 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, a ValueError is raised. If sys.implementation.cache_tag is not defined, NotImplementedError is 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.

ImportError is raised if name is a relative module name but package is a false value (e.g. None or the empty string). ImportError is also raised if a relative name would escape its containing package (e.g. requesting ..bacon from within the spam package).

Adicionado na versão 3.3.

Alterado na versão 3.9: To improve consistency with import statements, raise ImportError instead of ValueError for 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, then sys.modules[name].__spec__ is returned (unless the spec would be None or is not set, in which case ValueError is raised). Otherwise a search using sys.meta_path is done. None is 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 ModuleNotFoundError instead of AttributeError if 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_module does not return None, then any pre-existing attributes will not be reset. Also, no AttributeError will be raised if triggered while accessing spec or setting an attribute on the module.

This function is preferred over using types.ModuleType to 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 ModuleSpec instance based on a loader. The parameters have the same meaning as they do for ModuleSpec. The function uses available loader APIs, such as InspectLoader.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 ModuleSpec instance 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 .pyc file embeds the source_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’s create_module() method must return None or a type for which its __class__ attribute can be mutated along with not using slots. Finally, modules which substitute the object placed into sys.modules will not work as there is no way to properly replace the module references throughout the interpreter safely; ValueError is 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 for importlib.machinery.BuiltinImporter and importlib.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