C-style static variables in Python?
Duncan Booth
duncan.booth at invalid.invalid
Fri Apr 2 13:53:18 EDT 2010
kj <no.email at please.post> wrote:
> I suppose one could refactor this:
>
><procedural>
> def spam(x, y, z):
> try:
> mongo = spam.mongo
> except AttributeError:
> mongo = spam.mongo = heavy_lifting_at_runtime()
> return frobnicate(x, y, z, mongo)
>
> ham = spam(3, 4, 5)
></procedural>
>
> into this:
>
><OO>
> class _Spam(object):
> @classmethod
> def _(cls, x, y, z):
> try:
> mongo = cls.mongo
> except AttributeError:
> mongo = cls.mongo = heavy_lifting_at_runtime()
> return frobnicate(x, y, z, mongo)
>
> ham = _Spam._(1, 2, 3)
></OO>
>
>
> Is this really more natural or more readable? Hmmm.
No, but that's because it is needlessly obfuscated. What's with the weird _
method? Why use a class method? Why not just create an instance?
class Spam(object):
mongo = None
def __call__(self, x, y, z):
if self.mongo is None:
self.mongo = heavy_lifting_at_runtime()
return frobnicate(x, y, z, self.mongo)
spam = Spam()
ham = spam(1, 2, 3)
That's natural and readable.
There's also another good reason why the class is better than the static
variable: you can construct multiple different instances with different
calls to 'heavy_lifting_at_runtime'. e.g. You could write a unit test where
mongo is initialised to mock_heavy_lifting_at_runtime().
More information about the Python-list
mailing list