Help with modules/packages.
mefjr75 at hotmail.com
Sat Dec 4 20:14:54 CET 2004
"Christopher J. Bottaro" <cjbottaro at alumni.cs.utexas.edu> wrote in message
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.
> 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
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:
# this __init__.py file makes this dir a python package
classA = CJB.ClassA.ClassA
classB = CJB.ClassB.ClassB
# end of __init__.py
Now all you do is import.
> 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