473,568 Members | 2,964 Online
Bytes | Software Development & Data Engineering Community
+ 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(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_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_cons t.pi = 3.14159
irrational_cons t.e = 2.7178

even_const.firs t = 2
even_const.firs tPlus = 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 1562
"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_cons t.pi = 3.14159
Yes, irrational_cons t = _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(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_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_cons ts = _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(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_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:
>>AttributeErro r: _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.ConstErro r: 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(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_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_cons t.pi = 3.14159
irrational_cons t.e = 2.7178

even_const.firs t = 2
even_const.firs tPlus = 4
irrational_cons t = 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(Type Error): pass
=> def __setattr__(sel f,name,value):
=> if self.__dict__.h as_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_co nst.pi = 3.14159
=>irrational_co nst.e = 2.7178
=>
=>even_const.fi rst = 2
=>even_const.fi rstPlus = 4
=>
=>irrational_co nst = 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(Type Error): pass
def __setattr__(sel f,name,value):
if self.__dict__.h as_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.No tDefined = 0x00

And in my main module I have
#! /usr/bin/python
import const
import key_func_consts
print KeyFuncConst.MS K
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.MS K
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

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

Similar topics

0
1121
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 the current namespace with 'from' seems to work, but accessing members of the imported module only works if the imported name is qualified by the ...
17
6627
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. So I shall have an Abstract Base called 'Car' implemented by Toyota, Ford, and Buick. Further I'd like to enable to client to say Car *factory;
7
11761
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
1786
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: What does these two lines in the attached header file do? I vaguely remember there is something special about the underscores. #ifndef...
39
3478
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 and method parameters use camel casing, like this: void SetName(int id, string newName)
11
2841
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
1155
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 idiom going on here. Why do people sometimes use one leading underscore? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger...
2
1167
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 up with one =>underscore. Unless I'm missing something, there's a idiom going on here. => =>Why do people sometimes use one leading underscore? ...
9
1105
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
846
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. I was going to file a documentation bug, but then I checked the 2.6 docs online, and I see it has been fixed, by using single underscores...
0
7604
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7916
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8117
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6275
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5498
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3651
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2101
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 we have to send another system
0
932
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.