Proposal: Python Class Files

Michal Wallace sabren at manifestation.com
Fri Oct 6 11:08:06 EDT 2000


Proposal for a Python Enhancement Proposal: Python Class Files

A common python practice is to create modules with one class each.
This is especially true when building multi-file packages. This
practice makes for maintainable code, but causes some small
irritations for the developer, because imported classes are wrapped in
a module you don't need.

### somepackage/__init__.py ####

# three ways of importing classes into a package:
from Class1 import Class1
import Class2
# Class3 is defined in Class3.py, but not imported


### a calling script: 

import somepackage

obj1 = somepackage.Class1() # works, but returns somepackage.Class1.Class1

try:
   obj2 = somepackage.Class2() # Error
except:
   obj2 = somepackage.Class2.Class2()

try:
   obj3 = somepackage.Class3() # Error
except:
   obj3 = somepackage.Class3.Class3()


#######

That internal module is ugly... If you want to get rid of it, you have
to either write some sort of lazy-loading facility or put a bunch of
"from X import X" lines in your top level package, which makes python
do more work than it really needs to.

What I'd suggest instead is adding an import hook for modules that
contain only one class. Basically, if the file is called Class1.pc
then "import Class1" creates a new class, not a module.

Class files would work like this:

1. Each class file contains one and only one class.
2. The class name must match the filename (minus the .pc extension)
3. All statements in the file must be inside the class definition.
4. Class files may be run directly via "python Class1.pc". In this case,
   python looks for a __main__ method. This replaces the
   "if __name__=='__main__'" idiom for these files.
5. When class files are imported, the class is defined in the calling
   namespace. 
6. Calling "from package import *" would import all the classes defined
   in .pc files, EXCEPT classes beginning with an underscore.
7. Calling "import package" would import all class files into
   the package namespace. 

One alternative for 7 might be to load stubs of a new type called
"ClassFile", which would allow for lazy loading and might improve
speed. When you instantiate a ClassFile, only then does it read the
actual file.

####

Some modules are designed to work like singleton objects. (For
example, asyncore). I believe modules in general should behave more
like instances. This proposal is NOT meant to cover these situations.
I'm talking about importing classes, not instances here.

What do y'all think?

Cheers,

- Michal
------------------------------------------------------------------------
www.manifestation.com  www.sabren.com  www.linkwatcher.com  www.zike.net
------------------------------------------------------------------------





More information about the Python-list mailing list