0

I think this is an extension to another question

Background

Working with python 2.7, I have a class

class Report(object):
  def translate_report(self, report_entity):
    ... # Process report_entity dictionary and return results

# But there is a legacy report class too
class Legacy_Report(object):
  def translate_report(self, legacy_report_entity):
    ... # Process report_entity dictionary in different way and return results

The report_entity is a dictionary dumped as string in a text file. The dictionary objects vary depending upon Report and Legacy_Report.

Requirement

I'll recreate the object instance with this dictionary and call translate_report. The calling method would be agnostic whether the entity is legacy version or the new one.

My approach

class Legacy_Report(object):
  @staticmethod
  def _legacy_translation(legacy_report_entry):
    ... # Process
    return legacy_report_entry

  def __call__(self, underlying_function):
    def wrapper_func(self, report_object):
      if 'legacy' in report_object.keys():
        return Decorator._legacy_translation(report_object)
      else:
        return underlying_function(self, report_object)
    return wrapper_func

class Report(object):
  @Legacy_Report()
  def translate_report(self, report_entity):
    ... # Process report_entity 
    return report_entity

The Question

While this works, is this the right way to achieve this ?

Maybe decorator at some other level or some better pythonic way ?

Community
  • 1
  • 1
mittal
  • 915
  • 10
  • 29

1 Answers1

0

Just use inheritance.

class Report(object):
    def translate_report(self, report_entity):
        ... # Process report_entity dictionary and return results


class Legacy_Report(Report):
    def translate_report(self, legacy_report_entity):
        ... # Process the legacy report differently
chepner
  • 497,756
  • 71
  • 530
  • 681
  • That would defeat the purpose. By OOPS paradigm, they should not inherit as they are unrelated. Plus, the calling for `translate_report` should be conditional based upon the `report_entity` contents – mittal Jun 19 '19 at 20:17
  • I'm assuming the class contains something *besides* the `translate_report` method; otherwise, what's the point of the class in the first place? – chepner Jun 19 '19 at 20:22
  • Sort of. The legacy report class is basically just an extension of `__dict__` with very few additional methods. Newer report class is really fancy though :) – mittal Jun 19 '19 at 20:50
  • Any pythonic solution, anyone ?? – mittal Jun 23 '19 at 20:25