Dynamic Classes in Python

From PeformIQ Upgrade
Jump to navigation Jump to search

DynamicClassFactory.py

#!/usr/bin/env python
##
## Factory for dynamic classes
## $Id: DynamicClassFactory.py 1.1 1997/10/27 13:07:23 gandalf Exp $
## $Log: DynamicClassFactory.py $
## Revision 1.1  1997/10/27 13:07:23  gandalf
## Initial revision
##
##

__doc__ = """
Factory class for  dynamic classes. Support a generate a object instance and receive a methods
or class instance
addClasses                        Add a DynamicClass'es into factory
_addClasses                       same, but accept a tuple
addClass                          Add a single DynamicClass
delClass                          delete a single class
delClasses                        delete few classes
getMethod                         Return a 'pointer' to method by 'Class.method'
__getitem__                       Return a class instance
__call__                          Return a object instance
"""

class DynamicClassFactory:
    def __init__(self, *_dynclasses):
	self.__dclasses__ = {}
	self.__dclassinst__ = {}
	self._addClasses(_dynclasses)
    def _addClasses(self, _dynclasses):
	for i in _dynclasses:
	    self.addClass(i)
    def addClasses(self, *_dynclasses):
	for i in _dynclasses:
	    self.addClass(i)
    def addClass(self, _dynclass):
	self.__dclasses__[_dynclass.name()] = _dynclass
	_dynclass.setFactory(self)
	self.__dclassinst__[_dynclass.name()] = _dynclass.do()
    __add__ = addClass
    def delClass(self, _name):
	try:
	    del self.__dclasses__[_name]
	    del self.__dclassesinst__[_name]
	except KeyError:
	    return
    def delClasses(self, *_names):
	for i in _names:
	    self.delClass(i)
    def getMethod(self, _pointer):
	import string
	_cla_nam = string.split(string.strip(_pointer), '.')
	if len(_cla_nam) < 2:
	    return None
	try:
	    return self.__dclassinst__[_cla_nam[0]].__dict__[_cla_nam[1]]
	except (KeyError, AttributeError):
	    return None
    def __getitem__(self, key):
	return self.__dclassinst__[key]
    def __call__(self, key, *args, **kw):
	return apply(self[key],args,kw)

DynamicClass.py

#!/usr/bin/env python
##
## Dynamic Class - we will be create it dynamicaly :)
## $Id: DynamicClass.py 1.2 1997/10/27 13:01:30 gandalf Exp $
## $Log: DynamicClass.py $
## Revision 1.2  1997/10/27 13:01:30  gandalf
## Add a __doc__ string
##
## Revision 1.1  1997/10/27 12:58:49  gandalf
## Initial revision
##
##

import new

__doc__ = """
This class are collect a description of dynamic class and generate a class instance
setFactory                                    set a DynamicClassFactory for
                                              this DynamicClass
do                                            generate class instance
name                                          return classname
"""


class DynamicClass:
    def __init__(self, _classname, _methods = {}, _vars={},_baseclasses = (), _docstring=''):
	self.__classname__   = _classname
	self.__classdict__   = _methods
	self.__vars__        = _vars
	self.__baseclasses__ = _baseclasses
	self.__docstring__   = _docstring
	self.__factory__     = None
    def setFactory(self, _factory):
	self.__factory__     = _factory
    def do(self):
	import string
	_odct = {'__name__':self.__classname__,'__doc__':self.__docstring__}
	for i in self.__vars__.keys():
	    _odct[i] = self.__vars__[i]
	_unbounds = []
	for i in self.__classdict__.keys():
	    _mod_nam = string.split(string.strip(self.__classdict__[i]), '!')
	    if len(_mod_nam) < 2:
		_odct[i] = self.__factory__.getMethod(self.__classdict__[i])
		if _odct[i] == None:
		    del _odct[i]
		    continue
	    try:
		exec ('import %s'%_mod_nam[0])
	    except ImportError:
		continue
	    try:
		exec ("_odct[i] = %s.%s"%(_mod_nam[0],_mod_nam[1]))
	    except AttributeError:
		continue
	_bcrec = ()
	for i in self.__baseclasses__:
	    _bcrec = _bcrec + (self.__factory__[i],)
	#print _odct,_bcrec
	return new.classobj(self.__classname__, _bcrec, _odct)
    def name(self):
	return self.__classname__