Help with modules/packages.

M.E.Farmer mefjr75 at hotmail.com
Sat Dec 4 14:14:54 EST 2004


"Christopher J. Bottaro" <cjbottaro at alumni.cs.utexas.edu> 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 __init__.py in the folder you wish to import from. The
__init__.py makes the dir a package.
Example:
<dir> CJB
<file> __init__.py
<file> ClassA.py
<file> ClassB.py
 
> 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 "ClassA.py" and "ClassB.py".
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
"c=CJB.ClassA.ClassA()"
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()"...is 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 __init__.py you need to do your imports and aliasing:

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

Now all you do is import.

import CJB
dir(CJB)
CJB.ClassA()
CJB.ClassB()

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

Not to far off :)

> Thanks for the help.

HTH,
    M.E.Farmer



More information about the Python-list mailing list