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 8013755
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T19:43:07+00:00 2026-06-04T19:43:07+00:00

I have a class that keeps track of its instances in a class variable,

  • 0

I have a class that keeps track of its instances in a class variable, something like this:

class Foo:
    by_id = {}

    def __init__(self, id):
        self.id = id
        self.by_id[id] = self

What I’d like to be able to do is iterate over the existing instances of the class. I can do this with:

for foo in Foo.by_id.values():
    foo.do_something()

but it would look neater like this:

for foo in Foo:
    foo.do_something()

is this possible? I tried defining a classmethod __iter__, but that didn’t work.

  • 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-04T19:43:08+00:00Added an answer on June 4, 2026 at 7:43 pm

    If you want to iterate over the class, you have to define a metaclass which supports iteration.

    x.py:

    class it(type):
        def __iter__(self):
            # Wanna iterate over a class? Then ask that class for iterator.
            return self.classiter()
    
    class Foo:
        __metaclass__ = it # We need that meta class...
        by_id = {} # Store the stuff here...
    
        def __init__(self, id): # new isntance of class
            self.id = id # do we need that?
            self.by_id[id] = self # register istance
    
        @classmethod
        def classiter(cls): # iterate over class by giving all instances which have been instantiated
            return iter(cls.by_id.values())
    
    if __name__ == '__main__':
        a = Foo(123)
        print list(Foo)
        del a
        print list(Foo)
    

    As you can see in the end, deleting an instance will not have any effect on the object itself, because it stays in the by_id dict. You can cope with that using weakrefs when you

    import weakref
    

    and then do

    by_id = weakref.WeakValueDictionary()
    

    . This way the values will only kept as long as there is a “strong” reference keeping it, such as a in this case. After del a, there are only weak references pointing to the object, so they can be gc’ed.

    Due to the warning concerning WeakValueDictionary()s, I suggest to use the following:

    [...]
        self.by_id[id] = weakref.ref(self)
    [...]
    @classmethod
    def classiter(cls):
        # return all class instances which are still alive according to their weakref pointing to them
        return (i for i in (i() for i in cls.by_id.values()) if i is not None)
    

    Looks a bit complicated, but makes sure that you get the objects and not a weakref object.

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

Sidebar

Related Questions

I have a class that looks like this: typedef std::list<char*> PtrList; class Foo {
I have created a class called aptSchedule which, like its name suggests, keeps track
I have a Gene class that keeps track of genes. Gene has a method
I have a class that knows its existing instances. Sometimes I want the class
I have a multi-R/W lock class that keeps the read, write and pending read
I have this class that has a static member. it is also a base
I have code like this in C#: namespace WumpusWorld { class PlayerAI { //struct
Okay so what I have is a table that keeps track of history on
I would like to have a static member variable keep track of the amount
We have a custom panel class that animates its children via an internal DoubleAnimation

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.