[Python-3000] Composable abstract base class?

Ryan Freckleton ryan.freckleton at gmail.com
Sun May 27 09:19:20 CEST 2007


I've been following the python-dev and python 3000 lists for over a
year, but this is my first posting.

I think I've found additional abstract base class to add to PEP 3119.
An ABC for composable data (e.g. list, tuple, set, and perhaps dict)
to inherit from. An composable object can contain instances of other
composable objects. In other words, a composable object can be used as
the outer container in a nested data structure.

The motivating example is when you want to recurse through a nested
list of strings, e.g.

>>> seq = ['my', 'hovercraft', ['is', 'full', 'of', ['eels']]]
>>> def recurse(sequence):
	if isinstance(sequence, list):
		for child in sequence:
			recurse(child)
	else:
		print sequence


>>> recurse(seq)
my
hovercraft
is
full
of
eels

You could solve this by the composite pattern, but I think that using
an ABC may be simpler.

If we had a Composable ABC that set, list and tuple inherit, the above
code could be written as:

def recurse(sequence):
	if isinstance(sequence, Composoble):
		for child in sequence:
			recurse(child)
	else:
		print sequence

Which is much more general.

This could be easily introduced by a third party developer, using the
mechanisms outlined in the PEP, the question is: would it be
worthwhile to add this ABC to PEP 3119?

If it was added to to PEP 3119, I believe that it should be a subtype
of Container. I do not think it should inherit from Iterable, since it
is possible for a container types to not support the iterator
protocol, but still support composition.

Sincerely,
-- 
=====
--Ryan E. Freckleton


More information about the Python-3000 mailing list