Dynamically determine base classes on instantiation

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Aug 16 19:49:43 CEST 2012


On Thu, 16 Aug 2012 10:03:51 -0700, Richard Thomas wrote:

> class Foo(object):
>     def __new__(cls, arg):
>         if isinstance(arg, list):
>             cls = FooList
>         elif isinstance(arg, dict):
>             cls = FooDict
>         return object.__new__(cls, arg)
> 
> class FooList(Foo, list):
>     pass
> 
> class FooDict(Foo, dict):
>     pass


Did you actually try your code?


py> x = Foo([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __new__
TypeError: object.__new__(FooList) is not safe, use list.__new__()




-- 
Steven



More information about the Python-list mailing list