making objects unassignable "read-only" (especially when extending)

Rocco Moretti roccomoretti at hotpop.com
Wed Jan 18 10:23:59 EST 2006


Johannes Zellner wrote:
> Hi,
> 
> can I make an object read-only, so that
> 
>     x = new_value
> 
> fails (and x keeps it's orginal value)?

Simon gave you a way of doing it when x is an attribute access (e.g. 
p.x). I am unaware of a way of doing it when x is a straight global or 
local. Unlike other languages like C, the object pointed to by a 
variable is in no way involved in the assignment process. Variables are 
just labels (sticky notes) attached to objects. Assignment is moving of 
the label - this only involves the interpreter, and the object currently 
labeled by the variable is not consulted. If you haven't seen it before, 
http://starship.python.net/crew/mwh/hacks/objectthink.html is a good read.

Note that Simon's trick works not because it changes the object pointed 
to by the variable, but because it changes the properties of the 
namespace where that variable lives (the p in the p.x). To do so for a 
local or a global variable would require changing the local & global 
namespaces - i.e. rewriting the interpreter.



More information about the Python-list mailing list