Carel
Carel

Reputation: 3397

Python : Inheritance from one class, child classes give TypeError

I have two classes that inherit from the same base class but do not want to play with each other, such are the young ones indeed.

class A() : 
  ...

class B(A) : 
  ...

class C(A) : 
  ...

b=B()
c=C()
c.method(b)

gives me a TypeError of c and b are not the same, what does python need to think that they are the same ? Is there some __SpecialThingIDontKnowAbout__ property/method one should implement or not ? Or is there some trick to class design that I'm missing

To be particular I am inheriting TreeDict() as follows :

class TNode(TreeDict):
 def __init__(self,*args,**kwargs) : 
  super(TNode, self).__init__(*args, **kwargs)

class LNode(TreeDict):
 def __init__(self,*args,**kwargs) : 
  super(LNode, self).__init__(*args, **kwargs)

TN = TNode(); TN.A = 1
LN = LNode(); LN.A = 1
LN.attach('TN',TN)

gives

Traceback (most recent call last):
  File "JSONE.py", line 430, in <module>
  LN.attach(TN)
TypeError: descriptor 'attach' requires a 'treedict.treedict.TreeDict' ...
object but received a 'type'

I do understand that the children are of 'type' and 'treedict^3' is required but how do I get the children to mimic this behaviour ?

EDIT :

Hmm... it started working now, not that I did anything different from what I can see in the undo/redo history (Thanks all)

Upvotes: 4

Views: 649

Answers (1)

dsh
dsh

Reputation: 12213

The problem is that the TreeDict type doesn't allow subclassing. I found it in the treedict package. The TreeDict type itself is written in Cython. The culprit is this block of code in the attach() method (around line 1910 of treedict.pyx):

    if type(tree_or_key) is str:
        key = <str>tree_or_key
    elif type(tree_or_key) is TreeDict:
        if tree is not None:
            raise TypeError("Only one TreeDict instance can be given to attach.")

        tree = <TreeDict>tree_or_key
        key = None
    else:
        raise TypeError("`tree_or_key` must be either a string or TreeDict instance.")

Change the elif type(tree_or_key) is TreeDict: line to elif isinstance(tree_or_key, TreeDict): and submit a patch to the project. You might want to check the rest of treedict.pyx for other occurrences of the same bug.

Upvotes: 1

Related Questions