[Tutor] Restricting the type of passed-in objects

Michael P. Reilly arcege@speakeasy.net
Fri, 11 May 2001 20:03:35 -0400 (EDT)


VanL wrote
> 
> Hello all,
> 
> I am working on implementing a tree. 
> 
> First I am going to do it as a class.  A tree would be defined as one or 
> more treenodes.
> 
> My constructor looks like this:
> 
> class TreeNode:
> 
>    def __init__(self, name=None, data=None, objparent=None, 
> childobjects=[]):
>        if name: self.__label = name
>        if data: self.__data = data
>        if objparent: self.__parentlink = objparent
>        if childobjects: self.__childrenlist = childobjects

As an aside before I answer the question, I would not use [] as the
default value for childobjects.  Set it to None and in __init__ create
a new list object if childobject is None.
  def __init__(self, ..., childobjects=None):
    if childobjects is None:
      childobjects = []

> Now here is my quandry:  I think that I would want to restrict the type 
> of passed-in childobjects.  In my way of thinking, anyone who wanted a 
> tree could either use the vanilla class or they could subclass 
> TreeNode.  Ideally, then, the only objects passed in (as parents or 
> children, with the possible exception of the parent to the root node) 
> would be TreeNode instances (or whatever the subclass is).

How about:
  isTreeNode = lambda inst, cls=TreeNode: not isinstanct(inst, cls)
  if filter(isTreeNode, childobjects):
    raise ValueError("objects in children are not TreeNodes")

If the result of filter is a non-empty list, there are elements that
are not instances of TreeNode... or of subclasses of TreeNode.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |