Purpose of operator package

Carl Banks pavlovevidence at gmail.com
Tue May 13 19:46:23 EDT 2008


On May 13, 6:09 pm, Eric Anderson <e... at pixelwareinc.com> wrote:
> I mainly work in other languages (mostly Ruby lately) but my text
> editor (Scribes) is python. With python being everywhere for dynamic
> scripting I thought I would read the source to learn the language
> better (I've gone through some basic tutorials but I always prefer to
> learn from real source).

There is one significant drawback of that....


> So right from the start I see the following:
>
> from operator import truth
> if truth(argv):
>   # blah blah blah
>
> It is obvious they are testing to see if any command line arguments.
> But curious for why the function is needed.

It isn't.  The above is terrible code.

1. You don't even need operator.truth; the built-in bool performs that
job.  However, this code could have been written before the advent of
bool, so we'll give it a temporary pass.
2. bool in unnecessary in this context.
3. Lest someone claim that truth serves to document that you are
asking for the boolean value of argv (i.e., whether it's not empty),
it's redundnant since the if statement implies that.


> So I look up the operator
> package and fine it provides functions that are equivalent to the
> native operators. So my question is why would someone right the above
> instead of just
>
> if argv:
>   # blah blah blah
>
> Seems like unnecessary code but obviously I know nothing about Python.

You know more than the person who wrote the code above.

The purpose of the operator module is to provide  functional
representations of Python operators (and a few non-operators) for
functional programming.  They could, for example, be useful as the
arguments of map and reduce.  Few beginners use functional programming
so you might not want to worry about it now, though if you've been
using Ruby you might have done it before.

operator.truth was one of the few things in that module that was
useful for things other than functional programming, since there is no
truth operator in Python.  Now that the language has bool it's no
longer needed.


Carl Banks



More information about the Python-list mailing list