Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7971383
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T07:37:35+00:00 2026-06-04T07:37:35+00:00

I would to ask if using the Delegate Pattern in Python would lead to

  • 0

I would to ask if using the Delegate Pattern in Python would lead to circular references and if so, what would be the best way to implement it to ensure the object and its delegate will be garbage collected?

In Objective C, the above problem is avoided by using a weak reference to the delegate. In C++, we don’t call delete on the delegate. I’ve found a link to Python’s weak reference module here: http://docs.python.org/library/weakref.html. It seems like a plausible approach might be to create a weak reference to refer to the instance variable using this module but I’m not sure.

As I’ve googled this question and was not able to find answers to it, I’m wondering whether this is even a problem in Python or if there is a common solution (without the need for the weakref module) that I’m unaware of? Also, I did search stackoverflow before asking but the questions I found either deal with circular imports or delegate pattern in general and not specific to Python and the problem of circular references.

Thanks in advance for any replies.

Listed below is some code for a toy example to help illustrate my question. I’ve implemented code in this way and it works but I’m not sure whether memory is garbage collected at the end.

class A(object):
    def __init__(self):
        self.delegate = None

        # Some other instance variables that keep track of state for performing some tasks.

    def doSomething(self):
        if self.delegate is not None:
            self.delegate.doSomething()
        else:
            print('Cannot perform task because delegate is not set.')

    # Other methods not shown.

class B(object):
    def __init__(self):
        self.a = A() # Need to keep object 'a' from garbage collected so as to preserve its state information.
        self.a.delegate = self  # Is this a circular reference? How to 'fix' it so that A and B will eventually be garbage collected?

    def doSomething(self):
        print('B doing something')

    # Other methods not shown.

EDIT:

After reading some of the replies, I decided to clarify my question. I understand that Python has garbage collection. What I wasn’t sure was whether it will perform garbage collection on circular referenced objects. My worries stems from the following passage from Python’s doc:

CPython implementation detail: CPython currently uses a
reference-counting scheme with (optional) delayed detection of
cyclically linked garbage, which collects most objects as soon as they
become unreachable, but is not guaranteed to collect garbage
containing circular references
. See the documentation of the gc module
for information on controlling the collection of cyclic garbage. Other
implementations act differently and CPython may change. Do not depend
on immediate finalization of objects when they become unreachable (ex:
always close files).

The passage in its original form can be found here: http://docs.python.org/reference/datamodel.html The bold setting is mine.

The following post provides a clearer explanation on the problem of circular referenced objects and why it would prevent garbage collection on those objects (at least in a typical setting): http://www.electricmonk.nl/log/2008/07/07/python-destructor-and-garbage-collection-notes/.

Further, I just came across Alex Martellli’s reply to the following question on whether Python users should worry about circular reference: Should I worry about circular references in Python? From his answer, I gather that even though circular referenced objects will eventually be garbage collected BUT there would be overheads. Whether it is significant depends on the program.

Further, he mentioned to use Python’s weakref module but did not explicitly say how.

Hence, I would like to add the following questions to clarify some unresolved issues:

  1. The docs say garbaged collection is not guaranteed for circular
    referenced objects. But from the replies it appears that is not the
    case. So have I misunderstood the passage or are there further
    details that I’ve missed?
  2. I suppose using a weak reference, as stated in Alex’s reply and my
    question, would avoid the overhead the problem entirely?

Again thanks for the replies.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T07:37:36+00:00Added an answer on June 4, 2026 at 7:37 am

    Python already does garbage collection. You only need to do something special if you write your own container types in C, as extensions.

    Demo: Run this program and watch the memory usage not climb.

    class C(object):
        pass
    
    def circular():
        for x in range(10**4):
            for y in range(10**4):
                a = C()
                b = C()
                a.x = b
                b.x = a
    
    circular()
    

    Footnote: The following function doesn’t do anything, delete it.

    def setDelegate(self, delegate):
        self.delegate = delegate
    

    Instead of calling x.setDelegate(y), you can use x.delegate = y. You can overload member access in Python, so there’s no benefit to writing a method.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Good afternoon, I would ask some suggestion about the best way to monitor events
I would like to ask your guidance on how to authenticate using email add/
Using Commons beanUtils I would like to know how to ask any converter say
I would like ask if there's a way to download an android layout from
I would ask a question regarding compilers, specifically how they work. I would believe
I made a function that would ask a player to enter a letter until
The question seems to be basic but I would ask. Is there a standard
I think I already know the answer to this but thought I would ask
I am not sure what this error is. Thought I would ask you guys
Lately I've been job hunting, and for the most part, they would ask me

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.