title: Python MongoDB Motor dynamically create Indexes
body: <p>I am attempting to write a function which will async create Indexes for each of my collections dynamically. The struggle I am having is accessing the class instance of each of my collections, and then calling the object to create the index.</p>
  <p>I have tried:</p>
  <ul>
  <li>getattr</li>
  <li>ast.literal_eval</li>
  </ul>
  <p><strong>NOTE: I am unable to use eval() for security reasons</strong></p>
  <p>Example of how my class instance looks:</p>
  <pre class="lang-py prettyprint-override"><code>import ast
  from models.database_models import IndexedKeyModels
  
  
  class Mongo:  # pylint: disable=too-many-instance-attributes
      def __init__(self):
          self.connection = self.get_set_connection() # Function to create MongoDB connection
          self.db = self.connection.pal_db
          self.test1 = self.db.test1
          self.test2 = self.db.test2
  
      async def set_indexes(self) -&gt; None:
  
          test_string: str = &quot;&quot;
          if self.dev == &quot;True&quot;:
              test_string += &quot;test_&quot;
          for name in IndexedKeyModels():
              await ast.literal_eval(
                  f&quot;self.{test_string}{name[0]}.create_index([('{name[1]}', {ASCENDING})], background=True)&quot;
              )
  </code></pre>
  <p>The IndexedKeyModels looks like this:</p>
  <pre class="lang-py prettyprint-override"><code>class IndexedKeyModels(BaseModel):
      &quot;&quot;&quot;
      MongoDB Indexed Key names
      &quot;&quot;&quot;
  
      test1: str = &quot;Index1&quot;
      test2: str = &quot;Index2&quot;
  </code></pre>
  <p>I would like to be able to dynamically create each Index for each collection without having to define each create_index for each collection we have.</p>