Singledispatch functions raise AttributeError when called on an old-style class

Issue #6 new
ceridwenv
created an issue
from singledispatch import singledispatch

@singledispatch
def f(a): print('f', a)

class C: pass

f(C)
Traceback (most recent call last):
  File "singledispatch_old-style_classes.py", line 8, in <module>
    f(C)
  File "/usr/lib/python2.7/dist-packages/singledispatch.py", line 210, in wrapper
    return dispatch(args[0].__class__)(*args, **kw)
AttributeError: class C has no attribute '__class__'

One obvious possible fix is to replace args[0].__class__ with type(args[0]), which works on old-style classes. I don't know of any cases where type(foo) isn't the same as foo.__class__, though I can't guarantee they don't exist.

Comments (2)

  1. Łukasz Langa repo owner

    type(foo) is not strictly equivalent to foo.__class__. singledispatch is a backport so it's designed to work with new-style classes only. May I suggest moving your classes to be new-style instead?

  2. ceridwenv reporter

    In this case, the problem isn't classes in my code, it's classes in the Python 2.7 standard library that are old-style: I've encountered them in the email module so far, but I can't guarantee there aren't any others around.

  3. Log in to comment