1 <!-- subject: Lazy Proxy in {Python} -->
2 <!-- date: 2012-07-08 20:56:47 -->
3 <!-- tags: python, lazy proxy -->
4 <!-- categories: Articles, Techblog -->
6 <p>Paths of destiny lead mysterious ways. Not so long ago, I was
7 a hard-core C hacker and now, I spend a lot of the time coding in
<a
8 href=/
2010/python-wrazenia
/>Python
</a>.
10 <p>In somehow related news, I have discovered that my
11 search-foo is not good enough, when I was unable to find a decent
12 implementations of several design patterns in Python.
14 <p>What I needed was a generic proxy that would defer initialisation
15 of an object to the moment it is first used. Here is what I came up with:
18 class LazyProxy(object):
21 def __init__(self, cls, *args, **kw):
22 object.__setattr__(self, '_LazyProxy__get',
23 lambda: self.__set(cls(*args, **kw)))
26 object.__setattr__(self, '_LazyProxy__get', lambda: obj)
29 def __getattr__(self, name):
30 return getattr(self.__get(), name)
32 def __setattr__(self, name, value):
33 return setattr(self.__get(), name, value)
35 def __delattr__(self, name):
36 return delattr(self.__get(), name)
</pre>
40 <p>Here’s how one can use it:
46 def __init__(self, bar, baz):
47 print 'Creating Foo...'
53 print 'Foo.a: self=(foo=%s, bar=%s, baz=%s)' % (
54 self.foo, self.bar, self.baz)
58 print 'Foo.b: cls=%s, cls.foo=%s' % (
59 cls.__name__, cls.foo)
65 foo = LazyProxy(Foo, 'bar', baz='qux')
66 print 'LazyProxy created'
71 <p><code>foo
</code> can be used in (almost) the same
72 way as an already created
<code>Foo
</code> object would. The only
73 caveat is it will not be an instance of
<code>Foo
</code> which may or
74 may not be an issue. Also, it is not thread safe.
76 <p class=nt
>Code © Google Inc.
79 <!-- date: 2012-07-09 07:07:32 -->
81 <!-- nick_url: http://rdominiak.jogger.pl -->
84 <p>‘Not so long ago, I was a hard-core C hacker and now, I spend a lot of the time coding in Python.’
87 <p>I remember that some time ago you also wrote somethink like ‘why I don’t like Gentoo’, so next post will be ‘Coding Python on Gentoo’? ;)
90 <!-- date: 2012-07-09 22:09:03 -->
92 <!-- nick_url: http://mina86.com -->
95 <p>I remember that some time ago you also wrote somethink like ‘why I don’t like Gentoo’, so next post will be ‘Coding Python on Gentoo’? ;)
98 <p>That’s really unlikely. ;) If to anything, I’d probably switch to Debian, but
99 than again, I’ve never looked at Arch and it was recommended to me a few
102 <p>True enough though, that no one can tell what future will bring, and there
103 may be some bizarre event which will make me use Gentoo.
105 <p>PS. The referenced article:
<a href=
"https://mina86.com/2008/wrabzenia-z-gentoo/">Wrażenia z Gentoo
</a> (Polish).