python - Make class iterable respecting inheritance -


well making class iterable easy enough using meta classes (so other answers here). wish make class iterable, , enabling 1 "iterate subgroup based on inheritance". example of use:

class iterpartregistry(type):     def __iter__(cls):         return iter(cls._registry)   class a(object, metaclass=iterpartregistry):     _registry = []     def __init__(self, name):         self.name = name         self._registry.append(self)  class b(a):     pass  class c(a):     pass   a("a - first") b("b - first") b("b - second") c("c - first")  t in a:     print(t.name)  print(" --- ") t in b:     print(t.name)  exit() 

the first loop works - iterates on instances , childs of "a". second loop should run on specific subgroup of "a" - instances of child "b" (or children further down line).

(how) can achieved easiest? in such way adding more subclasses require least amount of work/change?

you can use isinstance insure getting class instances

in code 1 line change:

class iterpartregistry(type):     def __iter__(cls):         return (c c in cls._registry if isinstance(c, cls)) 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -