« And I thought *I* was audaciousWhat bloggers would like from their audience »

None versus dummy objects for delegation

03/11/05

Permalink 01:23:09 pm, by fumanchu Email , 201 words   English (US)
Categories: Python

None versus dummy objects for delegation

Jeremy Hylton posted a little blurb about wanting "to use composition instead of inheritance". I try to do that, too, and have an additional trick I play. Because function-calls are rather expensive in Python, I sometimes use None instead of a "dummy object" for the null-behavior case.

test.py:

class Parent(object):
    pass

a = Parent()
a.lock = None

b = Parent()
b.lock = lambda: True

interactive:

>>> import timeit
>>> t1 = timeit.Timer("if a.lock: a.lock()", "import test; a = test.a")
>>> t2 = timeit.Timer("if b.lock: b.lock()", "import test; b = test.b")
>>> t2.timeit()
1.7819946389834485
>>> t1.timeit()
0.44152985924188926
>>> t3 = timeit.Timer("b.lock()", "import test; b = test.b")
>>> t3.timeit()
1.373198548977598

The third case, t3, is what usually happens with normal delegation: even with a dummy object, a function-call is performed each time. If you have an object, you also have attribute lookup every time. If you have a high ratio of null delegates, it can save some time to use None instead. Using the naive timings above, if you have 50% null delegates, the times should average to (1.78 + .44) / 2 = 1.11 versus the 1.37 average of dummy objects. If you have, say, 75% nulls, you get .775 per call, on average.

1 comment

Comment from: Mihir Mehta [Visitor]

http://www.python.org/~jeremy/weblog/050311.html is the link you should be using.

05/22/12 @ 03:58

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.

Please enter the phrase "I am a real human." in the textbox above.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)
September 2020
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30      

Search

The requested Blog doesn't exist any more!

XML Feeds

powered by b2evolution free blog software