-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

  I was playing around with different ways to
simulate what atexit does and found this very interesting
use-case with weak references.


import weakref

class C: pass

def goodbye(param):
    print 'Bye.',param

x=weakref.ref(C, goodbye)

if __name__ == '__main__':
    print 3+4
    print 8+9

If you run this you should see "Bye. <weakref at 0x8a4c11c; dead>"
getting printed at the end. The code makes use of the callable
option to weak references which would get called just before the
weak reference is garbage collected.

Here I am forcing the weak reference to remain in the global context
by assigning it to x. If you remove the assignment, the call doesn't
go through.

Don't advise anyone to use this code - it is just to illustrate the
one of the ways in which weak references can be used. In general
it is better not to rely on the order of gc in your code to
implement a feature.


- -- 
Regards,

- --Anand

-
--------------------------------------------------------------------------------------
Software Architect/Consultant
anandpil...@letterboxes.org

Please note my updated email address <anandpil...@letterboxes.org>.
Kindly update your address books.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iQEcBAEBAgAGBQJSLrWVAAoJEMTxYeOp9eaomgEH/j8sJDo9FiZaGYZOpsawrWdZ
IFVl/9dB194dVfDIGyIdVINjtZX6frPmdtSIIVV6t6S3wK3CAdlMBzEayJt1hyem
GLlg+X0XHdYx0cVbXRzTgHRzlfjErH67Y+zSl2byEMEJAHnSYmE2TiNUrCsSPxei
HA2Ff6nNjXopOuJqMwsPwUmbFBAb3VzIWBOnztHPB7+MA/i3pq+Z6XMEufjLhZIP
qxKJimvZcPYoo1Egtz+l8tKFw0h4OYygqsJubn6RY2iHcbXpbgVKI02++VubXTGf
0oclxitxIm97oARelJmQ9+C/fDUpDbMe+JZOi+41UY4SQSE3J0xYdEajFc8R0oE=
=gL1u
-----END PGP SIGNATURE-----
_______________________________________________
BangPypers mailing list
BangPypers@python.org
https://mail.python.org/mailman/listinfo/bangpypers

Reply via email to