Jeffrey Aylesworth
Jeffrey Aylesworth

Reputation: 8480

Reference function or create a new function that only calls another?

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?

Upvotes: 1

Views: 148

Answers (4)

Alex Martelli
Alex Martelli

Reputation: 881595

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.

Upvotes: 2

Eld
Eld

Reputation: 984

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.

Upvotes: 5

Kugel
Kugel

Reputation: 19814

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

Why would you need Case II?

Upvotes: 0

Antony Hatchkins
Antony Hatchkins

Reputation: 33984

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

Upvotes: 0

Related Questions