Question about a single underscore.

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Feb 1 15:45:52 EST 2007


Steven W. Orr a écrit :
> I saw this and tried to use it:
> 
> ------------------><8------------------- const.py-------------
> class _const:
>     class ConstError(TypeError): pass
>     def __setattr__(self,name,value):
>         if self.__dict__.has_key(name):
>             raise self.ConstError, "Can't rebind const(%s)"%name
>         self.__dict__[name]=value
> 
> import sys
> sys.modules[__name__]=_const()
> ------------------><8------------------- const.py-------------
> 
> Then when I go to try to use it I'm supposed to say:
> 
> const.pi        = 3.14159
> const.e         = 2.7178
> 
> 
> Two questions:
> 
> 1. Why do I not have to say
> 
> _const.pi        = 3.14159
> _const.e         = 2.7178

Because of the last two lines of module const. sys.modules is a dict of 
already imported modules (yes, Python's modules are objects too), which 
avoids modules being imported twice or more. __name__ is a magic 
variable that is set either to the name of the module - when it's 
imported - or to '__main__' - when it's being directly executed as the 
main program. Here, when you first do 'import const', the module's code 
itself sets sys.modules['const'] to an instance of _const, so what you 
import in your namespace as 'const' is not the const module instance but 
a _const instance.

> and is this in the tutorial?

Hmmm... Not sure. FWIW, it's mostly a hack !-)

> 2. Can I make this behave in such a way that I can create my constants 
> with a classname

s/classname/name/

> that is different for different uses? e.g.,
> 
> irrational_const.pi        = 3.14159
> irrational_const.e         = 2.7178
> 
> even_const.first    = 2
> even_const.firstPlus    = 4

irrational_const = const.__class__()
even_const = const.__class__()

Now while I find this hack interesting, it's also totally unpythonic 
IMHO. The usual convention is to use ALL_UPPER names for (pseudo) 
symbolic constants, and I don't see any reason to forcefit B&D languages 
concepts into Python.

My 2 cents...



More information about the Python-list mailing list