2

I have a working module that contains a factory function, a super class and two sub classes. The actual module is here.

I split the factory into its own file and put the two subclasses into the commands/ directory so I could get around a recursion problem caused by importing my subs in the module containing my super.

Just when I think I have everything importing correctly, the factory is stuck with an empty list of subclasses when I try:

for cls in Command.__subclasses__():
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
mnate
  • 89
  • 6
  • 1
    Have any of the Command sub-classes actually been imported at the point where you look at the list? – Daniel Watkins Feb 21 '13 at 14:21
  • 2
    Note: `__subclassess__` is a CPython optimization detail. Do not rely on it as a language feature. – Martijn Pieters Feb 21 '13 at 14:23
  • 1
    Take a look at http://stackoverflow.com/questions/3048337/python-subclasses-not-listing-subclasses it seems `__subclasses__()` is quite finicky, in addition to being implementation dependent as @MartijnPieters points out. Have you thought about giving a `metaclass` a try? I've never seen these sorts of issues when using one to register subclasses to a factory or other construct. – Silas Ray Feb 21 '13 at 14:49
  • thanks for all the feedback. the classes seemt o be importing. the factory function can print the value of Command.__name__. I don't know if the subclasses are failing tob e imported or if the Command.__subclasses__ is just not valid after I move things around. – mnate Feb 22 '13 at 16:45
  • I 'll have to do some research on an alternative to using _subclasses__. an alternative might also provide a solution:) – mnate Feb 22 '13 at 16:46
  • I'm going to mark this as solved because metaclasses are probably the tool for the job. That said, they're fairly inaccessible to the novice. If I figure it out, I'll try to document the comparison of my original, lazy but convenient use of __subclasses__ to the probably more effective use of metaclasses. – mnate Feb 22 '13 at 17:19
  • @mnate: it's not "marked as solved" unless you post your (best) solution as an answer, and then select it by clicking the green check mark near the up/downvote buttons. – askewchan Feb 23 '13 at 00:21

1 Answers1

0

It ain't pretty but it works. I'd love a more elegant way to convert the string to the class name. looping through __subclasses__ was indeed too finicky. I just don't understand metaclass well enough to apply it.

from commands.shVersionCmd import shVersionCmd
from commands.shVRFCmd import shVRFCmd
def CommandFactory(commandnode):
    if commandnode.attrib['name'] == 'shVersionCmd': return shVersionCmd(commandnode)        
    if commandnode.attrib['name'] == 'shVRFCmd': return shVRFCmd(commandnode)
mnate
  • 89
  • 6