pythong referencing/aliasing

Jeff Epler jepler at
Fri Apr 25 21:40:27 CEST 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)
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 "): = re.compile('[%s]+|$' % delim) # approximately right
        self.s = s
        m =
        if m:
            self.idx = m.end()
            self.idx = 0
    def __iter__(self): return self
    def next(self):
        old_idx = self.idx
        if old_idx >= len(self.s): raise StopIteration
        m =, old_idx)
        self.idx = m.end()
        return self.s[old_idx:m.start()]


More information about the Python-list mailing list