OK, so I write a framework that looks for python files in subdirectories with a name task.py, and then looks for classes that are derived from the base class Taskand compile them. I decided that I needed to add a meta class to Task, but then issubclass()began to behave in a strange way. Here's what the catalog layout looks like:
start.py
tasks/__init__.py
tasks/base.py
tasks/sub/__init__.py # empty
tasks/sub/task.py
start.py:
from tasks.base import Task1, Task2
from tasks.sub.task import SubTask1, SubTask2
print "Normal import:"
print "is SubTask1 sub class of Task1? %s" % issubclass(SubTask1, Task1)
print "is SubTask2 sub class of Task2? %s" % issubclass(SubTask2, Task2)
from tasks import setup
print "Imp import:"
setup()
Tasks / INIT .py
import os.path, imp, types
from tasks.base import Task1, Task2
ALL_TASK1 = { }
ALL_TASK2 = { }
def _append_class(d, task, base):
if (type(task) == types.TypeType) and issubclass(task, base):
if task == base:
return
if not task.name in d:
d[task.name] = task
this_dir = os.path.dirname(os.path.abspath(__file__))
for root, dirs, files in os.walk(this_dir):
if not "task.py" in files:
continue
mod_name = "task"
f, pathname, description = imp.find_module(mod_name, [ root ])
m = imp.load_module(mod_name, f, pathname, description)
f.close()
for task in m.__dict__.itervalues():
_append_class(ALL_TASK1, task, Task1)
_append_class(ALL_TASK2, task, Task2)
def setup():
print "All Task1: %s" % ALL_TASK1
print "All Task2: %s" % ALL_TASK2
Tasks / base.py
class MetaClass (type):
def __init__(cls, name, bases, attrs):
pass
class Base (object):
__metaclass__ = MetaClass
def method_using_metaclass_stuff(self):
pass
class Task1 (Base):
pass
class Task2 (object):
pass
Tasks / sub / task.py
from tasks.base import Task1, Task2
class SubTask1 (Task1):
name = "subtask1"
class SubTask2 (Task2):
name = "subtask2"
When I run setup.py, I got the following output (ALL_TASK1 dict is empty!):
Normal import:
is SubTask1 sub class of Task1? True
is SubTask2 sub class of Task2? True
Imp import:
All Task1: {}
All Task2: {'subtask2': <class 'task.SubTask2'>}
But when I comment out the line __metaclass__in the class Base( Task1base class), I got the expected result (ALL_TASK1 dict is not empty):
Normal import:
is SubTask1 sub class of Task1? True
is SubTask2 sub class of Task2? True
Imp import:
All Task1: {'subtask1': <class 'task.SubTask1'>}
All Task2: {'subtask2': <class 'task.SubTask2'>}
, issubclass(), imp, , import.
- ( python 2.6.1)?