Relative Imports, why the hell is it so hard?
R. David Murray
rdmurray at bitdance.com
Tue Mar 24 13:01:01 CET 2009
Top posting corrected for clarity.
CinnamonDonkey <CinnamonDonkey at googlemail.com> wrote:
> On 23 Mar, 18:57, bearophileH... at lycos.com wrote:
> > CinnamonDonkey:
> > >what makes something a package?
> > If you don't know what a package is, then maybe you don't need
> > packages.
> > In your project is it possible to avoid using packages and just use
> > modules in the same directory?
> > Bye,
> > bearophile
> Hi Bearophile,
> Thanx for taking the time to post a response but I am afraid I feel
> the need to point out that it is exactly this kind of response that I
> find un-helpful. It is neither constructive nor educational.
> It's a bit like saying "If you don't know what a function is, then
> maybe you don't need it. ... have you tried having a single block of
> The point of people coming to these forums is to LEARN and share
> knowledge. Perhaps it's not the best solution for me right now but
> without trying it I won't know when or how to apply it as a solution.
> By the way, my project has about 50 files (modules) in it with a lot
> of shared code that could be used across other projects... seems as
> good a reason as any to try packages out ;-)
> Thanx anyway :)
I think bearophile could have left out the first sentence, but otherwise
his question is perfectly sensible. If you have a bunch of independent
modules, then you don't need to put them in packages. Your example
only showed one module file in each package...I understand now that was
just for simplicity of the example, but we had no way of knowing that.
We've had newbies come in and think they _need_ to put a module file into
a subpackage even when they'd only have one module file per subdirectory
and they don't really know what a package is...thus bearophile's (perhaps
poorly phrased) question.
Now that you know what packages are and what the restrictions on relative
imports are, and you've told us that you have '50 modules' with a lot
of shared code that 'could be used across other projects', perhaps you
see why relative imports are generally discouraged. If you use only
relative imports, the code _can't_ be shared across multiple projects,
because all that project code would have to be in one monster package,
and not be separate projects at all.
So now you'll know better where it makes Pythonic (as opposed to C++)
sense to use it and where not.
R. David Murray http://www.bitdance.com
More information about the Python-list