faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 2 people (50%) answered Yes

Entry

Circular references

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 309, Adrian Eyre


"""
Packages: oop;miscellaneous.introspection
"""
"""
>> I can dream up a million ways to kludge around this bug, but I
>> was referring to a 'fix' to the Python source code. How hard can
>> it be?
> It's unclear, but I can give you a lower bound:  in all the years
> people have been whining about how easy this is to "fix", nobody
> has managed to fix it.
How about this:
"""
import types
class Noisy:
    def __init__(self, name):
        self.name = name
        print "Created " + self.name
    def __del__(self):
        print "Destroyed " + self.name
# Only handles class instances (for now)
def mydel(obj, done = None):
    if done is None:
        done = []
    items = obj.__dict__.items()
    for key, value in items:
        if value in done:
            continue
        if type(value) != types.InstanceType:
            continue
        done.append(value)
        mydel(value, done[:])
        del obj.__dict__[key]
def main():
    a = Noisy("a")
    b = Noisy("b")
    a.b = b
    b.a = a
    mydel(a)
    del a
    mydel(b)
    del b
    print "End"
if __name__ == "__main__":
    main()
"""
If I can fix this in Python (admittedly for a limited set of
cases, but it should be easy enough to expand on), then why
not in C?
"""