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

Paul Moore p.f.moore at gmail.com
Sat Jan 31 16:46:33 CET 2015


On 31 January 2015 at 15:34, Donald Stufft <donald at stufft.io> wrote:
> It seems obvious to me that requiring a full path like that is the wrong way
> to expect people to work with constructing full paths for resources. It
> would be similar to expecting people to do ``import
> /data/foo.zip/submodule``. The import system should be abstracting all of
> that away for them.

Note the example in PEP 302:

    d = os.path.dirname(__file__)
    data = __loader__.get_data(os.path.join(d, "logo.gif"))

The parallel is with the historical filesystem-only approach,

    d = os.path.dirname(__file__)
    with open(os.path.join(d, "logo.gif"), 'rb') as f:
        data = f.read()

You *don't* want to use a relative pathname then in this case, so the
loader protocol is designed to follow that usage. As Brett says,
__file__ can have non-filesystem "token" elements (e.g., a zipfile
name) if necessary.

It's certainly possible to add a new API that loads resources based on
a relative name, but you'd have to specify relative to *what*.
get_data explicitly ducks out of making that decision.

Paul


More information about the Import-SIG mailing list