self.__dict__ tricks

Tim Johnson tim at
Fri Oct 30 03:16:37 CET 2009

This is not a request for help but a request for comments:
Consider the following code and note that
1)The initializer uses the dictionary style of arguments
2)The check loop executes before all of the class variables
  are declared
## --------------------------------------------------------------------
class formLoader():
	def __init__(self,**kw):
		self.fileName = None
		self.record = None
		self.string = None
		## Uncomment below to see that only fileName, record and string
		## are recorded by __dict__
		for k in kw.keys():
			if k in self.__dict__:
				self.__dict__[k] = kw[k]
				raise AttributeError("%s is not a class member. Use one of ('%s')"
						   % (repr(k),"', '".join(self.__dict__.keys())))
		self.tokens = ["form","input","textarea","select","option","form"]
		self.inputTypes = ["button","checkbox","file","hidden","image","password",
		self.inputValTypes = ["file","hidden","password","text"]						   
		self.colnames = []      ## case-insensitive column names
		self.formIndexes = []   ## Index forms in outer list
## .....
## --------------------------------------------------------------------
Now if I were to code something like the following:
fml = formLoader(fileName=doc,tokens="tim")
## Note that `tokens' is passed as a named argument.
I get the following error message:
AttributeError: 'tokens' is not a class member. Use one of ('record',
'string', 'fileName')

I am not complaining! This is a good thing and a cool idiom.
Placing the the check loop after _only_ the keywords that I wanted to
allow _disallows_ any others.
I'd welcome comments - such as any other applications.

Always a newbie ....
tim at

More information about the Python-list mailing list