Package: custom-imports
custom_importsTools to hook into Python'simportsyntax.These hooks can allow you toimportconfig files,
modules written in different languages,
or even create entirely virtual modules.Basic UsageIncluded incustom_importsare some sample importers,json_importer,cfg_importer,ini_importer, andCSVImporter.When registered, these importers allow you toimportthe corresponding file
types as though they were Python modules.For example,server_config.ini[environment]server_name=proddebug=no[database]host=https://example.comport=27017username=<username>password=<password>connections.pyimportserver_configifserver_config.environment.debug:setup_logging()db_client=DatabaseClient(**server_config.database)RegistrationImporters can be registered withimporter.register().fromcustom_importsimportini_importerini_importer.register()importserver_configAlternatively, you can use the importer as a context manager:withini_importer:importserver_configand the importer deregisters itself once thewithblock has been terminated.DeregistrationImport hooks modifysys.meta_path, which is global, so it's a bad idea to
leave your importers hanging around if you intend for your code to be used as
part of a larger project.For example, if two modules use different flavors of CSV, then one of them is
going to be unable to import their CSV files.Thankfully, once a module has been imported for the first time, it is stored in
the module cache, and so you no longer need the importer.To keep yoursys.meta_pathclear, you can deregister an importer once you're
finished with it.
This can be done either withimporter.deregister(), or by using the importer
as a context manager.Environment-wide SetupOn the other hand, it can be ugly needing to have a non-import(the importer
registration) before animport(your custom module type).If youarethe only project needing to use this Python environment, then you
can register an importer environment-wide.
To do so, create acustom-imports.pthfile in your environment'ssite-packagesfolder with the following contents:import custom_imports; custom_imports.ini_importer.register()For multiple importers, repeat the entire line, replacing the importer used.If your project uses an importer in this way, be sure to include this step in
your project's environment setup instructions.ReferenceFinderModuleFinders search for a module among the various paths available.
If it finds a module, it returns a "locator" for that module,
which can be any non-NonePython object that contains all the
information required to immediately locate the module.
If it fails to find a module, it returnsNone.ModuleFinders do not attempt to construct the module,
they only find their locators.CustomFinders should inherit fromFinderand override thefind_module_locatormethod.Two moduleFinders are provided by default:SimpleFinderA basic Finder class.SimpleFinder(locate_module=func,)Finds a module locator by callingfunc(fullname, path, target).FileModuleExtensionFinderFinder for file based modules by file extensions.A file based module is a module that is generated from a single file.FileModuleExtensionFinder(ext)This Finder interprets a module's name as a filename, with extensionext.
Parent modules are interpreted as directories.This provides a relative path, which is searched for on the standard module
search path. If a file with that relative path is found, then the absolutePathof that file is returned as its module locator.LoaderModuleLoaders take module locators, and construct the module at that location.CustomLoaders should inherit fromLoaderand override thecreate_moduleandexec_modulemethods.Two moduleLoaders are provided by default:SimpleLoaderA basic Loader class.SimpleLoader(module_type=cls,module_type_kwargs=kwargs,load_module=func,)Creates an empty module by calling the equivalent ofcls(**kwargs),
and executes it by callingfunc(module, module_locator).FileModuleLoaderLoader for file based modules.A file based module is a module that is generated from a single file.FileModuleLoader(module_type=cls,module_type_kwargs=kwargs,read_module=func,)This Loader takes aPathto the file to be loaded as its module locator,
creates an empty module by calling the equivalent ofcls(**kwargs),
and executes it by callingfunc(module, file).The file handle passed tofuncis closed afterfuncterminates.ImporterA basic Importer class.Importer(finder=finder,loader=loader,)When registered, thisImporteroverloadsimportsyntax to additionally
attempt to usefinderto find modules, andloaderto load them.Register anImporterwithimporter.register().
Deregister anImporterwithimporter.deregister().May also be used as a context manager:withfoo_importer:importfoowith the importer registering itself at the start of the block, and
deregistering itself at the end.Sample importersjson_importerWhen registered, imports.jsonfiles asdicts.cfg_importerWhen registered, import.cfgfiles usingConfigParser,
with attribute notation.ini_importerWhen registered, import.inifiles usingConfigParser,
with attribute notation.CSVImporterWhen instantiated and registered, import.csvfiles using the provided CSV reader.CSVImporter(csv_reader=csv_reader,csv_reader_kwargs=kwargs,)This importer loads a module using the result ofcsv_reader(file, **kwargs).csv_readershould be a CSV reader class (for example,csv.reader, orcsv.DictReader).