How do you create a weak reference to an object in Python?

How do you create a weak reference to an object in Python?


Asked by: Miranda593 | Posted: 27-01-2022






Answer 1

>>> import weakref
>>> class Object:
...     pass
...
>>> o = Object()
>>> r = weakref.ref(o)
>>> # if the reference is still active, r() will be o, otherwise None
>>> do_something_with_o(r()) 

See the wearkref module docs for more details. You can also use weakref.proxy to create an object that proxies o. Will throw ReferenceError if used when the referent is no longer referenced.

Answered by: Sydney674 | Posted: 28-02-2022



Similar questions

Using a reference to create a new object in python

I think that this is a pure Python "problem" but some context is needed: I'm creating a simple Python script to modify ods documents with the library ezodf. Ods files are similar to Excel documents: a table containing cells that contain value, format, etc. The source comes from a template that I can't edit since I don't have the access...


Using a reference to create a new object in python

I think that this is a pure Python "problem" but some context is needed: I'm creating a simple Python script to modify ods documents with the library ezodf. Ods files are similar to Excel documents: a table containing cells that contain value, format, etc. The source comes from a template that I can't edit since I don't have the access...


python - How do I successfully pass a function reference to Django’s reverse() function?

I’ve got a brand new Django project. I’ve added one minimal view function to views.py, and one URL pattern to urls.py, passing the view by function reference instead of a string: # urls.py # ------- # coding=utf-8 from django.conf.urls.defaults import * from myapp import views urlpatterns = patterns('', url(r'^myview/$', views.myview), ) # views.py ---------- # coding=u...


How can I reference columns by their names in python calling SQLite?

I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite: cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row["column_name"]) This gives the following error: T...


python - How can I get the number of records that reference a particular foreign key in Django?

I'm working on a blog application in Django. Naturally, I have models set up such that there are Posts and Comments, and a particular Post may have many Comments; thus, Post is a ForeignKey in the Comments model. Given a Post object, is there an easy way (ideally, through a method call) to find out how many Comments belong to the Post?


c++ - How do I define a SWIG typemap for a reference to pointer?

I have a Publisher class written in C++ with the following two methods: PublishField(char* name, double* address); GetFieldReference(char* name, double*& address); Python bindings for this class are being generated using SWIG. In my swig .i file I have the following: %pointer_class(double*, ptrDouble); This lets me publish a field that is defined in ...


reference counting - Python: pass c++ object to a script, then invoke extending c++ function from script

First of all, the problem is that program fails with double memory freeing ... The deal is: I have FooCPlusPlus *obj; and I pass it to my script. It works fine. Like this: PyObject *pArgs, *pValue; pArgs = Py_BuildValue("((O))", obj); pValue = PyObject_CallObject(pFunc, pArgs); where pFunc is a python function... So, my script has function, where ...


Why does Python keep a reference count on False and True?

I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest: Py_INCREF(Py_False); return Py_False; ... Py_INCREF(Py_True); return Py_True; Aren't Py_False and Py_True global values? Just out of sheer curiosity, why is Python keeping a reference count for these variables?


c# - In managed code, how do I achieve good locality of reference?

Since RAM seems to be the new disk, and since that statement also means that access to memory is now considered slow similarly to how disk access has always been, I do want to maximize locality of reference in memory for high performance applications. For example, in a sorted index, I want adjacent values to be close (unlike say, in a hashtable), ...


Reference to Part of List - Python

If I have a list in python, how can I create a reference to part of the list? For example: myList = ["*", "*", "*", "*", "*", "*", "*", "*", "*"] listPart = myList[0:7:3] #This makes a new list, which is not what I want myList[0] = "1" listPart[0] "1" Is this possible and if so how would I code it? Cheers, Joe


python - How to get a reference to a module inside the module itself?

How can I get a reference to a module from within that module? Also, how can I get a reference to the package containing that module?


Python reference problem

I'm experiencing a (for me) very weird problem in Python. I have a class called Menu: (snippet) class Menu: """Shows a menu with the defined items""" menu_items = {} characters = map(chr, range(97, 123)) def __init__(self, menu_items): self.init_menu(menu_items) def init_menu(self, menu_items): i = 0 for item in menu_items: self.menu_items[se...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top