Skip to content

Teaching Aliasing with Streams

 1 min Open streams and database connections gave me a useful way to explain Python assignment: another name refers to the same live resource.
Published

Sep 13, 2009

Assignment in Python binds a name without copying the object. A common demonstration binds two names to one list, then mutates the list through one and observes it through the other. I preferred an example where copying the object would mean more than duplicating some values.

In a discussion on the VPython list, I made the case with different objects: open streams and database links. Bind a second name to an open stream:

streamB = streamA

Now there is one live resource with two names. A stream carries more than bytes: a position, an operating-system handle, and possibly a peer on the other end. Binding another name does not open another stream.

The follow-up used a remote database connection. Opening a second usable connection requires another session with the server. Copying the local wrapper cannot create that server-side state. The object represents a relationship with something outside the Python process.

The same name-binding rule applies to a list. A copy is a separate operation, with behavior that depends on the object being copied. I was only months into Python when I suggested the example; the stream made the relationship between a name and its object concrete.