one-time factory in python for an experienced java guy

Peter Otten __peter__ at
Tue Jul 14 17:20:03 CEST 2009

phonky wrote:

> Thanks Paul,
>> Ugh, just forget everything you ever knew about java.  Do some Zen
>> exercises to erase your mind.  Then read a Python tutorial as if
>> you're starting from nothing.
> Yeah, surely right, but easier said than done...
> I'm working on it.
> Taking your example.
> import itertools
>      class Account(object):
>         def __init__(self, holder, gen=itertools.count()):
>            self.__accountnumber =
> If you consider my python illiteracy,
> "itertools.count(): Make an iterator that returns consecutive integers
> starting with n"
> to me that sounds like that solves the increment issue, but what about
> future modules wanting to plug in a different
> numbering format, e.g. 205434.1234 or whatever?

In that case you may want to stick with the class attribute:

>>> class Account(object):
...     def __init__(self):
...             self.account = self.next_account()
...     def __str__(self):
...             return "Account(number=%r)" % self.account
...     __repr__ = __str__
>>> from itertools import count
>>> Account.next_account = count(42).next
>>> a = Account()
>>> b = Account()
>>> a, b
(Account(number=42), Account(number=43))
>>> from uuid import uuid1
>>> Account.next_account = staticmethod(uuid1)
>>> c = Account()
>>> d = Account()
>>> c, d

You can plug in arbitrary callables at runtime. The only complication I can 
see is that you may have to wrap them into a staticmethod to prevent python 
from passing the self reference. You can avoid that if you just use a global 

next_account = ...
class Account(object):
   def __init__(self): self.number = next_account()

You can then set the factory elsewhere

import account
account.next_account = ...
a = Account()

In general in python we like to keep simple things simple rather than 
creating a huge bureaucracy.


More information about the Python-list mailing list