pythong referencing/aliasing

Jeff Epler jepler at unpythonic.net
Fri Apr 25 15:40:27 EDT 2003


On Fri, Apr 25, 2003 at 04:33:32PM -0000, Cameron Laird wrote:
> I'll make a positive assertion of this:  in C and
> C++, stylish programmers frequently use references
> to good effect.  Python rarely, very rarely, needs
> to do the same.  It might be instructive to choose
> a typical C++ reference idiom, and illustrate how
> its typical use case is better served in Python be
> a derived return, or dictionary construction, or ...

Well, some of the places you use a pointer/reference *and* a return
value, you use multiple return values in Python.  For instance:

// two outputs from function, one through a pointer
double modf(double x, double *iptr)

# In Python, return the two values as a tuple
>>> math.modf(3.14)
(0.14000000000000012, 3.0)

Sometimes it's instead of true exception handling (less so in C++):
// return whether an error happened, otherwise stick the result in the
// preallocated buffer and return the length
int read(int fd, void *buf, size_t count)

# In Python, raise an exception if the read fails.  Otherwise,
# return a freshly allocated buffer (which implicitly carries its
# length)
>>> sys.stdin.read(16)
No one expects the spanish inquisition # (typed in)
'No one expects t'

Somtimes it's instead of some stateful information (less so in C++):
// The state needed to continue iterating through tokens is in the
// third arg
char *strtok_r(char *s, const char *delim, char **ptrptr);

# In Python, you'd have an object.  This may not quite match C's strtok,
# but it gives the flavor of the implementation
class strtok:
    def __init__(self, s, delim="\t\r\n "):
        self.re = re.compile('[%s]+|$' % delim) # approximately right
        self.s = s
        m = self.re.match(self.s)
        if m:
            self.idx = m.end()
        else:
            self.idx = 0
    def __iter__(self): return self
    def next(self):
        old_idx = self.idx
        if old_idx >= len(self.s): raise StopIteration
        m = self.re.search(self.s, old_idx)
        self.idx = m.end()
        return self.s[old_idx:m.start()]

Jeff





More information about the Python-list mailing list