Generating modul classes with eval

Axel Straschil axel at straschil.com
Thu Feb 3 04:26:28 EST 2005


Hello!

> Note that we don't need eval anywhere.

Uuups, that looks realy cool! Thanks for that!

Im fooling around with generating html-tags. As there are only two kind
of html tags, one who can nest chields, and one who cant, i wantet to
play arround with something like:

I've got two base classes, _Tag and _ContainerTag (for tags which can
nest tags). Instead of getting an htmltag with _Tag(name='html'), I
want to have a class for each html-tag. So, I thought of creating that
classes dynamicly.

my now (nearly) working code is:

class _Tag(object):
	def __init__(self, name, flags=None, **props):
	[...]

class _ContainerTag(_Tag):
	def __init__(self, name, contents=None, flags=None, **props):
		super(_ContainerTag, self).__init__(name=name, flags=flags, **props)
		self._contents = coalesce(contents, [])
						

_module_name = sys.modules[__name__]

class_dic = {}
class_dic['Br'] = _Tag
class_dic['Hr'] = _Tag
class_dic['Html'] = _ContainerTag
class_dic['Table'] = _ContainerTag

for class_name, class_base in class_dic.items():
	class TmpClass(class_base):
		def __init__(self, **props):
			name = class_name.lower()
			#super(TmpClass, self).__init__(name=name, **props)
			class_base.__init__(self, name=name, **props)
	setattr(_module_name, class_name, TmpClass)
	
br = Br()
print br
table = Table()
print table

br is printed OK, but for table, I get:
AttributeError: 'TmpClass' object has no attribute '_contents'
so, it seems that __init__ of _Tag is not called. 
If I try to do the commented line
	super(TmpClass, self).__init__(name=name, **props)
instead of
	class_base.__init__(self, name=name, **props)
I get:
 TypeError: super(type, obj): obj must be an instance or subtype of
 type
for print table, print br ist processed OK.


Thanks for help and your perfekt examples,
AXEL.




More information about the Python-list mailing list