vendredi 26 décembre 2014

Does dynamically generating classes in python affect readability/performance?


I have a set of classes that represent different objects (tables in a database):



class ObjA:
# some class specific attributes and methods

def refresh(self):
# implementation
pass

class ObjB:
# some class specific attributes and methods

def refresh(self):
# implementation
pass


and they all have a refresh method. Now I have a task manager (like Luigi) that is used to call the refresh method on each class and the definitions look like:



from somewhere import ObjA, ObjB


class RefreshObjA(TaskManager):
def run(self):
ObjA.refresh()


class RefreshObjB(TaskManager):
def run(self):
ObjB.refresh()


TaskManager here is a parent class provided by the manager module. As you can see, the class definitions all have an identical pattern and naming convention, and it stands to reason that these can be dynamically generated as generateRefreshClasses([ObjA, ObjB, ...]).


However, I have been resisting this and writing each one out explicitly because



  • All the information re: the classes is available when the code is written i.e. I'm not reliant on any external/user generated input which is probably where dynamic generation is useful. This use is purely to save space/keystrokes/repetition.

  • One doesn't know if some ObjX might need modifications/additional requirements and will need to be careful to remove it from the dynamic generator, lest it is overwritten.

  • It is harder to reason where (as in file and line no:) an execution error occurs if the code is dynamically generated.

  • These classes might be imported elsewhere in the code base and I lose out on the static inspection based checking provided by the IDE.


Are these valid reasons to continue to individually define the classes (there might be about 20 or so of them) or are there other benefits to dynamic generation that might make these concerns small in comparison? Would dynamic generation of classes be considered acceptable/good practice in such an application?





Aucun commentaire:

Enregistrer un commentaire