Home > Software design >  Inter-dependent staticmethod's in python
Inter-dependent staticmethod's in python

Time:10-27

One of the uses of staticmethods in python (and I assume OOP in general) is to write utility functions that do not really need to have access to any attribute. I assume it is more for readability as well as letting the user to use them directly with class name rather than an instance of the class.

It may happen that you need to perform a task with a staticmethod that depends on other staticmethods. What is a good practice in this case? Do you have to write them as instance methods and instantiate the class to let each method to have access to others through instance? Example:

This is not possible:


class AWSHandler:

     @staticmethod
     def do_a_job():
        credentials = _get_credentials()
        return _job_handler(credentials)
     
     @staticmethod
     def _get_credentials():
          return credentials

     @staticmethod
     def _job_handler(credentials):
         return result

This is possible, but needs instantiation of an object:


class AWSHandler:

     def do_a_job(self):
        credentials = self._get_credentials()
        return self._job_handler(credentials)
     
     def _get_credentials(self):
          return credentials

     def _job_handler(self, credentials):
         return result

CodePudding user response:

What you need is a classmethod:

class AWSHandler:

     @classmethod
     def do_a_job(cls):
        credentials = cls._get_credentials()
        return cls._job_handler(credentials)
     
     @classmethod
     def _get_credentials(cls):
          return credentials

     @classmethod
     def _job_handler(cls, credentials):
         return result

You can then simply write

AWSHandler.do_a_job()
  • Related