[Tutor] How (and whether I should) use pkgutil.get_data()?

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Jan 18 06:12:12 EST 2016


On 17 January 2016 at 23:37, boB Stepp <robertvstepp at gmail.com> wrote:
> 1)  Is using pkgutil.get_data() the way I should be reading my data files?

Generally yes, although it may be unnecessary. The main purpose of
pkgutil.get_data is to transparently handle the case where your
packages are imported from a zip file. The initial motivation for this
was setuptools eggs but there are other reasons you might want to
import your code from a zip file.

> 2)  The book says that this method will return "...a byte string
> containing the raw contents of the file." (From page 409) Can I do all
> of the normal things on this returned object that I could do if I used
> "with open..."?  Is it iterable?  [OK, I confess up front.  I am being
> lazy here.  I *could* create a file and try this out to see what
> happens, so I will understand if I get chided (or worse!).]

Just try it out :)

> 3)  Should I be using relative imports in my projects?

I don't use relative imports. The supposed advantage of relative
imports is that you can easily move a package to a different location
in the import hierarchy. For example if you have a package called
stuff and the modules inside stuff use relative imports to access each
other then you could move stuff inside another package called things
and have it be a package called things.stuff without needing to change
the import lines.

Personally I think that fixing up a few import lines is no big deal.
I'd rather choose exactly where things is going to go in the import
hierarchy and be done with it. If I need to move it into another
package then I'll have to change the import statements inside things
but that's easy to do. So I prefer absolute imports since they're less
ambiguous.

--
Oscar


More information about the Tutor mailing list