How to isolate a constant?

Chris Rebert clp2 at rebertia.com
Sat Oct 22 20:41:23 EDT 2011


On Sat, Oct 22, 2011 at 5:26 PM, Gnarlodious <gnarlodious at gmail.com> wrote:
> Say this:
>
> class tester():

Style note: either have it explicitly subclass `object`, or don't
include the parens at all. Empty parens for the superclasses is just
weird.

>        _someList = [0, 1]
>        def __call__(self):
>                someList = self._someList
>                someList += "X"
>                return someList
>
> test = tester()
>
> But guess what, every call adds to the variable that I am trying to
> copy each time:
> test()
>> [0, 1, 'X']
> test()
>> [0, 1, 'X', 'X']
>
>
> Can someone explain this behavior?

The line `someList = self._someList` does NOT copy the list. It make
`someList` point to the same existing list object. Hence,
modifications to that object from either variable will affect the
other.
Similarly, `someList += "X"` modifies someList *in-place*; it does not
produce a new list object.

The upshot is that you're just modifying and returning references to
*the same list* repeatedly, never producing a new list object.

> And how to prevent a classwide
> constant from ever getting changed?

Python doesn't have any language-enforced notion of constants. So,
short of writing/using a library to try and enforce such a notion,
you're out of luck. You could use an immutable datatype (e.g. a tuple)
instead of a mutable one (e.g. a list) as some level of safeguard
though.

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list