How to avoid "f.close" (no parens) bug?

Christian Tismer tismer at stackless.com
Sun Dec 25 11:30:45 EST 2005


o wrote:
> plez send me

This is actually no bug but a feature. :-)

Well, I know what you mean.
The problem is created by the fact that in Python, functions
are first-class object which can be assigned, passed around,
inspected and whatever, as every other object can.

The drawback is that you have to write the parens to invoke
a call. There is not a lot to do about it but forgetting
about VB and thinking about a function as an object that
you have to call() to do its action.

You may get more used to it by using functions as first-class
objects by yourself. As an example, consider to build a tiny
calculator, fill a string-keyed dict with operations and
then use it:

def add(n1, n2):
     return n1 + n2

def mul(n1, n2):
     return n1 * n2

# and so on.Of course you also can use the operator module...

BINARY_OPS = {
   '+' : add,
   '*' : mul,
   # add more at your taste
}

def cal_bin(op, n1, n2):
     func = BINARY_OPS[op]
     return func(n1, n2)

# can you see the advantage?

There are exceptions, like using properties to avoid method
calls. This is a nice features to expose light-weight methods
which seem to be naturally modelled as object attributes,
but over-using this feature is clearly an abuse to avoid.

For instance:

class SomeObj(object):

     @property
     def nitems(self):
         pass # some cheap code to compute number of items

     def squaresum(self):
         pass # some more heavy computation

and then using

x = SomeObj()
# add a number of items
x.nitems  # used as a property

is a valid example, because the fact that nitems is not an
attribute but a cheaply computed property might be an implementation
detail that is fine to hide from the user.

On the other hand, doing lots of computation should be made
clear to the user by sticking with parentheses().
Caling the suqresum() method should not be turned into a property,
since such a thing isn't cheap in most cases.
Not to speak of functions which have side-effects.

merry christmas - chris

-- 
Christian Tismer             :^)   <mailto:tismer at stackless.com>
tismerysoft GmbH             :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9A     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 802 86 56  mobile +49 173 24 18 776  fax +49 30 80 90 57 05
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/



More information about the Python-list mailing list