Educational collection of surprising Python code snippets that demonstrate counter-intuitive behaviors and language internals
Overall
score
93%
Build a Python utility that helps developers understand how Python handles class attributes, method identity, and name mangling.
Create a module that implements the following capabilities:
Implement a function that determines whether an attribute belongs to the class or to an instance:
Implement a function that demonstrates method identity behavior:
is) and equality (==)Implement a function that handles Python's name mangling for private attributes:
__ but doesn't end with __), return the mangled name_ClassName__attributenamecheck_attribute_type returns 'class' @testcheck_attribute_type returns 'instance' @testcompare_method_identity, the identity check returns False but equality check returns True @test__secret, get_mangled_name('MyClass', '__secret') returns _MyClass__secret @test@generates
def check_attribute_type(cls, obj, attr_name):
"""
Determines whether an attribute is a class attribute, instance attribute, or both.
Args:
cls: The class to check
obj: An instance of the class
attr_name: The name of the attribute to check
Returns:
A string: 'class', 'instance', 'both', or 'neither'
"""
pass
def compare_method_identity(obj, method_name):
"""
Compares the identity and equality of method references from the same object.
Args:
obj: An object with methods
method_name: The name of the method to check
Returns:
A dict with keys 'is_identical' (bool) and 'is_equal' (bool)
"""
pass
def get_mangled_name(class_name, attr_name):
"""
Returns the mangled version of a private attribute name.
Args:
class_name: The name of the class
attr_name: The attribute name (may start with __)
Returns:
The mangled attribute name if applicable, or the original name
"""
passProvides educational examples of Python's class and object behavior patterns, including attribute handling, method identity, and name mangling.
Install with Tessl CLI
npx tessl i tessl/pypi-wtfpythondocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10