Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I worry about circular references in Python?

Tags:

python

Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.

I am concerned that they will not be garbage collected and the application will eventually consume all memory.

like image 756
bodacydo Avatar asked Mar 11 '10 20:03

bodacydo


People also ask

How do I stop circular dependency in python?

You can, however, use the imported module inside functions and code blocks that don't get run on import. Generally, in most valid cases of circular dependencies, it's possible to refactor or reorganize the code to prevent these errors and move module references inside a code block.

How do I fix the circular import error in python?

Change Name of working python script: Changing the name of the Working file different from the module which is imported in the script can avoid the Circular Imports problem. Import the module: Avoid importing objects or functions from a module that can cause Circular Imports.

Is circular reference possible in python destruction?

Output. In this case, reference counting is not going to destroy object A and object B beacause their reference count is non-zero and this is known as Circular References. Python memory manager cannot destroy these objects leading to Memory Leak.

What are circular references in python?

When two objects in Python holds reference of each other, it is termed as cyclic or circular reference. This occurs when object A's property refers to object B, and object B's property refers back to object A. Note: The objects can be of the same or of different classes.


1 Answers

"Worry" is misplaced, but if your program turns out to be slow, consume more memory than expected, or have strange inexplicable pauses, the cause is indeed likely to be in those garbage reference loops -- they need to be garbage collected by a different procedure than "normal" (acyclic) reference graphs, and that collection is occasional and may be slow if you have a lot of objects tied up in such loops (the cyclical-garbage collection is also inhibited if an object in the loop has a __del__ special method).

So, reference loops will not affect your program's correctness, but may affect its performance and/or footprint.

If and when you want to remove unwanted loops of references, you can often use the weakref module in Python's standard library.

If and when you want to exert more direct control (or perform debugging, see what exactly is happening) regarding cyclical garbage collection, use the gc module in Python's standard library.

like image 66
Alex Martelli Avatar answered Sep 27 '22 22:09

Alex Martelli