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

boB Stepp robertvstepp at gmail.com
Sun Jan 17 18:37:39 EST 2016


>From "Python Cookbook, 3rd Ed." by David Beazley and Brian K. Jones,
the authors recommend using pkgutil.get_data() to obtain the contents
of data files.  Normally I would use "with open..." giving my expected
file's location, but the authors claim that using pkgutil.get_data()
is a more robust way to do things due to the differences in how
packages get installed and used.  I have not thought that far ahead on
distributing my work.  So far I have been using my projects on the
machines on which I develop them, or manually copy the source code to
another nearby machine, manually making any adjustments in my
program's "home" directory.  (Typically my main.py program has a
single variable that sets the home location for the project, so I only
need to manually change it in this one place.)

But these projects in development for my wife's classes where they
have a variety of OS's has me rethinking this approach.  The book's
authors also seem to recommend relative addressing for importing a
program's modules.  That sounds nice in terms of being independent of
where the project gets installed, but I don't find "dots" to be very
descriptive!  So, some questions:

1)  Is using pkgutil.get_data() the way I should be reading my data files?

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!).]

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

TIA!

-- 
boB


More information about the Tutor mailing list