On 1/24/2014 3:45 PM, Chris Angelico wrote:
On Sat, Jan 25, 2014 at 7:32 AM, Asaf Las <roeg...@gmail.com> wrote:
On Friday, January 24, 2014 6:37:29 PM UTC+2, Chris Angelico wrote:
On Sat, Jan 25, 2014 at 3:31 AM, Asaf Las <r...@gmail.com> wrote:
Hi
Is there way to get list of instances of particular
class through class itself? via metaclass or any other method?
Not automatically, but you can make a class that keeps track of its
instances with a weak reference system.
By "not automatically" do you mean there is no way to get references to
instances of class via python's provided methods or attributes for class
object at time the class object is created?
Correct.
This depends on exactly the meaning of your question. CPython has a gc
module which has this method.
gc.get_objects()
Returns a list of all objects tracked by the collector, excluding
the list returned.
In a fresh 3.4.0 Idle shell, the list has about 15000 objects in about
150 classes. (A substantial fraction of the classes, at least, are Idle
classes used in the user process.) Numbers and strings are not tracked.
I believe instances of python-coded classes always are. So you can brute
force search all tracked instances for instances of a class you code in
Python, but this in not 'through [the] class itself'.
If you plan ahead, it seems better to use a class attribute such as
_instances = weakref.WeakSet()
to contain them and add them in the __init__ method.
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list