Whole file

mgedmin/objgraph

The author described this change as Fix python3 compatibility, and fix docstrings.. It counts as a record because the check below fails on the code as it stood at 34a1b76d3 and passes on 0ff6d0b3b, with nothing else changed between the two runs.

Fix saved2015-02-25
Sharing licenceMIT · LICENSE
Change size+722 717

What the code was meant to do, written into the code itself as a save note

Fix python3 compatibility, and fix docstrings.

The change

4444 import tempfile
4545 import sys
4646 import itertools
47-import types
48-
49-
50-try:
51- basestring
52-except NameError:
53- # Python 3.x compatibility
54- basestring = str
55-
56-try:
57- iteritems = dict.iteritems
58-except AttributeError:
59- # Python 3.x compatibility
60- iteritems = dict.items
61-
62-
63-def count(typename, objects=None):
64- """Count objects tracked by the garbage collector with a given class name.
65-
66- Example:
67-
68- >>> count('dict')
69- 42
70- >>> count('MyClass', get_leaking_objects())
71- 3
72- >>> count('mymodule.MyClass')
73- 2
74-
75- Note that the GC does not track simple objects like int or str.
76-
77- .. versionchanged:: 1.7
78- New parameter: ``objects``.
79-
80- .. versionchanged:: 1.8
81- Accepts fully-qualified type names (i.e. 'package.module.ClassName')
82- as well as short type names (i.e. 'ClassName').
83-
84- """
85- if objects is None:
86- objects = gc.get_objects()
87- if '.' in typename:
88- return sum(1 for o in objects if _long_typename(o) == typename)
89- else:
90- return sum(1 for o in objects if _short_typename(o) == typename)
91-
92-
93-def typestats(objects=None, shortnames=True):
94- """Count the number of instances for each type tracked by the GC.
95-
96- Note that the GC does not track simple objects like int or str.
97-
98- Note that classes with the same name but defined in different modules
99- will be lumped together if ``shortnames`` is True.
100-
101- Example:
102-
103- >>> typestats()
104- {'list': 12041, 'tuple': 10245, ...}
105- >>> typestats(get_leaking_objects())
106- {'MemoryError': 1, 'tuple': 2795, 'RuntimeError': 1, 'list': 47, ...}
107-
108- .. versionadded:: 1.1
109-
110- .. versionchanged:: 1.7
111- New parameter: ``objects``.
112-
113- .. versionchanged:: 1.8
114- New parameter: ``shortnames``.
115-
116- """
117- if objects is None:
118- objects = gc.get_objects()
119- if shortnames:
120- typename = _short_typename
121- else:
122- typename = _long_typename
123- stats = {}
124- for o in objects:
125- n = typename(o)
126- stats[n] = stats.get(n, 0) + 1
127- return stats
128-
129-
130-def most_common_types(limit=10, objects=None, shortnames=True):
131- """Count the names of types with the most instances.
132-
133- Returns a list of (type_name, count), sorted most-frequent-first.
134-
135- Limits the return value to at most ``limit`` items. You may set ``limit``
136- to None to avoid that.
137-
138- The caveats documented in :func:`typestats` apply.
139-
140- Example:
141-
142- >>> most_common_types(limit=2)
143- [('list', 12041), ('tuple', 10245)]
144-
145- .. versionadded:: 1.4
146-
147- .. versionchanged:: 1.7
148- New parameter: ``objects``.
149-
150- .. versionchanged:: 1.8
151- New parameter: ``shortnames``.
152-
153- """
154- stats = sorted(typestats(objects, shortnames=shortnames).items(),
155- key=operator.itemgetter(1), reverse=True)
156- if limit:
157- stats = stats[:limit]
158- return stats
159-
160-
161-def show_most_common_types(limit=10, objects=None, shortnames=True):
162- """Print the table of types of most common instances.
163-
164- The caveats documented in :func:`typestats` apply.
165-
166- Example:
167-
168- >>> show_most_common_types(limit=5)
169- tuple 8959
170- function 2442
171- wrapper_descriptor 1048
172- dict 953
173- builtin_function_or_method 800
174-
175- .. versionadded:: 1.1
176-
177- .. versionchanged:: 1.7
178- New parameter: ``objects``.
179-
180- .. versionchanged:: 1.8
181- New parameter: ``shortnames``.
182-
183- """
184- stats = most_common_types(limit, objects, shortnames=shortnames)
185- width = max(len(name) for name, count in stats)
186- for name, count in stats:
187- print('%-*s %i' % (width, name, count))
188-
189-
190-def show_growth(limit=10, peak_stats={}, shortnames=True):
191- """Show the increase in peak object counts since last call.
192-
193- Limits the output to ``limit`` largest deltas. You may set ``limit`` to
194- None to see all of them.
195-
196- Uses and updates ``peak_stats``, a dictionary from type names to previously
197- seen peak object counts. Usually you don't need to pay attention to this
198- argument.
199-
200- The caveats documented in :func:`typestats` apply.
201-
202- Example:
203-
204- >>> objgraph.show_growth()
205- wrapper_descriptor 970 +14
206- tuple 12282 +10
207- dict 1922 +7
208- ...
209-
210- .. versionadded:: 1.5
211-
212- .. versionchanged:: 1.8
213- New parameter: ``shortnames``.
214-
215- """
216- gc.collect()
217- stats = typestats(shortnames=shortnames)
218- deltas = {}
219- for name, count in iteritems(stats):
220- old_count = peak_stats.get(name, 0)
221- if count > old_count:
222- deltas[name] = count - old_count
223- peak_stats[name] = count
224- deltas = sorted(deltas.items(), key=operator.itemgetter(1),
225- reverse=True)
226- if limit:
227- deltas = deltas[:limit]
228- if deltas:
229- width = max(len(name) for name, count in deltas)
230- for name, delta in deltas:
231- print('%-*s%9d %+9d' % (width, name, stats[name], delta))
232-
233-
234-def get_leaking_objects(objects=None):
235- """Return objects that do not have any referents.
236-
237- These could indicate reference-counting bugs in C code. Or they could
238- be legitimate.
239-
240- Note that the GC does not track simple objects like int or str.
241-
242- .. versionadded:: 1.7
243- """
244- if objects is None:
245- gc.collect()
246- objects = gc.get_objects()
247- try:
248- ids = set(id(i) for i in objects)
249- for i in objects:
250- ids.difference_update(id(j) for j in gc.get_referents(i))
251- # this then is our set of objects without referrers
252- return [i for i in objects if id(i) in ids]
253- finally:
254- objects = i = None # clear cyclic references to frame
255-
256-
257-def by_type(typename, objects=None):
258- """Return objects tracked by the garbage collector with a given class name.
259-
260- Example:
261-
262- >>> by_type('MyClass')
263- [<mymodule.MyClass object at 0x...>]
264-
265- Note that the GC does not track simple objects like int or str.
266-
267- .. versionchanged:: 1.7
268- New parameter: ``objects``.
269-
270- .. versionchanged:: 1.8
271- Accepts fully-qualified type names (i.e. 'package.module.ClassName')
272- as well as short type names (i.e. 'ClassName').
273-
274- """
275- if objects is None:
276- objects = gc.get_objects()
277- if '.' in typename:
278- return [o for o in objects if _long_typename(o) == typename]
279- else:
280- return [o for o in objects if _short_typename(o) == typename]
281-
282-
283-def at(addr):
284- """Return an object at a given memory address.
285-
286- The reverse of id(obj):
287-
288- >>> at(id(obj)) is obj
289- True
290-
291- Note that this function does not work on objects that are not tracked by
292- the GC (e.g. ints or strings).
293- """
294- for o in gc.get_objects():
295- if id(o) == addr:
296- return o
297- return None
298-
299-
300-def find_ref_chain(obj, predicate, max_depth=20, extra_ignore=()):
301- """Find a shortest chain of references leading from obj.
302-
303- The end of the chain will be some object that matches your predicate.
304-
305- ``predicate`` is a function taking one argument and returning a boolean.
306-
307- ``max_depth`` limits the search depth.
308-
309- ``extra_ignore`` can be a list of object IDs to exclude those objects from
310- your search.
311-
312- Example:
313-
314- >>> find_ref_chain(obj, lambda x: isinstance(x, MyClass))
315- [obj, ..., <MyClass object at ...>]
316-
317- Returns ``[obj]`` if such a chain could not be found.
318-
319- .. versionadded:: 1.7
320- """
321- return _find_chain(obj, predicate, gc.get_referents,
322- max_depth=max_depth, extra_ignore=extra_ignore)[::-1]
323-
324-
325-def find_backref_chain(obj, predicate, max_depth=20, extra_ignore=()):
326- """Find a shortest chain of references leading to obj.
327-
328- The start of the chain will be some object that matches your predicate.
329-
330- ``predicate`` is a function taking one argument and returning a boolean.
331-
332- ``max_depth`` limits the search depth.
333-
334- ``extra_ignore`` can be a list of object IDs to exclude those objects from
335- your search.
336-
337- Example:
338-
339- >>> find_backref_chain(obj, is_proper_module)
340- [<module ...>, ..., obj]
341-
342- Returns ``[obj]`` if such a chain could not be found.
343-
344- .. versionchanged:: 1.5
345- Returns ``obj`` instead of ``None`` when a chain could not be found.
346-
347- """
348- return _find_chain(obj, predicate, gc.get_referrers,
349- max_depth=max_depth, extra_ignore=extra_ignore)
350-
351-
352-def show_backrefs(objs, max_depth=3, extra_ignore=(), filter=None, too_many=10,
353- highlight=None, filename=None, extra_info=None,
354- refcounts=False, shortnames=True, output=None):
355- """Generate an object reference graph ending at ``objs``.
356-
357- The graph will show you what objects refer to ``objs``, directly and
358- indirectly.
359-
360- ``objs`` can be a single object, or it can be a list of objects. If
361- unsure, wrap the single object in a new list.
362-
363- ``filename`` if specified, can be the name of a .dot or a image
364- file, whose extension indicates the desired output format; note
365- that output to a specific format is entirely handled by GraphViz:
366- if the desired format is not supported, you just get the .dot
367- file. If ``filename`` and ``output`` is not specified, ``show_backrefs``
368- will try to produce a .dot file and spawn a viewer (xdot). If xdot is
369- not available, ``show_backrefs`` will convert the .dot file to a
370- .png and print its name.
371-
372- ``output`` if specified, the GraphViz output will be written to this
373- file object. ``output`` and ``filename`` should not both be specified.
374-
375- Use ``max_depth`` and ``too_many`` to limit the depth and breadth of the
376- graph.
377-
378- Use ``filter`` (a predicate) and ``extra_ignore`` (a list of object IDs) to
379- remove undesired objects from the graph.
380-
381- Use ``highlight`` (a predicate) to highlight certain graph nodes in blue.
382-
383- Use ``extra_info`` (a function taking one argument and returning a
384- string) to report extra information for objects.
385-
386- Specify ``refcounts=True`` if you want to see reference counts.
387- These will mostly match the number of arrows pointing to an object,
388- but can be different for various reasons.
389-
390- Specify ``shortnames=False`` if you want to see fully-qualified type
391- names ('package.module.ClassName'). By default you get to see only the
392- class name part.
393-
394- Examples:
395-
396- >>> show_backrefs(obj)
397- >>> show_backrefs([obj1, obj2])
398- >>> show_backrefs(obj, max_depth=5)
399- >>> show_backrefs(obj, filter=lambda x: not inspect.isclass(x))
400- >>> show_backrefs(obj, highlight=inspect.isclass)
401- >>> show_backrefs(obj, extra_ignore=[id(locals())])
402-
403- .. versionchanged:: 1.3
404- New parameters: ``filename``, ``extra_info``.
405-
406- .. versionchanged:: 1.5
407- New parameter: ``refcounts``.
408-
409- .. versionchanged:: 1.8
410- New parameter: ``shortnames``.
411-
412- .. versionchanged:: 1.9
413- New parameter: ``output``.
414-
415- """
416- _show_graph(objs, max_depth=max_depth, extra_ignore=extra_ignore,
417- filter=filter, too_many=too_many, highlight=highlight,
418- edge_func=gc.get_referrers, swap_source_target=False,
419- filename=filename, output=output, extra_info=extra_info, refcounts=refcounts,
420- shortnames=shortnames)
421-
422-
423-def show_refs(objs, max_depth=3, extra_ignore=(), filter=None, too_many=10,
424- highlight=None, filename=None, extra_info=None,
425- refcounts=False, shortnames=True, output=None):
426- """Generate an object reference graph starting at ``objs``.
427-
428- The graph will show you what objects are reachable from ``objs``, directly
429- and indirectly.
430-
431- ``objs`` can be a single object, or it can be a list of objects. If
432- unsure, wrap the single object in a new list.
433-
434- ``filename`` if specified, can be the name of a .dot or a image
435- file, whose extension indicates the desired output format; note
436- that output to a specific format is entirely handled by GraphViz:
437- if the desired format is not supported, you just get the .dot
438- file. If ``filename`` and ``output`` is not specified, ``show_refs`` will
439- try to produce a .dot file and spawn a viewer (xdot). If xdot is
440- not available, ``show_refs`` will convert the .dot file to a
441- .png and print its name.
442-
443- ``output`` if specified, the GraphViz output will be written to this
1045 further changed lines not shown

The check that tells the two apart

failpass·tests.py::ShowGraphTest::test_basic_file_output

Check file tests.py, taken without changes from the fix and copied onto the older code, so the exact same check runs against both versions.

Origin and history

The code before it34a1b76d3c75682c2242da2de1ec6758e05668cf
Broken version dated2015-02-25
Moduleobjgraph
Units changed_get_obj_type
Fingerprint9107990b9af291c5
Checked2026-08-18 by goldset/0.1

Every field above is generated by our program. None of it is written by hand.