[Import-SIG] Loading Resources From a Python Module/Package

Barry Warsaw barry at python.org
Sun Feb 1 22:43:05 CET 2015


On Jan 31, 2015, at 06:05 PM, Donald Stufft wrote:

>How about this, instead here’s the top level APIs I want:
>https://bpaste.net/show/0c490aa07c07 <https://bpaste.net/show/0c490aa07c07>

I like almost all of this.  It nicely handles the case where you want a longer
lived file resource (via resource_filename()) and don't care about its life
cycle, and where you want to clean up the resource asap (via
ResourceFilename).

If I didn't skim over something critical, I think Nick's introduction of the
term "resource anchor" is a useful one.  Given that a resource anchor can be

1. a string containing the dotted module path to a package
2. an actual module object
3. a module spec

the term better describes the first argument in these APIs than "package".

I still would like a generalization of resource_stream() that allows opening
in text mode with a given encoding, e.g.

# importlib.resources

def open(resource_anchor, resource, encoding=None):
    """
    resource_anchor is a 1) str that represents a dot seperated import module;
    2) a module object; 3) a module spec.

    resource is a str that represents a relative to package resource.

    Return a file like object (but it may be an io.BytesIO) where read() yields
    bytes.  If encoding is given, read() yields strs.

    No `mode` is provided, as this is a read-only interface.
    """

I can build this out of the pieces already described:

from importlib.resources import ResourceFilename

with ResourceFilename('my.package', 'foo.cfg') as filename:
    with open(filename, 'r', encoding='utf-8') as fp:
        my_config = fp.read()


but it's certainly not as convenient as:

with importlib.resources.open('my.package', 'foo.cfg', 'utf-8') as fp:
    my_config = fp.read()

(oh, and is anybody else tired of writing `open('file', 'r', encoding='utf-8')`
literally *everywhere*, and which it were just the default already? ;)

Cheers,
-Barry


More information about the Import-SIG mailing list