### Add deadsnakes PPA and install Python versions Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Add the deadsnakes PPA and install multiple Python versions on Ubuntu. ```bash sudo add-apt-repository -y ppa:deadsnakes sudo apt-get update sudo apt-get install python3.{6,7,8,9} ``` -------------------------------- ### Show Forward Reference Chain Source: https://github.com/mgedmin/objgraph/blob/master/docs/chain.md Visualizes the chain of references from a starting object to an object matching a specific condition. Ensure objgraph is installed and the target object is reachable from the starting object. ```Python >>> class MyUnpicklableObject(object): ... def __getstate__(self): ... raise NotImplementedError ... >>> my_object = dict(foo=dict(unrelated='things'), ... bar=[dict(nesting='fun'), ... dict(boobytrap=MyUnpicklableObject())]) >>> import objgraph >>> objgraph.show_chain( ... objgraph.find_ref_chain( ... my_object, ... lambda x: isinstance(x, MyUnpicklableObject)), ... backrefs=False, ... filename='forward-chain.png') Graph written to ...dot (4 nodes) Image generated as forward-chain.png ``` -------------------------------- ### Release process command Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Run the make release command to get instructions for making a new release. This command is safe to run anytime. ```bash make release ``` -------------------------------- ### Define a simple Node class Source: https://github.com/mgedmin/objgraph/blob/master/docs/highlighting.txt This snippet defines a basic class used to create a graph structure for demonstration purposes. It's a prerequisite for the highlighting example. ```Python class Node(object): def __init__(self, *neighbours): self.neighbours = list(neighbours) a = Node() b = Node(a) c = Node(b) d = Node(c) a.neighbours.append(d) ``` -------------------------------- ### Clone the objgraph repository Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Get the latest source code for objgraph from GitHub. ```bash git clone https://github.com/mgedmin/objgraph ``` -------------------------------- ### Find and Show Reference Chain Source: https://github.com/mgedmin/objgraph/blob/master/docs/chain.txt Uses objgraph to find a reference chain from a starting object to an instance of MyUnpicklableObject and generates a PNG image of the chain. ```python import objgraph objgraph.show_chain( objgraph.find_ref_chain( my_object, lambda x: isinstance(x, MyUnpicklableObject)), backrefs=False, filename='forward-chain.png') ``` -------------------------------- ### Show Object References Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.txt Generates a graph of object references starting from specified roots. Useful for debugging memory leaks. Ensure the graphviz 'dot' executable is in your PATH. ```python objgraph.show_refs(roots[:3], refcounts=True, filename='roots.png') ``` -------------------------------- ### Show Most Common Object Types Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.txt Displays a list of the most common object types currently in memory, along with their counts. Useful for getting a high-level overview of memory usage. ```python >>> objgraph.show_most_common_types() # doctest: +RANDOM_OUTPUT tuple 5224 function 1329 wrapper_descriptor 967 dict 790 builtin_function_or_method 658 method_descriptor 340 weakref 322 list 168 member_descriptor 167 type 163 ``` -------------------------------- ### Track Object Growth Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.md Show the growth in object counts since the last call to show_growth or since program start. Useful for identifying newly created objects that might indicate a memory leak. The 'limit' parameter restricts the output to the top N growing types. ```python >>> objgraph.show_growth(limit=3) ``` ```python >>> computate_something() >>> objgraph.show_growth() ``` -------------------------------- ### Get and Analyze Leaking Objects Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.txt Retrieves objects that might be leaking memory by identifying objects not properly deallocated. Used in conjunction with show_most_common_types to analyze potential leaks. ```python >>> roots = objgraph.get_leaking_objects() >>> len(roots) # doctest: +RANDOM_OUTPUT 4621 ``` ```python >>> objgraph.show_most_common_types(objects=roots) ... # doctest: +RANDOM_OUTPUT tuple 4333 dict 171 list 74 instancemethod 4 listiterator 2 MemoryError 1 Sub 1 RuntimeError 1 Param 1 Add 1 ``` -------------------------------- ### Manual restview command for PyPI description Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Manually preview the PyPI long description using restview with a command that executes setup.py. ```bash restview -e "python setup.py --long-description" ``` -------------------------------- ### Clean, build images, and documentation Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Clean previous build artifacts, generate images, and rebuild the documentation. ```bash make clean images docs ``` -------------------------------- ### Preview PyPI long description with restview Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Use a make rule to preview the PyPI long description, which is generated by concatenating README.rst and CHANGES.rst. ```bash make preview-pypi-description ``` -------------------------------- ### Run the test suite Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Execute the test suite to ensure the project is functioning correctly. This primarily checks for crashes. ```bash make test ``` -------------------------------- ### Configure git for imgdiff comparison Source: https://github.com/mgedmin/objgraph/blob/master/HACKING.rst Set up git to use imgdiff for comparing PNG files, useful for reviewing documentation image changes. ```bash git config diff.imgdiff.command 'f() { imgdiff $1 $2; }; f' git diff docs/*.png ``` -------------------------------- ### Activate and Iterate a Generator Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.md Instantiate the generator and retrieve its first value using next(). This shows how to activate a generator. ```pycon >>> it = count_to_three() >>> next(it) 1 ``` -------------------------------- ### Check Source Tarball Completeness Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Run this command to ensure that source tarballs generated with `python setup.py sdist` are not missing any files. This is automatically performed by `make release`. ```bash make distcheck ``` -------------------------------- ### Configure git for image diffing with options Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Configure git to use imgdiff with specific options for easier visual comparison of image changes. ```bash git config diff.imgdiff.command 'f() { imgdiff $1 $2; }; f' ``` -------------------------------- ### Generate Reference Graph for All Characters Source: https://github.com/mgedmin/objgraph/blob/master/docs/quoting.txt Use objgraph.show_refs to create a graph visualizing references for a dictionary containing all 256 possible characters. Set 'too_many' to a value greater than the number of nodes to ensure all are included. The output file is specified by the 'filename' argument. ```python import objgraph all_the_chars = dict((chr(i), i) for i in range(256)) objgraph.show_refs(all_the_chars, too_many=600, filename='all-the-chars.dot') ``` -------------------------------- ### Run tests with tox for multiple Python versions Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Use tox to run the test suite across all supported Python versions. ```bash tox -p auto ``` -------------------------------- ### Configure git for image diffing Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Configure git to use imgdiff for comparing image differences, useful for debugging test failures. ```bash git config diff.imgdiff.command 'f() { imgdiff --eog -H $1 $2; }; f' ``` -------------------------------- ### View image differences Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md View the differences between generated images using git diff. ```bash git diff docs/*.png ``` -------------------------------- ### Configure git for enhanced imgdiff comparison Source: https://github.com/mgedmin/objgraph/blob/master/HACKING.rst Configure git to use imgdiff with specific options (--eog -H) for a more detailed comparison of PNG images. ```bash git config diff.imgdiff.command 'f() { imgdiff --eog -H $1 $2; }; f' git diff docs/*.png ``` -------------------------------- ### Highlight Node instances in object graph Source: https://github.com/mgedmin/objgraph/blob/master/docs/highlighting.txt Use objgraph.show_backrefs to visualize object references and highlight nodes that are instances of the Node class. This helps in understanding the structure of the graph. ```Python import objgraph objgraph.show_backrefs(a, max_depth=15, extra_ignore=[id(locals())], highlight=lambda x: isinstance(x, Node), filename='highlight.png') # doctest: +NODES_VARY ``` -------------------------------- ### Show Object References Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.txt Generates a graph of objects reachable from a given set of objects. Useful for visualizing object relationships. ```python >>> x = [] >>> y = [x, [x], dict(x=x)] >>> import objgraph >>> objgraph.show_refs([y], filename='sample-graph.png') ``` -------------------------------- ### objgraph.show_growth Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Prints object growth statistics to a file. ```APIDOC ## objgraph.show_growth ### Description Prints object growth statistics to a file. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **limit** (int, optional) - The maximum number of types to track. Defaults to 10. - **peak_stats** (dict, optional) - A dictionary to store peak statistics. Defaults to an empty dictionary. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. - **file** (file-like object, optional) - The file to write to. Defaults to sys.stdout. - **filter** (callable, optional) - A filter function to apply to objects. ``` -------------------------------- ### Generate images for visual testing Source: https://github.com/mgedmin/objgraph/blob/master/HACKING.rst Create visual representations of object graphs for manual inspection. This is useful for identifying subtle output errors. ```bash make images ``` -------------------------------- ### objgraph.at Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Returns an object at a given memory address. ```APIDOC ## objgraph.at ### Description Returns an object at a given memory address. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **address** (int) - Required - The memory address of the object. ``` -------------------------------- ### objgraph.show_chain Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Displays a reference chain. ```APIDOC ## objgraph.show_chain ### Description Displays a reference chain. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **chain** (iterable) - Required - The chain of objects to display. - **highlight** (callable, optional) - A callable to highlight specific objects. - **filename** (string, optional) - The file to save the graph to. - **extra_info** (callable, optional) - A callable to add extra information to nodes. - **refcounts** (bool, optional) - If True, display reference counts. Defaults to False. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. ``` -------------------------------- ### Visualize Object Reference Chain to Module Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.txt Generates a graph showing a specific reference chain from a module to a 'Canary' object. This technique is useful for debugging garbage collection issues. ```python objgraph.show_chain( objgraph.find_backref_chain(objgraph.by_type('Canary')[0], objgraph.is_proper_module), filename='canary-chain.png') ``` -------------------------------- ### Visualize Object Back References Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.txt Generates a graph visualizing the objects that hold a reference to 'Canary' objects. This is useful for understanding object relationships and memory retention. Requires 'Canary' objects to be present. ```python objgraph.show_backrefs(objgraph.by_type('Canary'), max_depth=7, filename='canary.png') ``` -------------------------------- ### Generate Graph with Highlighted Nodes Source: https://github.com/mgedmin/objgraph/blob/master/docs/highlighting.md Generates a back-reference graph, highlighting nodes that are instances of the Node class. This requires the objgraph library to be imported. ```python import objgraph >>> objgraph.show_backrefs(a, max_depth=15, ... extra_ignore=[id(locals())], ... highlight=lambda x: isinstance(x, Node), ... filename='highlight.png') Graph written to ....dot (12 nodes) Image generated as highlight.png ``` -------------------------------- ### objgraph.show_refs Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Displays references for a set of objects. ```APIDOC ## objgraph.show_refs ### Description Displays references for a set of objects. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **objs** (iterable) - Required - The objects to find references for. - **max_depth** (int, optional) - The maximum depth to search. Defaults to 3. - **extra_ignore** (iterable, optional) - An iterable of objects to ignore. - **filter** (callable, optional) - A filter function to apply. - **too_many** (int, optional) - The threshold for too many references. Defaults to 10. - **highlight** (callable, optional) - A callable to highlight specific objects. - **filename** (string, optional) - The file to save the graph to. - **extra_info** (callable, optional) - A callable to add extra information to nodes. - **refcounts** (bool, optional) - If True, display reference counts. Defaults to False. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. ``` -------------------------------- ### Visualize Reference Chain to Module Root Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.md Trace and visualize the reference chain from a specific object back to a module root. This is crucial for diagnosing memory leaks by showing what is keeping an object alive. Requires graphviz for image generation. ```python >>> import random >>> objgraph.show_chain( ... objgraph.find_backref_chain( ... random.choice(objgraph.by_type('MyBigFatObject')), ... objgraph.is_proper_module), ... filename='chain.png') ``` -------------------------------- ### Define a Custom Class Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.md Define a simple custom class named 'Canary'. This is used to demonstrate object tracking. ```pycon >>> class Canary(object): ... pass ``` -------------------------------- ### Visualize Object Back-references Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.md Use objgraph.show_backrefs() to visualize all objects that hold a reference to instances of 'Canary'. This is useful for debugging memory leaks. Specify max_depth and output filename. ```pycon >>> objgraph.show_backrefs(objgraph.by_type('Canary'), ... max_depth=7, ... filename='canary.png') Graph written to ....dot (15 nodes) Image generated as canary.png ``` -------------------------------- ### Define a Custom Class Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.txt Defines a simple custom class named 'Canary'. This is a basic building block for demonstrating object tracking. ```python class Canary(object): pass ``` -------------------------------- ### Visualize Reference Chain to a Module Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.md Use objgraph.show_chain() to visualize a specific reference chain leading from a module to a target object. This helps in understanding garbage collection roots. ```pycon >>> objgraph.show_chain( ... objgraph.find_backref_chain(objgraph.by_type('Canary')[0], ... objgraph.is_proper_module), ... filename='canary-chain.png') Graph written to ....dot (11 nodes) Image generated as canary-chain.png ``` -------------------------------- ### Generate HTML test coverage report Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Generate an HTML report for test coverage, which can be browsed in a web browser. ```bash make coverage coverage html ``` -------------------------------- ### Show Object Backreferences Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.txt Generates a graph of objects that reference a given set of objects. Helps in understanding what objects are holding onto a specific object. ```python >>> objgraph.show_backrefs([x], filename='sample-backref-graph.png') ``` -------------------------------- ### Show References with All Characters Source: https://github.com/mgedmin/objgraph/blob/master/docs/quoting.md Generates a graph of references for a dictionary containing all 256 ASCII characters. Use this to test how quoting handles a wide range of characters. The 'too_many' parameter is set to a high value to ensure all references are included. ```python >>> import objgraph >>> all_the_chars = dict((chr(i), i) for i in range(256)) >>> objgraph.show_refs(all_the_chars, too_many=600, ... filename='all-the-chars.dot') Graph written to all-the-chars.dot (... nodes) ``` -------------------------------- ### Compare generated images with previous versions Source: https://github.com/mgedmin/objgraph/blob/master/HACKING.rst Use imgdiff to visually compare generated PNG images of object graphs. This helps in identifying unintended changes. ```bash make images PYTHON=pythonX.Y git config diff.imgdiff.command 'f() { imgdiff --eog -H $1 $2; }; f' git diff docs/*.png ``` -------------------------------- ### objgraph.at_addrs Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Returns objects at a given set of memory addresses. ```APIDOC ## objgraph.at_addrs ### Description Returns objects at a given set of memory addresses. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **address_set** (set of int) - Required - A set of memory addresses. ``` -------------------------------- ### Visualize Backreferences with Reference Counts Source: https://github.com/mgedmin/objgraph/blob/master/docs/references.md Enable reference counts in `show_backrefs` to display the number of references to each object. This helps in understanding the exact reference counts, though interpreter internals might add extra references. ```python >>> import sys >>> one_reference = object() >>> objgraph.show_backrefs([one_reference], refcounts=True, ... filename='refcounts.png') ``` -------------------------------- ### objgraph.show_most_common_types Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Prints the most common object types to a file. ```APIDOC ## objgraph.show_most_common_types ### Description Prints the most common object types to a file. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **limit** (int, optional) - The maximum number of types to print. Defaults to 10. - **objects** (iterable, optional) - An iterable of objects to consider. If not provided, all objects are considered. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. - **file** (file-like object, optional) - The file to write to. Defaults to sys.stdout. ``` -------------------------------- ### Show Object Growth Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.txt Tracks and displays the increase in object counts between two points in time. Essential for identifying potential memory leaks by observing newly created objects. ```python >>> objgraph.show_growth(limit=3) # doctest: +RANDOM_OUTPUT tuple 5228 +5228 function 1330 +1330 wrapper_descriptor 967 +967 ``` ```python >>> computate_something() >>> objgraph.show_growth() # doctest: +RANDOM_OUTPUT MyBigFatObject 2 +2 dict 797 +1 ``` -------------------------------- ### Generate images for visual debugging Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Generate images for visual debugging, specifying a Python version. This is useful when tests fail. ```bash make images PYTHON=pythonX.Y ``` -------------------------------- ### Create a Generator Using a Custom Class Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.md Define a generator function that instantiates and uses the custom 'Canary' class. This generator yields numbers. ```pycon >>> def count_to_three(): ... tweety = Canary() ... yield 1 ... yield 2 ... yield 3 ``` -------------------------------- ### Visualizing Classes with Finalizers Source: https://github.com/mgedmin/objgraph/blob/master/docs/uncollectable.txt This code uses `objgraph.show_refs` to visualize the references of a class that defines a `__del__` method. Unlike instances in cycles, the class definition itself is not considered uncollectable garbage. ```python import objgraph objgraph.show_refs(Nondestructible, max_depth=1, filename='class-with-finalizers.png') ``` -------------------------------- ### Visualize Object References Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.md Generate a graph of object references for a subset of objects, including reference counts. This is useful for visually debugging complex reference chains and potential leaks. ```python >>> objgraph.show_refs(roots[:3], refcounts=True, filename='roots.png') ... Graph written to ...dot (19 nodes) Image generated as roots.png ``` -------------------------------- ### Revert changed image and dot files Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Discard changes to image and dot files in the docs directory. ```bash git checkout -- docs/*.png docs/*.dot ``` -------------------------------- ### Create a Generator Using a Custom Class Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.txt Defines a generator function that instantiates and uses the custom 'Canary' class. It yields numbers from 1 to 3. ```python def count_to_three(): tweety = Canary() yield 1 yield 2 yield 3 ``` -------------------------------- ### objgraph.growth Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Tracks object growth over time. ```APIDOC ## objgraph.growth ### Description Tracks object growth over time. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **limit** (int, optional) - The maximum number of types to track. Defaults to 10. - **peak_stats** (dict, optional) - A dictionary to store peak statistics. Defaults to an empty dictionary. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. - **filter** (callable, optional) - A filter function to apply to objects. ``` -------------------------------- ### Visualize classes with __del__ methods using objgraph Source: https://github.com/mgedmin/objgraph/blob/master/docs/uncollectable.md This snippet uses `objgraph.show_refs` to visualize the references originating from a class that defines a `__del__` method, specifically `Nondestructible`. This helps distinguish between instances that are uncollectable and the class definition itself. The output is saved to `class-with-finalizers.png`. ```python objgraph.show_refs(Nondestructible, max_depth=1, filename='class-with-finalizers.png') ``` -------------------------------- ### Visualizing Uncollectable Objects with objgraph Source: https://github.com/mgedmin/objgraph/blob/master/docs/uncollectable.txt This snippet uses `objgraph.show_backrefs` to visualize the back-references of uncollectable objects, specifically highlighting instances of 'Nondestructible'. This helps in understanding why they are not collected. ```python import objgraph objgraph.show_backrefs(objgraph.by_type('Nondestructible'), filename='finalizers.png') ``` -------------------------------- ### Generate test coverage report Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Generate a test coverage report to identify areas not covered by tests. ```bash make coverage ``` -------------------------------- ### Activate and Iterate a Generator Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.txt Activates the 'count_to_three' generator and retrieves the first yielded value using next(). ```python it = count_to_three() next(it) ``` -------------------------------- ### objgraph.by_type Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Returns all objects of a given type. ```APIDOC ## objgraph.by_type ### Description Returns all objects of a given type. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **typename** (string) - Required - The name of the type to filter by. - **objects** (iterable, optional) - An iterable of objects to consider. If not provided, all objects are considered. ``` -------------------------------- ### objgraph.show_backrefs Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Displays back-references for a set of objects. ```APIDOC ## objgraph.show_backrefs ### Description Displays back-references for a set of objects. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **objs** (iterable) - Required - The objects to find back-references for. - **max_depth** (int, optional) - The maximum depth to search. Defaults to 3. - **extra_ignore** (iterable, optional) - An iterable of objects to ignore. - **filter** (callable, optional) - A filter function to apply. - **too_many** (int, optional) - The threshold for too many references. Defaults to 10. - **highlight** (callable, optional) - A callable to highlight specific objects. - **filename** (string, optional) - The file to save the graph to. - **extra_info** (callable, optional) - A callable to add extra information to nodes. - **refcounts** (bool, optional) - If True, display reference counts. Defaults to False. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. ``` -------------------------------- ### Highlight code coverage in Vim Source: https://github.com/mgedmin/objgraph/blob/master/docs/HACKING.md Use a Vim plugin to highlight lines not covered by tests while editing code. ```bash make coverage vim objgraph.py :HighlightCoverage ``` -------------------------------- ### Count Instances of a Custom Class Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.txt Uses objgraph.count() to determine the number of live 'Canary' objects in memory. This helps verify object existence. ```python import objgraph objgraph.count('Canary') ``` -------------------------------- ### Show Reference Chain to Module Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.txt Visualizes the chain of references from a garbage collector root (like a module) to a specific object. Helps in debugging memory leaks by tracing object lifecycles. ```python >>> import random >>> objgraph.show_chain( ... objgraph.find_backref_chain( ... random.choice(objgraph.by_type('MyBigFatObject')), ... objgraph.is_proper_module), ... filename='chain.png') # doctest: +NODES_VARY Graph written to ...dot (13 nodes) Image generated as chain.png ``` -------------------------------- ### Adding Object IDs to References Source: https://github.com/mgedmin/objgraph/blob/master/docs/extra-info.md Use the `extra_info` parameter in `objgraph.show_refs` to display object IDs. This helps in identifying specific objects within the graph. Ensure `objgraph` is imported. ```python >>> x = [] >>> y = [x, [x], dict(x=x)] >>> import objgraph >>> objgraph.show_refs([y], extra_info=lambda x: hex(id(x)), ... filename='extra-info.png') Graph written to ....dot (... nodes) Image generated as extra-info.png ``` -------------------------------- ### Visualize uncollectable objects with objgraph Source: https://github.com/mgedmin/objgraph/blob/master/docs/uncollectable.md This snippet uses `objgraph.show_backrefs` to visualize the back-references of uncollectable objects of type `Nondestructible`. This helps in understanding the structure of the cycle and why they are uncollectable. The output is saved to `finalizers.png`. ```python objgraph.show_backrefs(objgraph.by_type('Nondestructible'), filename='finalizers.png') ``` -------------------------------- ### Visualize Backreferences with Truncation Source: https://github.com/mgedmin/objgraph/blob/master/docs/references.md Use `show_backrefs` to visualize objects pointing to a target object. The `too_many` parameter limits the displayed backreferences, and `max_depth` controls the graph depth. ```python >>> moo = 'moo' >>> refs_to_moo = [[moo] for n in range(42)] >>> objgraph.show_backrefs([moo], too_many=5, max_depth=1, filename='42.png') ``` -------------------------------- ### Show Most Common Types of Leaking Objects Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.md After identifying potential leaking objects, use show_most_common_types to see the distribution of their types. This helps in diagnosing the nature of the leaks. ```python >>> objgraph.show_most_common_types(objects=roots) ... tuple 4333 dict 171 list 74 instancemethod 4 listiterator 2 MemoryError 1 Sub 1 RuntimeError 1 Param 1 Add 1 ``` -------------------------------- ### Identify uncollectable objects using gc.garbage Source: https://github.com/mgedmin/objgraph/blob/master/docs/uncollectable.md After removing all external references to the cyclic objects and running the garbage collector, this snippet shows how to check `gc.garbage` to find the uncollectable objects. It verifies that one such object is present. ```python import objgraph del x, y, z import gc _ = gc.collect() len(gc.garbage) ``` -------------------------------- ### Define Node Class Source: https://github.com/mgedmin/objgraph/blob/master/docs/highlighting.md Defines a simple Node class with a list of neighbours, used for creating a sample object graph. ```python class Node(object): def __init__(self, *neighbours): self.neighbours = list(neighbours) >>> a = Node() >>> b = Node(a) >>> c = Node(b) >>> d = Node(c) >>> a.neighbours.append(d) ``` -------------------------------- ### Looking Up Objects by ID Source: https://github.com/mgedmin/objgraph/blob/master/docs/extra-info.md The `objgraph.at()` function allows you to retrieve an object using its ID, which is useful for inspecting objects identified in the graph. This function works for objects tracked by the cyclic garbage collector. ```python >>> objgraph.at(id(x)) is x True ``` -------------------------------- ### objgraph.typestats Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Returns statistics about object types. ```APIDOC ## objgraph.typestats ### Description Returns statistics about object types. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **objects** (iterable, optional) - An iterable of objects to consider. If not provided, all objects are considered. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. ``` -------------------------------- ### Visualize Objects with Too Many References Source: https://github.com/mgedmin/objgraph/blob/master/docs/references.md Use `show_refs` to visualize objects with a high number of references. The `too_many` parameter truncates the graph to avoid overwhelming detail. ```python import objgraph >>> objgraph.show_refs([list(range(7))], too_many=5, filename='too-many.png') ``` -------------------------------- ### Count Instances of a Custom Class Source: https://github.com/mgedmin/objgraph/blob/master/docs/generator-sample.md Use objgraph.count() to determine the number of instances of the 'Canary' class currently in memory. This helps in understanding object lifecycle. ```pycon >>> import objgraph >>> objgraph.count('Canary') 1 ``` -------------------------------- ### Add Object IDs to Graph Source: https://github.com/mgedmin/objgraph/blob/master/docs/extra-info.txt Use the 'extra_info' parameter to include object IDs in the generated graph. This helps in identifying specific objects later. ```python >>> x = [] >>> y = [x, [x], dict(x=x)] >>> import objgraph >>> objgraph.show_refs([y], extra_info=lambda x: hex(id(x)), ... filename='extra-info.png') ``` -------------------------------- ### Create a Nested Object Structure Source: https://github.com/mgedmin/objgraph/blob/master/docs/chain.txt Creates a complex nested dictionary containing instances of the custom unpicklable object to test reference chain finding. ```python my_object = dict(foo=dict(unrelated='things'), bar=[dict(nesting='fun'), dict(boobytrap=MyUnpicklableObject())]) ``` -------------------------------- ### objgraph.get_new_ids Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Retrieves newly created object IDs. ```APIDOC ## objgraph.get_new_ids ### Description Retrieves newly created object IDs. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **skip_update** (bool, optional) - If True, skip updating the object ID cache. Defaults to False. - **limit** (int, optional) - The maximum number of new IDs to return. Defaults to 10. - **sortby** (string, optional) - The key to sort the results by. Defaults to 'deltas'. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. - **file** (file-like object, optional) - The file to write to. Defaults to sys.stdout. ``` -------------------------------- ### Highlight lines not covered by tests in Vim Source: https://github.com/mgedmin/objgraph/blob/master/HACKING.rst Use a Vim plugin to visually highlight lines of code that are not covered by the test suite while editing. ```vim :HighlightCoverage ``` -------------------------------- ### objgraph.is_proper_module Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Checks if an object is a proper module. ```APIDOC ## objgraph.is_proper_module ### Description Checks if an object is a proper module. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **obj** (object) - Required - The object to check. ``` -------------------------------- ### objgraph.most_common_types Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Returns the most common object types. ```APIDOC ## objgraph.most_common_types ### Description Returns the most common object types. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **limit** (int, optional) - The maximum number of types to return. Defaults to 10. - **objects** (iterable, optional) - An iterable of objects to consider. If not provided, all objects are considered. - **shortnames** (bool, optional) - If True, use short type names. Defaults to True. ``` -------------------------------- ### Define an Unpicklable Object Source: https://github.com/mgedmin/objgraph/blob/master/docs/chain.txt Defines a custom class that raises an error when its state is requested, simulating an unpicklable object. ```python class MyUnpicklableObject(object): def __getstate__(self): raise NotImplementedError ``` -------------------------------- ### Limitations of `objgraph.at()` Source: https://github.com/mgedmin/objgraph/blob/master/docs/extra-info.md The `objgraph.at()` function does not work for immutable types like strings, integers, or other simple types that are not tracked by the cyclic garbage collector. Attempting to use it with such types will result in no output. ```python >>> a = 'a string' >>> objgraph.at(id(a)) ``` -------------------------------- ### Find Leaking Objects Source: https://github.com/mgedmin/objgraph/blob/master/docs/index.md Use get_leaking_objects() to find objects that may have reference counting bugs. Be aware that this will include legitimate GC roots. ```python >>> roots = objgraph.get_leaking_objects() >>> len(roots) 4621 ``` -------------------------------- ### objgraph.count Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Counts the number of objects of a given type. ```APIDOC ## objgraph.count ### Description Counts the number of objects of a given type. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **typename** (string) - Required - The name of the type to count. - **objects** (iterable, optional) - An iterable of objects to consider. If not provided, all objects are considered. ``` -------------------------------- ### Create a cyclic reference with an uncollectable object Source: https://github.com/mgedmin/objgraph/blob/master/docs/uncollectable.md This snippet demonstrates creating a cyclic reference involving an instance of `Nondestructible`. This cycle will cause the objects to be uncollectable by the garbage collector. ```python x = Nondestructible() y = [] z = [] x.append(y) y.append(z) z.append(x) ``` -------------------------------- ### objgraph.find_ref_chain Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Finds a reference chain from an object to a predicate. ```APIDOC ## objgraph.find_ref_chain ### Description Finds a reference chain from an object to a predicate. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **obj** (object) - Required - The starting object. - **predicate** (callable) - Required - A callable that returns True if the target is found. - **max_depth** (int, optional) - The maximum depth to search. Defaults to 20. - **extra_ignore** (iterable, optional) - An iterable of objects to ignore during the search. ``` -------------------------------- ### Collecting Uncollectable Garbage Source: https://github.com/mgedmin/objgraph/blob/master/docs/uncollectable.txt After removing external references to objects involved in a cycle, this code forces garbage collection and checks the `gc.garbage` list to confirm that one uncollectable object remains. ```python import gc del x, y, z _ = gc.collect() len(gc.garbage) ``` -------------------------------- ### objgraph.find_backref_chain Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Finds a back-reference chain from an object to a predicate. ```APIDOC ## objgraph.find_backref_chain ### Description Finds a back-reference chain from an object to a predicate. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **obj** (object) - Required - The starting object. - **predicate** (callable) - Required - A callable that returns True if the target is found. - **max_depth** (int, optional) - The maximum depth to search. Defaults to 20. - **extra_ignore** (iterable, optional) - An iterable of objects to ignore during the search. ``` -------------------------------- ### Define a class with a __del__ method Source: https://github.com/mgedmin/objgraph/blob/master/docs/uncollectable.md This snippet defines a class `Nondestructible` that inherits from `list` and includes a `__del__` method. This method prevents instances of this class from being garbage collected if they are part of a cycle. ```python class Nondestructible(list): def __del__(self): pass ``` -------------------------------- ### objgraph.get_leaking_objects Source: https://github.com/mgedmin/objgraph/blob/master/docs/objgraph.txt Finds objects that might be leaking memory. ```APIDOC ## objgraph.get_leaking_objects ### Description Finds objects that might be leaking memory. ### Method N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **objects** (iterable, optional) - An iterable of objects to consider. If not provided, all objects are considered. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.