/Lib/test/crashers/gc_inspection.py

http://unladen-swallow.googlecode.com/ · Python · 32 lines · 3 code · 0 blank · 29 comment · 0 complexity · fb68a4f8c7554e6e21d832bf16f5b066 MD5 · raw file

  1. """
  2. gc.get_referrers() can be used to see objects before they are fully built.
  3. Note that this is only an example. There are many ways to crash Python
  4. by using gc.get_referrers(), as well as many extension modules (even
  5. when they are using perfectly documented patterns to build objects).
  6. Identifying and removing all places that expose to the GC a
  7. partially-built object is a long-term project. A patch was proposed on
  8. SF specifically for this example but I consider fixing just this single
  9. example a bit pointless (#1517042).
  10. A fix would include a whole-scale code review, possibly with an API
  11. change to decouple object creation and GC registration, and according
  12. fixes to the documentation for extension module writers. It's unlikely
  13. to happen, though. So this is currently classified as
  14. "gc.get_referrers() is dangerous, use only for debugging".
  15. """
  16. import gc
  17. def g():
  18. marker = object()
  19. yield marker
  20. # now the marker is in the tuple being constructed
  21. [tup] = [x for x in gc.get_referrers(marker) if type(x) is tuple]
  22. print tup
  23. print tup[1]
  24. tuple(g())