Splitting a class definition into several files?

Bengt Richter bokr at oz.net
Tue Nov 16 04:18:42 EST 2004


On 15 Nov 2004 15:08:31 -0800, jerry.levan at eku.edu (Jerry) wrote:

>My "main" class is getting a bit long...Is it possble to split a class definition
>into several files and then import the pieces to get the whole definition?
>
>Jerry
Ignoring the fact that this is not unlikely a symptom of a design problem ... ;-)

If you import from different files, the code in them will have distinct
globals() dictionaries -- i.e., the module dicts of the respective imported
modules. If that doesn't matter -- as e.g., if you wanted to define the functions
for methods that don't use globals (including the Main class name) then you could
use import to bind methods and initial class variable values -- remembering that
the latterbindingswithin the Main class.
_____________________________________________________________________

 >>> for line in file('main.py'): print line.rstrip()
 ...
_____________________________________________________________________

class Main(object):
    """
    Class Main demonstrates
    - importing functions from other module global scope to become methods
      showing distinction of global references from imported vs locally defined
      method functions.
    - including code into class via execfile
    - normal method and class variable definitions
    """
    # do example imports
    from main_methods_1 import main_method_1, trouble, trouble_global, foo_mm1
    # from main_methods_2 import ...
    # from main_methods_3 import ...

    # example execfile
    execfile("main_classvar_defs.py")

    #normal stuff
    def foo(x='foo local'): return locals().keys(), globals().keys()
    def normalmethod(self):
        "normalmethod defined in class Main of main.py"
        return self.normalmethod.__doc__
    normal_class_var = 'normal classvar defined in Main of main.py'
_____________________________________________________________________

 >>> for line in file('main_methods_1.py'): print line.rstrip()
 ...
_____________________________________________________________________

def main_method_1(self):
    "main_method_1 defined in main_methods_1.py global scope as function"
    return type(self).main_method_1.__doc__ # can't refer to Main.main_method_1

def foo_mm1(x='foo_mm1 local'): return locals().keys(), globals().keys()

trouble_global = 'global defined in global scope of main_methods_1.py'
def trouble(self):
    """
    this returns a global, but it's not Main's global
    and in fact is also given a Main class var binding via the import *
    """
    return trouble_global
_____________________________________________________________________

 >>> for line in file('main_classvar_defs.py'): print line.rstrip()
 ...
_____________________________________________________________________

cv1 = 'class var cv1 from execfile("main_classvar_defs.py")'
def xfmethod(self):
    "defined in main_classvar_defs.py via execfile -- note ref to Main ok"
    return Main.xfmethod.__doc__, Main.cv1
def foo_cv1(x='foo_cv1 local'): return locals().keys(), globals().keys()
_____________________________________________________________________

Now, importing main:

 >>> import main
 >>> help(main)

Help on module main:

NAME
    main

FILE
    c:\pywk\clp\jerry.levan\main.py

CLASSES
    __builtin__.object
        Main

    class Main(__builtin__.object)
     |  Class Main demonstrates
     |  - importing functions from other module global scope to become methods
     |    showing distinction of global references from imported vs locally defined
     |    method functions.
     |  - including code into class via execfile
     |  - normal method and class variable definitions
     |
     |  Methods defined here:
     |
     |  foo(x='foo local')
     |      #normal stuff
     |
     |  foo_cv1(x='foo_cv1 local')
     |
     |  foo_mm1(x='foo_mm1 local')
     |
     |  main_method_1(self)
     |      main_method_1 defined in main_methods_1.py global scope as function
     |
     |  normalmethod(self)
     |      normalmethod defined in class Main of main.py
     |
     |  trouble(self)
     |      this returns a global, but it's not Main's global
     |      and in fact is also given a Main class var binding via the import *
     |
     |  xfmethod(self)
     |      defined in main_classvar_defs.py via execfile -- note ref to Main ok
     |
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |
     |  __dict__ = <dictproxy object at 0x009AEFF0>
     |      dictionary for instance variables (if defined)
     |
     |  __weakref__ = <attribute '__weakref__' of 'Main' objects>
     |      list of weak references to the object (if defined)
     |
     |  cv1 = 'class var cv1 from execfile("main_classvar_defs.py")'
     |
     |  normal_class_var = 'normal classvar defined in Main of main.py'
     |
     |  trouble_global = 'global defined in global scope of main_methods_1.py'

 >>> mlist = [k for k,v in vars(main.Main).items() if callable(v) and not k.startswith('__')]
 >>> mlist
 ['xfmethod', 'foo_mm1', 'main_method_1', 'trouble', 'foo_cv1', 'foo', 'normalmethod']
 >>> minst = main.Main()
 >>> for m in mlist: print '%14s: %r'%(m, getattr(minst, m)())
 ...
       xfmethod: ('defined in main_classvar_defs.py via execfile -- note ref to Main ok', 'class
 var cv1 from execfile("main_classvar_defs.py")')
        foo_mm1: (['x'], ['__builtins__', 'foo_mm1', '__file__', 'trouble_global', 'main_method_1
 ', '__name__', 'trouble', '__doc__'])
  main_method_1: 'main_method_1 defined in main_methods_1.py global scope as function'
        trouble: 'global defined in global scope of main_methods_1.py'
        foo_cv1: (['x'], ['__builtins__', '__name__', '__file__', 'Main', '__doc__'])
            foo: (['x'], ['__builtins__', '__name__', '__file__', 'Main', '__doc__'])
   normalmethod: 'normalmethod defined in class Main of main.py'


 >>> minst.trouble()
 'global defined in global scope of main_methods_1.py'
 >>> minst.trouble_global
 'global defined in global scope of main_methods_1.py'
 >>> minst.trouble_global is minst.trouble()
 True
 >>> minst.trouble_global is main.Main.trouble_global
 True

<disclaimer>I haven't used these techniques in any significant way, so testing is advised.
They're just what I thought of in response to your post, based on a few previous experiments.
;-)</disclaimer>

Regards,
Bengt Richter



More information about the Python-list mailing list