0

I am trying to subclass Queue and the following code throws an exception:

from Queue import Queue

class MyQueue(Queue, object):
    def __init__(self, my_stuff = None):
        super(MyQueue, self).__init__()
        self.my_stuff = my_stuff

    def my_function(self):
        return self.my_stuff

And I'm calling it from __main__ like so:

a_queue = MyQueue(my_stuff = "some stuff")
print a_queue

I am getting, as expected:

$ ./my_queue.py
some stuff

But I only get that if I also inherit from object (per new-style classes). Otherwise I get:

Traceback (most recent call last):
File "./my_queue", line 13, in <module>
  a_queue = MyQueue(my_stuff = "some stuff")
File "./my_queue", line 6, in __init__
  super(MyQueue, self).__init__()
TypeError: must be type, not classobj

Why? It apparently doesn't work for Queue as easily as it does for e.g. mp.Process (see this question and also this question).

Virgil Gheorghiu
  • 493
  • 1
  • 4
  • 13

1 Answers1

1

The problem is that the Queue class does not support the super feature since it is an old style class. This way inheriting from object will solve your problem (make it a new style class). But if you want to avoid it just call init directly

change it to:

from  Queue import Queue

class MyQueue(Queue):
     def __init__(self, my_stuff = None):
         Queue.__init__(self)
         self.my_stuff = my_stuff

     def my_function(self):
         return self.my_stuff

while old classes in python cannot do this New style classes may use super(Foo, self) where Foo is the class and self is the instance.

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

The new style class is usually a better choice

Omer Ben Haim
  • 595
  • 4
  • 14