Question about a single underscore.

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Feb 1 17:12:58 EST 2007


Steven W. Orr a écrit :
> On Thursday, Feb 1st 2007 at 21:45 +0100, quoth Bruno Desthuilliers:
> 
(snip)

> =>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.
> 
> Ok. Now *maybe* we're getting to where I want to be. My const.py now looks 
> like this:
> 
> 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()
> 
> and in a seperate module call key_func_consts I say:
> 
> import const
> # Define constants for Key Function Field.
> KeyFuncConst   = const.__class__()
> KeyFuncConst.NotDefined                = 0x00
> 
> And in my main module I have
> #! /usr/bin/python
> import const

Note that you don't need it if you don't use it directly.

> import key_func_consts
> print KeyFuncConst.MSK
> 
> 
> but the last print fails with 

A NameError, of course. key_func_consts is the module, KeyFuncConst is 
an attribute of this module. You either need to

1/ use a fully qualified name:

import key_func_consts
print key_func_consts.KeyFuncConst.MSK

or
2/ import the KeyFuncConst name directly:

from key_func_consts import KeyFuncConst
print KeyFuncConst.MSK

or
3/ use the same dirty hack as in the const module - but this is starting 
to be very ugly and unpythonic, so I won't give an implementation 
example !-)

Also, note that since you did not define KeyFuncConst.MSK in the 
key_func_const module, you'll then have an AttributeError !-)

> The goal is to be able to create classes of global constants.

Then just define your "constants" in the module and import it:

# key_func_const.py
NOT_DEFINED = 0x00
MSK = 42

# main.py
import key_func_const
print key_func_const.NOT_DEFINED
print key_func_const.MSK


> Do I need to get the KeyFuncConst object into sys.modules somehow? I know 
> I'm close.

Nope. You're going the wrong direction. It's a typical case of arbitrary 
overcomplexification. Please re-read the last paragraph of my previous 
post. By convention, in Python, ALL_UPPER names means "constant value, 
dont touch". The example I give you above is the Pythonic way of doing 
things, it's dead simple, and *it just works* - so why bother messing 
with sys.modules hacks ?




More information about the Python-list mailing list