opening a file using a relative path from a subclass in a package
fredrik at pythonware.com
Wed Dec 7 23:35:55 CET 2005
"spike grobstein" write:
> I understand why it wasn't working and it makes sense based on the
> structure of namespaces that python defines, however, I'm just
> surprised that there isn't some kind of built-in facility for dealing
> with these types of things.
> Module packages are a spectacular idea, it is just kinda easy to get
> confused when you start spaghettifying your imports with multiple
> directories and whatnot.
> My whole reason for wanting to do this is that I've written a program
> that contains a framework for extending the application. It's got a
> plugin-like module package framework that allows endusers to add new
> functionality, and I'd like it to not only be as trivial as possible to
> create new plugins (by simply plugging in values to a new subclass),
> but to also repeat as little code as possible (the DRY principal; don't
> repeat yourself)
> I toyed with the idea of using generic filenames (icon.png,
> description.rtf, etc), but ultimately decided against it when I thought
> about things I'd want to implement in the future.
why not just add an attribute to each subclass which tells the baseclass
where to look for the files ? if you let the attribute be either a directory
or a file in the directory, you can do
location = __file__
in most subclasses, but you can also do fancier stuff, like:
for p in ".", __file__, "/usr/local/mysystem/config/root":
if os.path.isfile(os.path.join(p, "config.xml")):
self.location = p # found it!
the superclass would then simply use self.location to locate stuff:
location = "."
# location can be either a directory or a file in the
# config directory
location = self.location
if os.path.isfile(location): # use the directory this file is in
location = os.path.dirname(self.location)
data = ConfigLoader(os.path.join(location, "config.xml"))
More information about the Python-list