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

J

Johannes Zellner

Hi,

can I make an object read-only, so that

x = new_value

fails (and x keeps it's orginal value)?

This would be especially of interest for me for an object created by
a c extension.
 
R

Rocco Moretti

Johannes said:
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.
 
F

Fredrik Lundh

Johannes said:
can I make an object read-only, so that

x = new_value

fails (and x keeps it's orginal value)?

the original x does contain the original value; assignment only changes
the binding in the target namespace. you cannot override this.

you can control attribute assignment, though:

x.y = new_value

(via __setattr__ methods/slots on the x object)

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top