What are modules really for?
saint.infidel at gmail.com
Tue Aug 9 17:54:37 CEST 2005
> I am very new to Python, but have done plenty of development in C++ and
And therein lies the root of your question, I believe.
> One thing I find weird about python is the idea of a module. Why is this
> needed when there are already the ideas of class, file, and package?
One reason is that functions need a place to exist too. In Java, every
function, even "static" ones has to be a class method. In Python,
"static" functions are best kept in a module. Another thing is that
packages were a later addition to the language.
> To my mind, although one CAN put many classes in a file, it is better to
> put one class per file, for readability and maintainability.
Personally I find it easier to maintain a set of related classes when
they're all in the same file. I've got a few modules that I'm
currently hacking on, each of which contains a handful of classes.
Maybe it's just a matter of scale, since these are both fairly small
libraries, but I just don't see any advantage to splitting them up into
> One can then create packages and libraries, using groups of files, one
> class per file.
Since Java's compiler enforces this, perhaps you've just come to accept
it as "normal".
> Python seems to let you group classes together in one file and call it a
> module, but what for?
What if one of your classes creates/manipulates other classes. If
they're in the same module then they all exist in the same namespace
and you don't have to have modules importing each other or such things.
> I find that this, combined with mixins, makes it difficult to find out
> where code is inherited from.
Perhaps you are relying too much on inheritance, then?
> With single inheritance in C++ or Java, if you wanted to see what a
> method did and it appeared to be inherited, you would simply look in the
> base class's file, and if necessary recurse up the inheritance hierarchy
> until you found the method.
> With Python an inherited method could be in one of many base classes
> and/or mixins and there seems no particular logic as to what the
> filename would be.
It shouldn't be too hard to figure out, unless someone was being
intentially vague. You could always fire up the interpreter, import
your class, and check it's .mro property (method resolution order),
which lists the classes in the order they will be examined to find a
method named at runtime.
> Am I missing something?
I just think you're thinking in terms of Java. You'll pick things up
quickly, though :-)
More information about the Python-list