detect interactivity
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Wed Dec 30 00:27:35 EST 2009
On Wed, 30 Dec 2009 03:33:18 +0100, Roald de Vries wrote:
> I'm using a database, and want to use python interactively to manipulate
> it. On the other hand, I also want to be able to use it non-
> interactively. In that case, it would be a waste of CPU to load the
> function/class definitions meant for interactive use.
Premature optimization is the root of all evil.
The code for interactive use almost certainly won't be a significant
drain on the computer's resources, unless you're using some sort of
embedded device. And if it is, then the natural overhead of merely
running Python at all is almost certainly even more of a drain -- Python
is not a language designed for the efficiency of the CPU, but for the
programmer instead.
But even if we give you the benefit of the doubt, and assume that you've
profiled your code and determined that, in this case, such optimization
is needed, I see at least two problems with that approach.
Problem #1: the benefit won't be as much as you might expect.
If your approach is the following:
# common code used both interactively and non-interactively
def parrot():
pass
def spanish_inquisition():
pass
# interactive code only:
if interactive(): # however you determine this
def cheeseshop():
pass
then the approach you are trying isn't doing what you think it does.
Python still has to parse the definition of cheeseshop and compile it
before running the module code, so the benefit of making it optional is
minimal.
You might think that the better approach is to move it into another
module:
if interactive(): # however you determine this
from interactive_code import *
but even this means that the benefit is relatively small, since the
interactive_code module will be compiled to a .pyc file, and therefore
most of the effort of parsing it, compiling it etc. will be skipped. And
now you have to deal with the problem of circular imports.
Problem #2: if you have code that only appears at certain times, how do
you test it to be sure it works correctly?
Since test code (unit tests, doc tests, etc.) generally are run non-
interactively, your code will be missing all the interactive functions,
which means you can't test them easily. Any automated test suite will
skip half your code!
--
Steven
More information about the Python-list
mailing list