[Tutor] Const on Python

Andreas Kostyrka andreas at kostyrka.org
Thu Mar 6 10:39:58 CET 2008

The answer is slightly more complex.

1.) objects are either mutable or immutable. E.g. tuples and strings are
per definition immutable and "constant". Lists and dictionaries are an
example of the mutable kind.

2.) "variables", "instance members" are all only references to objects.


# lists are mutable
a = [1, 2]
b = a
assert a == [1, 2, 3]

Now coming back to your question, that you want a non-changeable name,
well, one can create such a beast, e.g.:

def constant(value):
    def _get(*_dummy):
        return value
    return property(_get)

class Test(object):
    const_a = constant(123)

This creates a member that can only be fetched, but not set or deleted.

But in practice, I personally never have seen a need for something like
this. You can always overcome the above constant. Btw, you can do that
in C++ privates too, worst case by casting around and ending up with a
pointer that points to the private element ;)


Am Mittwoch, den 05.03.2008, 21:07 -0300 schrieb Tiago Katcipis:
> Its a simple question but i have found some trouble to find a good 
> answer to it, maybe i just dont searched enough but it wont cost 
> anything to ask here, and it will not cost to much to answer :-). I have 
> started do develop on python and i really liked it, but im still 
> learning. Im used to develop on c++ and java and i wanted to know if 
> there is any way to create a final or const member, a member that after 
> assigned cant be reassigned. Thanks to anyone who tries to help me and 
> sorry to bother with a so silly question. i hope someday i can be able 
> to help :-)
> best regards
> katcipis
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20080306/e56f0d67/attachment.pgp 

More information about the Tutor mailing list