473,462 Members | 1,055 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Question about a single underscore.

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

and is this in the tutorial?

2. Can I make this behave in such a way that I can create my constants
with a classname 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

TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Feb 1 '07 #1
10 1556
"Steven W. Orr" <st****@syslang.netwrites:
------------------><8------------------- const.py-------------
...
sys.modules[__name__]=_const()
__name__ is 'const' since this file is const.py. So you've
juset set the const module to actually be a const instance.
1. Why do I not have to say
_const.pi = 3.14159
const.pi refers to item 'pi' in the const module, which you've
set in sys.modules above.
2. Can I make this behave in such a way that I can create my constants
with a classname that is different for different uses? e.g.,
irrational_const.pi = 3.14159
Yes, irrational_const = _const()
Feb 1 '07 #2
On Feb 1, 5:52 pm, "Steven W. Orr" <ste...@syslang.netwrote:
I saw this and tried to use it:

------------------><8------------------- const.py-------------
[...]
sys.modules[__name__]=_const()
__name__ == 'const', so you´re actually doing
const = _const()
Feb 1 '07 #3
On Thursday, Feb 1st 2007 at 09:25 -0800, quoth Bart Ogryczak:

=>On Feb 1, 5:52 pm, "Steven W. Orr" <ste...@syslang.netwrote:
=>I saw this and tried to use it:
=>>
=>------------------><8------------------- const.py-------------
=>[...]
=>sys.modules[__name__]=_const()
=>
=>__name__ == 'const', so you´re actually doing
=>const = _const()

So how can I say this in 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

def __init__(self):
sys.modules[self]=_const()

import sys

to cause a different instantiation a la

foo = _const()

The goal would be to create different instances of consts.

I did try the previous suggestion

irrational_consts = _const()

but I got
>>import const
iii=_const()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name '_const' is not defined
*>>iii=const()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: _const instance has no __call__ method

------------
For ref:

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()

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Feb 1 '07 #4
"Steven W. Orr" <st****@syslang.netwrites:
to cause a different instantiation a la
foo = _const()
The goal would be to create different instances of consts.
The idea of putting it in sys.modules is so it's visible in all modules.
>import const
iii=_const()
You need
iii = const._const
Feb 1 '07 #5
On Thursday, Feb 1st 2007 at 10:36 -0800, quoth Paul Rubin:

=>"Steven W. Orr" <st****@syslang.netwrites:
=>to cause a different instantiation a la
=>foo = _const()
=>The goal would be to create different instances of consts.
=>
=>The idea of putting it in sys.modules is so it's visible in all modules.
=>
=>>import const
=>>iii=_const()
=>
=>You need
= iii = const._const
=>--
=>http://mail.python.org/mailman/listinfo/python-list
=>
547 python
Python 2.3.5 (#2, May 4 2005, 08:51:39)
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>import const
iii = const._const
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: _const instance has no attribute '_const'
*>>iii = const._const()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: _const instance has no attribute '_const'
>>>

What am I missing here? (Sorry if it should be obvious)

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Feb 1 '07 #6
"Steven W. Orr" <st****@syslang.netwrites:
AttributeError: _const instance has no attribute '_const'
>>
What am I missing here? (Sorry if it should be obvious)
Oh I see. No it's not obvious. module "const" has gotten overwritten
by the _const instance. I think that module author was too clever for
his or her own good.
Feb 1 '07 #7
Paul Rubin a écrit :
"Steven W. Orr" <st****@syslang.netwrites:
>>AttributeError: _const instance has no attribute '_const'

What am I missing here? (Sorry if it should be obvious)


Oh I see. No it's not obvious. module "const" has gotten overwritten
by the _const instance. I think that module author was too clever for
his or her own good.
Not necessarily - given the intent, it's just smart IMHO. But the
workaround is quite obvious anyway:
>>import const
# so what is const ?
const
<const._const instance at 0x40409acc>
>># ok, it's an instance, so it should refer to it's class:
Const = const.__class__
Const
<class const._const at 0x403fbdac>
>># Bingo. Let's have another _const instance:
c = Const()
c
<const._const instance at 0x404095cc>
>>c.pi = 42
c.pi = 33
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "const.py", line 5, in __setattr__
raise self.ConstError, "Can't rebind const(%s)"%name
const.ConstError: Can't rebind const(pi)
>>>
HTH
Feb 1 '07 #8
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...
Feb 1 '07 #9
On Thursday, Feb 1st 2007 at 21:45 +0100, quoth Bruno Desthuilliers:

=>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.

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
import key_func_consts
print KeyFuncConst.MSK
but the last print fails with

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

561 t_const.py
Traceback (most recent call last):
File "./t_const.py", line 6, in ?
print KeyFuncConst.MSK
NameError: name 'KeyFuncConst' is not defined

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

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Feb 1 '07 #10
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 ?

Feb 1 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Tom Blackwell | last post by:
Today I installed the 'mechanoid' package from sourceforge, but the self-test failed. On looking into it, I noticed odd behaviour in the handling of single underscore module names. Importing into...
17
by: Medi Montaseri | last post by:
Hi, Given a collection of similar but not exact entities (or products) Toyota, Ford, Buick, etc; I am contemplating using the Abstraction pattern to provide a common interface to these products....
7
by: csx | last post by:
Hi everyone! two quick questions relating to arrays. Q1, Is it possible to re-assign array elements? int array = {{2,4}, {4,5}}; array = {2,3}
9
by: John Smith | last post by:
I'm looking at some codes I wrote five years ago when taking a C++ course. Having not touched C++ since, I have forgotten most of it. Now I can't even comprehend my own codes. I have a question:...
39
by: Patrick | last post by:
The c# code style guide that I follow suggests that class variables (fields) be coded with camel casing, like this: int recordId; string name; It also suggests that variables within methods...
11
by: manstey | last post by:
Hi, I am having trouble designing my classes. I have two classes. The first one wraps around an old-style class called oref Class CacheClass(object): def __init__(self, obj):
4
by: Steven W. Orr | last post by:
I understand that two leading underscores in a class attribute make the attribute private. But I often see things that are coded up with one underscore. Unless I'm missing something, there's a...
2
by: Steven W. Orr | last post by:
On Friday, Feb 23rd 2007 at 11:12 -0500, quoth Steven W. Orr: =>I understand that two leading underscores in a class attribute make the =>attribute private. But I often see things that are coded...
9
by: Skye | last post by:
What is this doing? print >fd, _(__doc__) I'm guessing line-splitting __doc__ into a list, but what's that leading underscore do? Thanks!
1
by: Frank Millman | last post by:
Hi all I have started experimenting with properties. The example in the 2.5 docs uses an inconsistent mixture of single and double underscores for the internal representation of the attribute....
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.