views:

73

answers:

4
def a(something):
    return something*something

#Case I - referencing
b = a
#Case II - creating a new function to call the first
def b(something):
    return a(something)

Which is better style? Are there drawbacks to either?

A: 

First doesn't generate a new function, should be better.

Antony Hatchkins
A: 

Function call creates overhead. Case I is faster. Case II creates new function unrelated function.

Why would you need Case II?

Kugel
+5  A: 

Depends on what you need.

def a(something):
    return something*something

b = a

def a(something):
    return something+something

>>> b(3)
9
>>> a(3)
7

Whereas if you did:

b = lambda x:a(x)

b and a will always returns the same

If you want to optimize an extra function call out the first way is better, if you want b and a to always return the same thing the second way is better.

Eld
...and I don't think the extra function call is worth optimizing out in most cases.
Jason Baker
+2  A: 

b = a means calls to b will be faster (no overhead), but introspection (e.g. help(b)) will show the name a, and a's docstring. Unless the latter issues are a killer for your specific application (some kind of tutorial, for example), the speed advantage normally wins the case.

Consider, e.g. in ref.py:

def a(something):
    return something*something

#Case I - referencing
b1 = a
#Case II - creating a new function to call the first
def b2(something):
    return a(something)

Now:

$ python -mtimeit -s'import ref' 'ref.a(23)'
1000000 loops, best of 3: 0.716 usec per loop
$ python -mtimeit -s'import ref' 'ref.b1(23)'
1000000 loops, best of 3: 0.702 usec per loop
$ python -mtimeit -s'import ref' 'ref.b2(23)'
1000000 loops, best of 3: 0.958 usec per loop

I.e., calls to b1 (pure referencing) are just as fast as calls to a (actually appear 2% faster in this run, but that's well within "the noise" of measurement;-), calls to b2 (entirely new function which internally calls a) incur a 20% overhead -- not a killer, but normally something to avoid unless that performance sacrifice buys you something specific that's quite important for your use case.

Alex Martelli