473,602 Members | 2,896 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

module exports a property instead of a class -- Evil?

gry
I often find myself wanting an instance attribute that can take on only
a few fixed symbolic values. (This is less functionality than an enum,
since there are no *numbers* associated with the values). I do want
the thing to fiercely object to assignments or comparisons with
inappropriate values. My implementation below gets me:

..import mode
..class C(object):
.. status = mode.Mode('star ted', 'done', 'on-hold')
..
..c=C()
..c.status = 'started'
..c.status = 'stated': #Exception raised
..if c.status == 'done': something
..if c.status == 'stated': #Exception raised
..if c.status.done: something #simpler and clearer than string compare
..if c.status < 'done': something # Mode arg strings define ordering

I would appreciate comments on the overall scheme, as well as about the
somewhat sneaky (I think) exporting of a property-factory instead of a
class. My intent is to provide a simple clear interface to the client
class ("C" above), but I don't want to do something *too* fragile or
confusing...
(I'd also welcome a better name than "Mode"...)

-------------------------- mode.py ----------------------
class _Mode: #internal use only, not exported.
def __init__(self, *vals):
if [v for v in vals if not isinstance(v, str)]:
raise ValueError, 'Mode values must be strings'
else:
self.values = list(vals)

def set(self, val):
if val not in self.values:
raise ValueError, 'bad value for Mode: "%s"' % val
else:
self.state = val

def __cmp__(self, other):
if other in self.values:
return cmp(self.values .index(self.sta te),
self.values.ind ex(other))
else:
raise ValueError, 'bad value for Mode comparison'

def __getattr__(sel f, name):
if name in self.values:
return self.state == name
else:
raise AttributeError, 'no such attribute: "%s"' % name
def Mode(*vals): # *function* returning a *property*, not a class.
m = _Mode(*vals)
def _insert_mode_ge t(self):
return m
def _insert_mode_se t(self, val):
m.set(val)
return property(_inser t_mode_get, _insert_mode_se t)
-----------------------------------------------------------

Thanks,
George

Jul 19 '05 #1
3 1982
The property factory is nice, but have you considered subclassing
property?

class Mode(property):
def __init__(self, *vals):
if [v for v in vals if not isinstance(v,st r)]:
raise ValueError, 'Mode values must be strings'
else:
self.values = list(vals)
property.__init __(self, self.get, self.set)
def get(self, instance):
...
def set(self, instance, value):
...

Jul 19 '05 #2
gry
Hmm, I had no idea that "property" was a class. It's listed in the
library
reference manual under builtin-functions. That will certainly make
things neater. Thanks!

-- George

Jul 19 '05 #3
On 29 Apr 2005 11:02:59 -0700, gr*@ll.mit.edu wrote:
I often find myself wanting an instance attribute that can take on only ^^^^^^^^
without checking deeply, are you not sharing state among all instance?
See following for an alternative way, allowing initialization by a
first assignment of a name sequence, followed by normal operation on
a per instance basis.
a few fixed symbolic values. (This is less functionality than an enum,
since there are no *numbers* associated with the values). I do want
the thing to fiercely object to assignments or comparisons with
inappropriat e values. My implementation below gets me:

.import mode
.class C(object):
. status = mode.Mode('star ted', 'done', 'on-hold')
.
.c=C()
.c.status = 'started'
.c.status = 'stated': #Exception raised
.if c.status == 'done': something
.if c.status == 'stated': #Exception raised
.if c.status.done: something #simpler and clearer than string compare
.if c.status < 'done': something # Mode arg strings define ordering

I would appreciate comments on the overall scheme, as well as about the
somewhat sneaky (I think) exporting of a property-factory instead of a
class. My intent is to provide a simple clear interface to the client
class ("C" above), but I don't want to do something *too* fragile or
confusing...
(I'd also welcome a better name than "Mode"...)

-------------------------- mode.py ----------------------
class _Mode: #internal use only, not exported.
def __init__(self, *vals):
if [v for v in vals if not isinstance(v, str)]:
raise ValueError, 'Mode values must be strings'
else:
self.values = list(vals)

def set(self, val):
if val not in self.values:
raise ValueError, 'bad value for Mode: "%s"' % val
else:
self.state = val

def __cmp__(self, other):
if other in self.values:
return cmp(self.values .index(self.sta te),
self.values.in dex(other))
else:
raise ValueError, 'bad value for Mode comparison'

def __getattr__(sel f, name):
if name in self.values:
return self.state == name
else:
raise AttributeError, 'no such attribute: "%s"' % name
def Mode(*vals): # *function* returning a *property*, not a class.
m = _Mode(*vals)
def _insert_mode_ge t(self):
return m
def _insert_mode_se t(self, val):
m.set(val)
return property(_inser t_mode_get, _insert_mode_se t)
-----------------------------------------------------------

Not tested beyond what you see ;-)

----< state.py >----------------------------------------------------------------------------------------------
# set up to validate state name strings
namerefcode = compile('a','', 'eval').co_code
non_name_chars = []
for c in (chr(i) for i in xrange(256)):
try:
if compile(c, '', 'eval').co_code != namerefcode:
non_name_chars. append(c)
except (SyntaxError, TypeError):
non_name_chars. append(c)
non_name_chars = ''.join(non_nam e_chars)
idem = ''.join([chr(i) for i in xrange(256)])

class Status(object):
def __get__(self, inst, cls=None):
if inst is None: return self
if not '_state' in inst.__dict__:
raise ValueError, 'Uninitialized instance state names'
return inst._state
def __set__(self, inst, value):
if not hasattr(inst, '_state'): inst._state = self.State(*val ue)
else: inst._state._se tv(value)

class State(object):
def __init__(self, *names):
for s in names:
if s[:1].isdigit() or s!= s.translate(ide m, non_name_chars) :
raise ValueError, '%r is not a valid name'%s
self._names = list(names)
self._value = names[0]
def _name_ck(self, name):
if name not in self._names:
raise AttributeError(
'Legal names are: %s -- not %r' % (', '.join(map(repr , self._names)), name))
def __getattr__(sel f, attr):
if attr.startswith ('_'):
return object.__getatt ribute__(self, attr)
self._name_ck(a ttr)
return self._value == attr
def _setv(self, value):
self._name_ck(v alue)
self._value = value
def __cmp__(self, other):
self._name_ck(o ther)
return cmp(self._names .index(self._va lue), self._names.ind ex(other))
def __str__(self):
return self._value

def test():
class C(object):
status = Status()
instances = [C(), C(), C()]
nameslist = map(str.split, ['started done on_hold', 'one two three', 'UNK running stopped'])
for i, (inst, names) in enumerate(zip(i nstances, nameslist)):
inst.status = names
inst.status = names[i]
print 'Instance %s names: %r' %(i, inst.status._na mes)
for i, inst in enumerate(insta nces):
print i, 'names:',inst.s tatus._names
print i, 'current:', inst.status
print i, ' '.join([' .%s? -> %s'% (name, getattr(inst.st atus, name)) for name in inst.status._na mes])
print i, ' '.join(['==%s? -> %s'% (name, inst.status == name) for name in inst.status._na mes])
print i, ' '.join([' >%s? -> %s'% (name, inst.status > name) for name in inst.status._na mes])
print i, ' '.join([' <%s? -> %s'% (name, inst.status < name) for name in inst.status._na mes])
try: inst.status = 'fini'
except Exception, e:
print 'Exception %s: %s' %(e.__class__._ _name__, e)
class D(object):
hownow = Status()
dinst = D()
for bogus in ['this$', 'an#d', 'with space', '4digitstart', 'bad\x00']:
try: dinst.hownow = ('verily', bogus, 'will', 'fail')
except Exception, e:
print 'Exception %s: %s' %(e.__class__._ _name__, e)

if __name__ == '__main__': test()
--------------------------------------------------------------------------------------------------------------
Result:

[ 0:00] C:\pywk\clp>py2 4 state.py
Instance 0 names: ['started', 'done', 'on_hold']
Instance 1 names: ['one', 'two', 'three']
Instance 2 names: ['UNK', 'running', 'stopped']
0 names: ['started', 'done', 'on_hold']
0 current: started
0 .started? -> True .done? -> False .on_hold? -> False
0 ==started? -> True ==done? -> False ==on_hold? -> False
0 >started? -> False >done? -> False >on_hold? -> False
0 <started? -> False <done? -> True <on_hold? -> True
Exception AttributeError: Legal names are: 'started', 'done', 'on_hold' -- not 'fini'
1 names: ['one', 'two', 'three']
1 current: two
1 .one? -> False .two? -> True .three? -> False
1 ==one? -> False ==two? -> True ==three? -> False
1 >one? -> True >two? -> False >three? -> False
1 <one? -> False <two? -> False <three? -> True
Exception AttributeError: Legal names are: 'one', 'two', 'three' -- not 'fini'
2 names: ['UNK', 'running', 'stopped']
2 current: stopped
2 .UNK? -> False .running? -> False .stopped? -> True
2 ==UNK? -> False ==running? -> False ==stopped? -> True
2 >UNK? -> True >running? -> True >stopped? -> False
2 <UNK? -> False <running? -> False <stopped? -> False
Exception AttributeError: Legal names are: 'UNK', 'running', 'stopped' -- not 'fini'
Exception ValueError: 'this$' is not a valid name
Exception ValueError: 'an#d' is not a valid name
Exception ValueError: 'with space' is not a valid name
Exception ValueError: '4digitstart' is not a valid name
Exception ValueError: 'bad\x00' is not a valid name

Regards,
Bengt Richter
Jul 19 '05 #4

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

Similar topics

18
3030
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases...
15
2115
by: Ron Adam | last post by:
Does anyone have suggestions on how to improve this further? Cheers, Ron_Adam def getobjs(object, dlist=, lvl=0, maxlevel=1): """ Retrieve a list of sub objects from an object. """
2
2000
by: Reid Priedhorsky | last post by:
Dear group, I'd have a class defined in one module, which descends from another class defined in a different module. I'd like the superclass to be able to access objects defined in the first module (given an instance of the first class) without importing it. Example of what I'm looking for: <<<file spam.py>>> class Spam(object):
6
1899
by: Bob | last post by:
Declaring a module level form object in multiple froms within a project to show another project form causes a stack overflow and other assorted errors. Can anyone help?
42
4927
by: WindAndWaves | last post by:
Dear All Can you tell me why you use a class module??? Thank you Nicolaas ---
3
2479
by: Johnny M | last post by:
using Access 2003 Pardon the subject line, but I don't have a better word for this strange behavior (or behavior I don't understand!!!) I have a class module named DepreciationFactor. One of the properties is a follows (irrelevant code omitted):
30
2054
by: Franck PEREZ | last post by:
Hello, I'm developing a small XML marshaller and I'm facing an annoying issue. Here's some sample code: ########### My test application ############ class Foo(object): #The class I'd like to serialize pass
4
1075
by: cj | last post by:
I've got some classes for a program and the classes were written in Module1. It works fine however I am curious if instead of doing "project|add module" I'd done "project|add class" how is that different? Here is the module I added. Note it contains 2 classes and the sub main. Module Module1 <STAThread()> Public Sub main(ByVal CmdArgs() As String) Dim mainForm As New Form1
6
4021
by: JonathanOrlev | last post by:
Hello everyone, I have a newbe question: In Access (2003) VBA, what is the difference between a Module and a Class Module in the VBA development environment? If I remember correctly, new types of objects (classes) can only be defined in Class modules.
0
7993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7920
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8404
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8268
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6730
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5867
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5440
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3900
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.