[Python-ideas] Should Python have user-defined constants?

Steven D'Aprano steve at pearwood.info
Tue Nov 21 20:51:05 EST 2017


On Wed, Nov 22, 2017 at 11:47:28AM +1100, Chris Angelico wrote:
> On Wed, Nov 22, 2017 at 11:27 AM, Steven D'Aprano <steve at pearwood.info> wrote:

> > Types are literally irrelevant to this, except in the sense that in many
> > languages, including Python, the distinction between mutable and
> > immutable is usually controlled by the type of object. But that's not
> > fundamental to the concept: we could, if we wanted, decouple the two.
> 
> There's a good reason for that - the type of an object determines what
> operations make sense (you can add two numbers together, but you can't
> add two open sockets), and mutability impacts the validity of
> operations. Can you give an example of where it would make sense to
> decouple mutability from object type?

I didn't say we should, or that I would, only that we could if we wanted 
to. But for the sake of the hypothetical argument, being able to freeze 
an object may be useful, as opposed to copying it into a new, frozen 
object. To make the difference clear:

a = b = something()
a = freeze(a)

b would still be mutable; but:

a = b = something()
freeze(a)

now b is immutable, since it is the same frozen object as a.

But possibly even more interesting might be to have the concept of code 
permissions, so that you can grant software components either read/write 
or read-only permission on values you pass to them.

(Immutable views could possibly do the same job.)

At the moment every time you pass a list to a library function, you risk 
it modifying the list without your knowledge. In general that's more of 
a theoretical risk than an actual risk (we generally know which library 
functions mutate their arguments), but there may be circumstances where 
you'd like to pass a mutable object to (let's say) a callback function, 
or a thread, and trust that it can't modify the object at all.

At the moment, the only obvious alternative is to make an arbitrarily 
expensive deepcopy of the object each time you pass it. Or just hope 
that the called function doesn't mess with your data.


-- 
Steve


More information about the Python-ideas mailing list