Help with modules/packages.

Nick Coghlan ncoghlan at
Sun Dec 5 02:46:45 CET 2004

Christopher J. Bottaro wrote:
> Hello,
>         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 "".
>         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?
> Is my understand of modules/packages correct or am I way off?

To collapse the namespace locally (i.e. in the module you're currently writing, 
rather than in the package you're referring to), you can use a convention like:

from CJB.ModuleA import ClassA as CJB_A
from CJB.ModuleB import ClassB as CJB_B

This also has the advantage of being slightly faster - each '.' in a name 
represents another namespace lookup, which happens at run time, not compile 
time. This can end up mattering if the lookup is being done inside a loop.

The above idiom gives you a reference directly to the classes you want to use, 
thus allowing them to be found directly in the module's own dictionary.


More information about the Python-list mailing list