Physical constants

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Nov 4 00:41:20 EST 2006


On Fri, 03 Nov 2006 18:38:33 -0800, Rares Vernica wrote:

> Hi,
> 
> I am not sure how the constants are implemented in math,

>>> import math
>>> math.__file__
'/usr/lib/python2.4/lib-dynload/mathmodule.so'

Looks like it is all done in C. It's probably just a binding to your
platform's C floating point library.

But regardless of where they come from, constants like pi are just regular
Python names and objects.

>>> math.pi
3.1415926535897931
>>> math.pi = 3
>>> math.pi
3

So not "real" constants, just constant-by-convention. Whether you call
that a feature or a wart is up to you.

But if you want actual constants that can't be re-bound, then look at this
recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207

Keep in mind that this carries a performance penalty.


> but here is how 
> I would do it. The main idea is to declare the constants as globals in 
> some file.
> 
> Declare all the constants in a file:
> const.py
> ---
> pi = 3.14
> 
> Whenever you want to use pi from another file, just do:
> somecode.py
> ---
> from const import pi

Or just import const and refer to const.pi. That's arguably clearer,
although again there is a tiny performance cost.



-- 
Steven.




More information about the Python-list mailing list