Using Python's .__dict__ to Work with Attributes – Real Python
a year ago
- #Python
- #Debugging
- #Metaprogramming
- Python's .__dict__ is a special attribute in classes and instances that maps attribute names to their values.
- .__dict__ allows dynamic inspection, modification, addition, or deletion of attributes, making it useful for metaprogramming and debugging.
- Both vars() and .__dict__ can inspect an object's attributes, with .__dict__ providing direct access to the object's namespace.
- Common use cases for .__dict__ include dynamic attribute management, introspection, serialization, and debugging.
- .__dict__ is fundamental to Python's data model and is used internally by the interpreter for dynamic attribute access.
- Classes and instances have separate .__dict__ attributes, with instance .__dict__ containing only instance-specific attributes.
- Functions also have a .__dict__ attribute, which can be used to attach metadata or for caching purposes.
- Built-in functions and data types may not have a .__dict__ attribute, as they are implemented in C for efficiency.
- .__dict__ can be used for memoization, serializing objects to JSON, and customizing attribute access with special methods like __getattribute__ and __setattr__.
- Descriptors can use .__dict__ to avoid recursion issues when implementing __get__ and __set__ methods.