Re: Loading Resources From a Python Module/Package
Paul Moore <[email protected]> Sat, 31 Jan 2015 15:46:33 +0000
| Newsgroups | gmane.comp.python.import |
|---|---|
| Message-ID | <CACac1F-+Dd-QzrDvdUZOr=wwO+q5YRTeYCskXnCRvbx4GOPHqA@mail.gmail.com> |
On 31 January 2015 at 15:34, Donald Stufft <[email protected]> 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