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

Discussion in 'Python' started by Johannes Zellner, Jan 18, 2006.

  1. 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.

    --
    Johannes
     
    Johannes Zellner, Jan 18, 2006
    #1
    1. Advertising

  2. Simon Brunning, Jan 18, 2006
    #2
    1. Advertising

  3. 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.
     
    Rocco Moretti, Jan 18, 2006
    #3
  4. Re: making objects unassignable "read-only" (especially whenextending)

    Johannes Zellner wrote:

    > 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>
     
    Fredrik Lundh, Jan 18, 2006
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. mark
    Replies:
    2
    Views:
    462
  2. Ulf Meinhardt
    Replies:
    0
    Views:
    385
    Ulf Meinhardt
    Nov 14, 2004
  3. mike
    Replies:
    3
    Views:
    404
    Virgil Green
    Jul 11, 2005
  4. Replies:
    2
    Views:
    436
    Larry Barowski
    Jan 31, 2006
  5. keithb
    Replies:
    2
    Views:
    8,036
    keithb
    Jun 7, 2006
Loading...

Share This Page