[Baypiggies] Baypiggies snippets

Chad Netzer chad.netzer at gmail.com
Thu Mar 29 07:53:11 CEST 2007

On 3/28/07, Keith Dart ♂ <keith at dartworks.biz> wrote:
> Doug Landauer wrote the following on 2007-03-21 at 23:07 PDT:
> ===
> > If we have come across the need/desire for a new general method that
> > should work just fine with anything that "quacks like a sequence", and
> > we would like to make it available to any sequence in any of our Python
> > code, and I want to invoke it as foo.method for any foo that is
> > a sequence, then where/how would I define such a method?
> ===

I'm not sure in which thread Doug posed this question, but if I
understand it, you want to have a way of adding a method to all
sequence like objects?  I think the short answer is that you have to
make it a function, not a method, and call it like a function with the
sequence as argument.  The long answer I'll have to leave for later,
or someone else, but basically methods are defined in, or inherited
from, a class, and if you make a method that operates on sequences,
not all sequence-like objects will inherit from that class.

Note that numpy has a whole bunch of functions that operate on
array-like sequences, rather than providing them as methods on the
array objects, precisely because those functions generalize to many
other kinds of objects.  I'm no Ruby expert, but your example seem
ruby-ish, and perhaps it  provides a way to do what you are asking?

> I suppose the most acceptable pattern is something like this:
> from mypackage import utils
> utils.waddle(quacker)
> What say you?

If you have a few functions you are gonna use a lot, I like to just
make the functions local:

from mypackage.utils import div,grad,curl

seq2 = div(seq1)
seq4 = div(seq3)
seq6 = curl(seq5)

And sometimes you have many helper functions in a module, and aren't
using each function as often, so you just import the module, and
access the functions with dot notation:

from mypackage import utils

b = utils.div(a)
c = utils.grad(b)
d = utils.curl(a)

But often it is a mixture of the two:

from mypackage import vector_calculus
from mypackage.vector_calculus import div  # or div = vector_calculus.div

c = vector_calculus.grad(div(b))

Basically, there are a number of options for dealing with your names
and namespaces.  In fact, I also often use shorter names (temporarily)
for longer variables or functions, when it makes the code "cleaner".

x = some_really_long_descriptive_variable_function_or_module_name
x + 3*x + x**2     # or foo(x("abc"), x("qvc"), x("bvd"))  etc...
x = None   # or del x, if you want to indicate that x was a temporary name


More information about the Baypiggies mailing list