[Tutor] What is "in-line code"?

Alan Gauld alan.gauld at blueyonder.co.uk
Sat Aug 14 15:50:55 CEST 2004

> What is "in-line code"?

Code that appears in-line.
In other words its not in a function.
This is the flip side of the recent thread about why not
to write linear programs...


def add4(x): return x+4

for n in range(5):
   print add4(n)

Uses a function but we can write the same using inline
cde instead:

for n in range(5):
   print n + 4

This is faster because it avoids the need for a function call,
and function calls in Python are significant speed hits. So
where you might need to speed up a loop you can often do quite
a lot by deconstructing a function used inside the loop into
in-line code.

In the case above it's obvious but with longer functions
you might have a lot of code to retype, especialoly if
the function is used in several places, so you wind up
maintaining the code both in the function and in the loop.
Its a trade off of convenience versus speed.

> It appears in the Conclusion section, in "Try to use map(),
> filter() or reduce() to replace an explicit for loop, but only if
you can
> use a built-in function:

So he is saying that the overhead of calling a python function
is greater than the savings of using map. (Nowadays we would
use a comprehension in most cases where map() was used
- which is faster still)


Alan G.

More information about the Tutor mailing list