title: Is it possible to add attributes to built in python objects dynamically in Python?
body: <p>I need to add an attribute (holding a tuple or object) to python objects dynamically. This works for Python classes written by me, but not for built in classes. </p>
  
  <p>Consider the following program: </p>
  
  <pre><code>import numpy as np
  
  class My_Class():
      pass
  
  my_obj = My_Class()
  my_obj2 = My_Class()
  
  my_obj.__my_hidden_field = (1,1)
  my_obj2.__my_hidden_field = (2,1)
  
  print(my_obj.__my_hidden_field, my_obj2.__my_hidden_field)
  </code></pre>
  
  <p>This correctly prints <code>(1, 1) (2, 1)</code>. However the following program doesnt work.</p>
  
  <pre><code>X  = np.random.random(size=(2,3))
  
  
  X.__my_hidden_field = (3,1) 
  setattr(X, '__my_hidden_field', (3,1))
  </code></pre>
  
  <p>Both of the above line throws the following error <code># AttributeError: 'numpy.ndarray' object has no attribute '__my_hidden_field'</code></p>
  
  <p>Now, the reason found from these questions (i.e., <a href="https://stackoverflow.com/questions/5741699/attribute-assignment-to-built-in-object">Attribute assignment to built-in object</a>, <a href="https://stackoverflow.com/questions/1529002/cant-set-attributes-of-object-class">Can&#39;t set attributes of object class</a>, <a href="https://stackoverflow.com/questions/8843140/python-dynamically-adding-attributes-to-a-built-in-class">python: dynamically adding attributes to a built-in class</a>) is Python does not allow dynamically adding attributes to built_in objects. </p>
  
  <p>Excerpt from the answer: <a href="https://stackoverflow.com/a/22103924/8413477">https://stackoverflow.com/a/22103924/8413477</a> </p>
  
  <blockquote>
    <p>This is prohibited intentionally to prevent accidental fatal changes to built-in types (fatal to parts of the code that you never though of). Also, it is done to prevent the changes to affect different interpreters residing in the address space, since built-in types (unlike user-defined classes) are shared between all such interpreters.</p>
  </blockquote>
  
  <p>However, all the answers are quite old, and I am badly in need of doing this for my research project. </p>
  
  <p>There is a module that allows to add methods to built in Class though: 
  <a href="https://pypi.org/project/forbiddenfruit/" rel="nofollow noreferrer">https://pypi.org/project/forbiddenfruit/</a></p>
  
  <p>However,it doesnt allow adding objects/attributes to each object. </p>
  
  <p>Any help ?</p>