views:

256

answers:

3

I need a class that works like this:

>>> a=Foo()
>>> b=Foo()
>>> c=Foo()
>>> c.i
3

Here is my try:

class Foo(object):
    i = 0
    def __init__(self):
        Foo.i += 1

It works as required, but I wonder if there is a more pythonic way to do it.

+9  A: 

Nope. That's pretty good.

From The Zen of Python: "Simple is better than complex."

That works fine and is clear on what you're doing, don't complicate it. Maybe name it counter or something, but other than that you're good to go as far as pythonic goes.

Paolo Bergantino
Maybe I should post my comment here, instead of on the question: I'm just curious, is something like this threadsafe? Would you be able to instantiate Foo from multiple threads and have a proper count?
Tom
@Tom: Good question. I honestly am not sure, but I would think that it does.
Paolo Bergantino
I asked the question here: http://stackoverflow.com/questions/1072821/is-modifying-a-class-variable-in-python-threadsafe.
Tom
The verdict is in... it is not threadsafe.
Tom
+2  A: 

Abuse of decorators and metaclasses.

def counting(cls):
    class MetaClass(getattr(cls, '__class__', type)):
        __counter = 0
        def __new__(meta, name, bases, attrs):
            old_init = attrs.get('__init__')
            def __init__(*args, **kwargs):
                MetaClass.__counter += 1
                if old_init: return old_init(*args, **kwargs)
            @classmethod
            def get_counter(cls):
                return MetaClass.__counter
            new_attrs = dict(attrs)
            new_attrs.update({'__init__': __init__, 'get_counter': get_counter})
            return super(MetaClass, meta).__new__(meta, name, bases, new_attrs)
    return MetaClass(cls.__name__, cls.__bases__, cls.__dict__)

@counting
class Foo(object):
    pass

class Bar(Foo):
    pass

print Foo.get_counter()    # ==> 0
print Foo().get_counter()  # ==> 1
print Bar.get_counter()    # ==> 1
print Bar().get_counter()  # ==> 2
print Foo.get_counter()    # ==> 2
print Foo().get_counter()  # ==> 3

You can tell it's Pythonic by the frequent use of double underscored names. (Kidding, kidding...)

ephemient
+1: This is disgusting.
Thomas
+2  A: 

If you want to worry about thread safety (so that the class variable can be modified from multiple threads that are instantiating Foos), the above answer is in correct. I asked this question about thread safety here. In summary, you would have to do something like this:

from __future__ import with_statement # for python 2.5

import threading

class Foo(object):
  lock = threading.Lock()
  instance_count = 0

  def __init__(self):
    with Foo.lock:
      Foo.instance_count += 1

Now Foo may be instantiated from multiple threads.

Tom