Skip to content
Advertisement

Using __init__ method to call class main functionality

I needed to encapsulate functions related to single responsibility of parsing and emiting messages to API endpoint so I have created class Emitter.

class Emitter:
    def __init__(self, message: str) -> None:
        self.parsed = self.parse_message(message)
        self.emit_message(self.parsed)

    @staticmethod
    def parse_message(msg: str) -> str:
        ...  # parsing code

    @staticmethod
    def emit_message(msg: str) -> None:
        ...  # emitting code

In order to emit a message I call a short-lived instance of that class with message passed as argument to __init__.

Emitter("my message to send")

__init__ itself directly runs all necessary methods to parse and emit message. Is it correct to use __init__ to directly run the main responsibility of a class? Or should I use different solution like creating function that first instantiates the class and then calls all the necessary methods?

Advertisement

Answer

It looks like you’re attempting to do the following at once:

  1. initialize a class Emitter with an attribute message
  2. parse the message
  3. emit the message

IMO, a class entity is a good design choice since it allows granular control flow. Given that each step from above is discrete, I’d recommend executing them as such:

# Instantiate (will automatically parse)
e = Emitter('my message')

# Send the message
e.send_message()

You will need to redesign your class to the following:

class Emitter:
    def __init__(self, message: str) -> None:
        self.message = message
        self.parsed = self.parse_message(message)

    @staticmethod
    def parse_message(msg: str) -> str:
        ...  # parsing code

    # This should be an instance method
    def emit_message(msg: str) -> None:
        ...  # emitting code

Also, your parse_message() method could be converted to a validation method, but that’s another subject.

Advertisement