Question about math.pi is mutable

Thomas 'PointedEars' Lahn PointedEars at web.de
Fri Nov 6 17:19:42 EST 2015


Chris Angelico wrote:

> On Sat, Nov 7, 2015 at 6:30 AM, Bartc <bc at freeuk.com> wrote:
>> Is there no way then in Python to declare:
>>
>>    pi = 3.141519     # etc
>>
>> and make it impossible to override?
> 
> Nope. Even in C++, where classes can define certain things as const,
> private, and other such restrictions, you can always get around them
> by manipulating pointers appropriately. In Python, there's a
> *convention* that a leading underscore means "private", but the
> language doesn't enforce anything about it.

It is certainly possible for attributes of (instances of) new-style classes 
(starting with Python 3.2 at the latest) to be read-only by declaring them a 
property that does not have a setter, or one that has a setter that throws a 
specific exception (here: the former):

#--------------------------
class SafeMath(object):
    def __init__ (self):
        from math import pi
        self._pi = pi
    
    @property
    def pi (self):
        return self._pi

#--------------------------

| >>> math = SafeMath()
| >>> math.pi
| 3.141592653589793
| >>> math.pi = 42
| Traceback (most recent call last):
|   File "<stdin>", line 1, in <module>
| AttributeError: can't set attribute

(Or you can use “pi = property(…)” within the class declaration.)

In theory, it should be possible to substitute “math” with a reference to an 
object that acts as a proxy for the original “math” module object but whose 
base class declares the attributes for all the constants read-only.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list