Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1.     class RecursiveCatcher:
  2.         def __init__(self):
  3.             global stack_depth
  4.             stack_depth = 0
  5.             self.no_of_getattribute_calls = 0
  6.  
  7.         def __getattribute__(self, attr_name):
  8.             # We need something that is outside the scope of this class:
  9.             global stack_depth
  10.             stack_depth += 1
  11.  
  12.             if stack_depth<=10: # to prevent a stack overflow
  13.                 self.no_of_getattribute_calls += 1
  14.                 # Oops! We just accessed an attribute (no_of_getattribute_calls)
  15.                 # Guess what happens when self.no_of_getattribute_calls is
  16.                 # accessed?
  17.  
  18.             # Using 'object' directly because using super() here will also
  19.             # trigger a __getattribute__() call.
  20.             return object.__getattribute__(self, attr_name)
  21.  
  22.         def my_method(self):
  23.             pass
  24.  
  25.     def test_getattribute_is_a_bit_overzealous_sometimes(self):
  26.         catcher = self.RecursiveCatcher()
  27.         catcher.my_method()
  28.         global stack_depth
  29.         self.assertEqual(11, stack_depth)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement