[Baypiggies] Baypiggies snippets

Keith Dart ♂ keith at dartworks.biz
Thu Mar 22 07:43:57 CET 2007

Doug Landauer wrote the following on 2007-03-21 at 23:07 PDT:
> This sure seems more like it oughta be a method, which displays either 
> a flaw
> in Python's general duck-typing philosophy or...

Not really. Consider the str() function. It can "stringify" any object.
The object can control how it is stringified by defining the __str__
"magic method". But the user/consumer of it never calls it directly. 

Another example is my own "sgn()" function: 

def sgn(val):
    """Sign function. Returns -1 if val negative, 0 if zero, and 1 if
        return val._sgn_()
    except AttributeError:
        if val == 0:
            return 0
        if val > 0:
            return 1
            return -1

I defined some objects (modified PhysicalQuantity from
ScientificPython) with that "custom-magic-method" so that it does the
right thing with those, but otherwise assumes a number type. In other
words, by using a function like this instead of a method you can put
some logic in it that makes it work for anything, even if it doesn't
have the proper method.

The "flatten" method is like that. It can really flatten any iterable,
not just lists (however, you always get a list back). Alex has a good
suggestion to also make this an iterable itself.

> 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?

That's what I'm asking. ;-) There seems to be no clear guideline for
this, so what I do is insert them into __builtins__ namespace. But not
as methods, as str-like functions. 

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   Keith Dart <keith at dartworks.biz>
   public key: ID: 19017044

More information about the Baypiggies mailing list