Path: csiph.com!news.mixmin.net!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.python Subject: Re: Question about math.pi is mutable Date: Fri, 06 Nov 2015 23:19:42 +0100 Organization: PointedEars Software (PES) Lines: 51 Message-ID: <1521937.lCYGF7V2BE@PointedEars.de> References: Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit X-Trace: solani.org 1446848385 8399 eJwFwQcBADAIAzBLO7QMOVz/EpbgcjNVCAoG0yZY6mVpMbfDm8M87Uf7MXSwPRwHahW13gc2rhH/ (6 Nov 2015 22:19:45 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Fri, 6 Nov 2015 22:19:45 +0000 (UTC) User-Agent: KNode/4.14.2 X-User-ID: eJwFwYEBwCAIA7CXhqUUzlGR/09YQoTFlQfDOZyAW+rVS7cR8tXpYu0iIVVvh6ZPf+WpFciV6tah6SoMPy86FFI= Cancel-Lock: sha1:Lw4z0g+nwIR+tJ7aTBH8BzInvpI= X-NNTP-Posting-Host: eJwFwYEBACAEBMCVhH81Dsn+I3QH4+INJ+gYjGjKO0dhzx+X4C71HTV5e5S2sz1ZXdyNCHwR+BEB Xref: csiph.com comp.lang.python:98376 Chris Angelico wrote: > On Sat, Nov 7, 2015 at 6:30 AM, Bartc 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 "", line 1, in | 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.