Skip to main content

custom_imports

Tools to hook into Python's import syntax.

These hooks can allow you to import config files, modules written in different languages, or even create entirely virtual modules.

Basic Usage

Included in custom_imports are some sample importers, json_importer, cfg_importer, ini_importer, and CSVImporter.

When registered, these importers allow you to import the corresponding file types as though they were Python modules.

For example,

server_config.ini

[environment]
server_name = prod
debug = no

[database]
host = https://example.com
port = 27017
username = <username>
password = <password>

connections.py

import server_config

if server_config.environment.debug:
    setup_logging()

db_client = DatabaseClient(**server_config.database)

Registration

Importers can be registered with importer.register().

from custom_imports import ini_importer

ini_importer.register()

import server_config

Alternatively, you can use the importer as a context manager:

with ini_importer:
    import server_config

and the importer deregisters itself once the with block has been terminated.

Deregistration

Import hooks modify sys.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 your sys.meta_path clear, you can deregister an importer once you're finished with it. This can be done either with importer.deregister(), or by using the importer as a context manager.

Environment-wide Setup

On the other hand, it can be ugly needing to have a non-import (the importer registration) before an import (your custom module type).

If you are the only project needing to use this Python environment, then you can register an importer environment-wide. To do so, create a custom-imports.pth file in your environment's site-packages folder 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.

Reference

Finder

Module Finders 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-None Python object that contains all the information required to immediately locate the module. If it fails to find a module, it returns None.

Module Finders do not attempt to construct the module, they only find their locators.

Custom Finders should inherit from Finder and override the find_module_locator method.

Two module Finders are provided by default:

SimpleFinder

A basic Finder class.

SimpleFinder(
    locate_module=func,
)

Finds a module locator by calling func(fullname, path, target).

FileModuleExtensionFinder

Finder 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 extension ext. 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 absolute Path of that file is returned as its module locator.

Loader

Module Loaders take module locators, and construct the module at that location.

Custom Loaders should inherit from Loader and override the create_module and exec_module methods.

Two module Loaders are provided by default:

SimpleLoader

A basic Loader class.

SimpleLoader(
    module_type=cls,
    module_type_kwargs=kwargs,
    load_module=func,
)

Creates an empty module by calling the equivalent of cls(**kwargs), and executes it by calling func(module, module_locator).

FileModuleLoader

Loader 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 a Path to the file to be loaded as its module locator, creates an empty module by calling the equivalent of cls(**kwargs), and executes it by calling func(module, file).

The file handle passed to func is closed after func terminates.

Importer

A basic Importer class.

Importer(
    finder=finder,
    loader=loader,
)

When registered, this Importer overloads import syntax to additionally attempt to use finder to find modules, and loader to load them.

Register an Importer with importer.register(). Deregister an Importer with importer.deregister().

May also be used as a context manager:

with foo_importer:
    import foo

with the importer registering itself at the start of the block, and deregistering itself at the end.

Sample importers

json_importer

When registered, imports .json files as dicts.

cfg_importer

When registered, import .cfg files using ConfigParser, with attribute notation.

ini_importer

When registered, import .ini files using ConfigParser, with attribute notation.

CSVImporter

When instantiated and registered, import .csv files using the provided CSV reader.

CSVImporter(
    csv_reader=csv_reader,
    csv_reader_kwargs=kwargs,
)

This importer loads a module using the result of csv_reader(file, **kwargs).

csv_reader should be a CSV reader class (for example, csv.reader, or csv.DictReader).

Metadata

Release files for custom-imports 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for custom-imports 1.0.0
File Size Uploaded Provenance
custom_imports-1.0.0.tar.gz 10.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for custom-imports 1.0.0
File Interpreter ABI Platform
custom_imports-1.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 23.4 kB

Release files / custom_imports-1.0.0.tar.gz

Download URL custom_imports-1.0.0.tar.gz
Size 10.1 kB
Tags Source
SHA-256 checksum
How to use checksums
cf5bf1365f8f9e4f078020a5a5d0d81f78df8f3f91431c52a0f9785c5890e410
BLAKE2b-256 checksum
How to use checksums
c2a95c969a7875d63025917724a6a628212d55e980004617fa9e77b646ae8662
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.2

Release files / custom_imports-1.0.0-py3-none-any.whl

Download URL custom_imports-1.0.0-py3-none-any.whl
Size 13.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cce3245172e05a9d6d2858b338fbc689e3055b2e740338cd5a96e79608ed0351
BLAKE2b-256 checksum
How to use checksums
25985b1c86d984b40ca3e2ce2ba7216bd997e6a2bf2aa4fedc6e6f0bf07da1a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.2

Security for custom-imports 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page