
PYTHON — Inspecting Dunder Objects in Python
Information technology and business are becoming inextricably interwoven. I don’t think anybody can talk meaningfully about one without the talking about the other. — Bill Gates

PYTHON — Summary of Python’s defaultdict
# Inspecting Dunder Objects in Python
In this tutorial, we will delve into inspecting dunder objects in Python. We will explore where Python stores variables and how it keeps track of the nonlocal scope of a function, even after the function’s scope has been dereferenced.
First, let’s start by understanding the vocabulary that will be used in this tutorial:
.__code__object.co_cellvarsattribute.co_freevarsattribute.__closure__objectCellobject.cell_contentsattribute
Now, let’s dive into the code and inspect these dunder objects using Python code snippets.
def outer():
message = "world"
def inner():
print(message)
return inner
inner_returned = outer()
# Inspecting co_cellvars in the __code__ object of the outer function
outer_code_object = outer.__code__
print(outer_code_object.co_cellvars) # ('message',)
# Inspecting __closure__ of the inner_returned function object
inner_returned_closure = inner_returned.__closure__
print(inner_returned_closure) # (<cell at 0x000001E4F209B400: str object at 0x000001E4F1FEDF80>,)
# Accessing the value of the cell_contents
message_value = inner_returned_closure[0].cell_contents
print(message_value) # 'world'
# Changing the value of the variable in the nonlocal scope
inner_returned.__closure__[0].cell_contents = "oops"
print(inner_returned()) # oopsIn the code snippet above, we inspect the .__code__ object of the outer() function to see where the message variable is stored. We also inspect the .__closure__ of the inner_returned function object to access the value of the message variable and change its value in the nonlocal scope.
It’s important to note that modifying dunder objects is typically for internal use of Python and is not recommended for end users. However, Python provides the flexibility to access and modify these objects if necessary.
By understanding and inspecting dunder objects, you gain insight into how Python manages variables and scopes, which can be valuable for advanced debugging and understanding the inner workings of Python.
In conclusion, inspecting dunder objects in Python provides a deeper understanding of variable storage and scope management, allowing you to gain insights into the internal mechanisms of Python.

