title: How to make a polymorphic dataclass constructor method
body: <p>I have 3 dataclass objects say:</p>
  <pre><code>class Message1:
      def __init__(a):
         ...
  
  class Message2:
      def __init__(d,e,f):
         ...
  
  class Message3:
      def __init__(g,i):
         ...
  </code></pre>
  <p>For these 3 messages I want to make a factory type method which can return one of the three objects if it succeeds and if not it should return either the one it identified as the correct message to be created but failed at creation or it should notify the user that it could not create any of the messages. Are there any OOP patterns for this?</p>
  <p>My initial thought was to do a:</p>
  <pre><code>def factory_method(**parameters):
      try:
          Message1(**parameters)
      except TypeError:
          try:
              Message2(**parameters)
          except:
              try:
                  Message3(**parameters)
              except:
                  print(&quot;Could not deduce message type&quot;)
  </code></pre>
  <p>My issue with this idea is that:</p>
  <ol>
  <li>It's not a dynamically scalable solution, with each new message class I introduce I need to add a new try catch block</li>
  <li>If the whole nested block structure fails, I have no feedback as to why, was the parameters correct for one of the message but wrong value, or was it plain gibberish?</li>
  </ol>
  <p>I realize this might be a bit opinion based on what the best outcome is. At the same time it might be the solution is not too elegant and the simplest way is to just tell the factory_method what kind of message to initialize. Any suggestions or ideas would be appreciated.</p>