Help with modules/packages.

M.E.Farmer mefjr75 at
Sat Dec 4 20:14:54 CET 2004

"Christopher J. Bottaro" <cjbottaro at> wrote in message 
Hello Christopher,
    You probably know this but I will mention it here for
completeness, if you want to be able to make a dir a package you also
need to add an in the folder you wish to import from. The makes the dir a package.
<dir> CJB
> I want to be able to say stuff like "import CJB.ClassA" and "import
> CJB.ClassB" then say "c = CJB.ClassA()" or "c = CJB.ClassB()".  CJB will be
> a directory containing files "" and "".
Let us clarify a few things first.
"import CJB.ClassA" imports MODULE ClassA from PACKAGE CJB into the
namespace, but it is a MODULE and therefore not callable ;)
"c = CJB.ClassA()" is attempting to call the module ClassA , but you
want to call a ClassA CLASS in the ClassA MODULE
BTW the names you have used makes this less understandable.
Maybe CJB.ModuleA.ClassA() would make this clearer.

>         Now that I think about it, that can't work because Python allows you import
> different things from the same module (file).  If I said "import
> CJB.ClassA", I'd have to instantiate ClassA like "c = CJB.ClassA.ClassA()".
> I guess I could say "from CJB.ClassA import ClassA", but then I'd
> instantiate like "c = ClassA()".  What I really want is to say "c =
> CJB.ClassA()" that possible?

Yes it is possible.
I will show you how, BUT I must mention that it makes it VERY UNCLEAR
where the code comes from. The beauty of packages is code seperation
and modularity, and you are going to find aliasing makes for an
interesting debug session trying to guess where it all went wrong. You
should probably just bite the bullet and use
name = package.module.class it is easier to grasp 1 year from now and
makes it easier for others to read. The time you saved typing the
extra letters is less then the time you will spend looking at your
code. READABILITY counts.

Ok now onto the imports.
This is just *A* way to do it, there are others.
In your you need to do your imports and aliasing:

# this file makes this dir a python package
import CJB.ClassA
import CJB.ClassB
classA = CJB.ClassA.ClassA
classB = CJB.ClassB.ClassB
# end of

Now all you do is import.

import CJB

> Is my understand of modules/packages correct or am I way off?

Not to far off :)

> Thanks for the help.


More information about the Python-list mailing list