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

Home Posts Topics Members FAQ

ADT for restricted set of values

Howdy all,

I'd like to have an Abstract Data Type for a scalar value that is
restricted to a small set of values. Like an Enum, I suppose.

What I would like is to be able to use simple 'str' values in most of
the code, but where the values are actually used in a semantically
meaningful context, have them used as an ADT that will barf if the
value isn't part of the set.

Using the HumanSex class example from an earlier thread:

class HumanSex(str):

_descriptions = {
None: "unknown",
'male': "Male",
'female': "Female",
}

def __init__(self, value):
str.__init__(va lue)
if value not in self._descripti ons:
raise ValueError, \
"Not a valid HumanSex value: '%s'" % value

def __get_descripti on(self):
return self._descripti ons[self]
description = property(__get_ description)

This way, most of the rest of the code doesn't need to know that the
HumanSex instances are anything but a simple 'str' value.

Is this a sensible way to do what I'm describing? Am I missing a
common programming pattern?

--
\ "I bought a self learning record to learn Spanish. I turned it |
`\ on and went to sleep; the record got stuck. The next day I |
_o__) could only stutter in Spanish." -- Steven Wright |
Ben Finney
Nov 4 '05 #1
1 1618
Ben Finney wrote:
Howdy all,

I'd like to have an Abstract Data Type for a scalar value that is
restricted to a small set of values. Like an Enum, I suppose.

What I would like is to be able to use simple 'str' values in most of
the code, but where the values are actually used in a semantically
meaningful context, have them used as an ADT that will barf if the
value isn't part of the set.


How about this:

class BaseEnum(str):
"""Base class for enumerations. You must subclass and provide
values for the _valid list."""

_valid = []

def __init__(self, v):
assert self in self._valid, 'value %r not in %r' % (self,
self._valid)

cass Gender(BaseEnum ):
_valid = ['male', 'female', 'unknown']

Trying the following:

Gender('male')
Gender('female' )
assert Gender('male') == 'male'
Gender('shemale ')

The last will return an error:
AssertionError: value 'shemale' not in ['male', 'female', 'unknown']

Graham

Nov 4 '05 #2

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

Similar topics

30
2545
by: Sean R. Lynch | last post by:
I've been playing around with Zope's RestrictedPython, and I think I'm on the way to making the modifications necessary to create a capabilities-based restricted execution system. The idea is to strip out any part of RestrictedPython that's not necessary for doing capabilities and do all security using just capabilities. The basic idea behind capabilities is that you don't give any piece of code you don't trust a reference to something...
13
4000
by: Rolf Magnus | last post by:
Hi, I would like to embed a python interpreter within a program, but since that program would be able to automatically download scripts from the internet, I'd like to run those in a restricted environment, which basically means that I want to allow only a specific set of modules to be used by the scripts, so that it wouldn't be possible for them to remove files from the hard drive, kill processes or do other nasty stuff. Is there any...
5
2579
by: Peter Ammon | last post by:
It's my understanding that the printf() function is declared as int printf(const char * restrict format, ...); in stdio.h. And loosely speaking, if a parameter is declared as restricted, then accesses to the object must go through that parameter. Does this mean that printf("%s", "%s");
0
1097
by: Jussi | last post by:
Hi! I have a COM server object in which I have set certain interfaces restricted/hidden. For example With VB client these attributes works as excpected. However if I use this same COM component from C# client hidden/restricted attributes seems to have no effect. Is there any way to restrict C# client's access to certain
1
7750
by: Kiran_Juikar | last post by:
In my application, I want to copy some file from network location to local machine folder. It works fine for administrator but If I run it with restricted user (not having permissions to local machine folder) it gives me Access denied error. How can I programmatically give permission to the foder for restrcited user.
1
2588
by: rz0 | last post by:
Hi, I have a function that takes a callback function (function pointer of some type) and a value to be passed to it when it is invoked later. The prototype looks pretty much like : int reg(int (*)(void *), void *); Now, it appears that most of the values (second argument) I want to register have types of the form T * restrict *, that is, a pointer to
1
1880
by: steve | last post by:
Hello ! I have a special need implementing a lexical parser. I have a C restricted grammar, in which I accept such operations as (3<3.5) or (s<"string"). My problem is that I meet some conception problem. I would like Yacc to simply operate $$=$1+$3 on my following Node objects. I tryed to overload operators so that NodeInt n1 < NodeLong n2 automatically get the right values with getValue() function but C++ spec forbids template virtual...
6
4268
by: burkley | last post by:
In XML Schema, is it possible to derive a complex type via restriction and have the new derived type be in a different namespace than the original base type? I've banged on this for 2 days now and I'm starting to think the answer is no. I've searched this group and have not seen anything discussing this. the base type. All values of the restricted type are also valid according to the base type".
3
2632
by: Paul Rudin | last post by:
I'm occasionally seeing tracebacks like this: Traceback (most recent call last): File "logging/__init__.py", line 744, in emit File "logging/__init__.py", line 630, in format File "logging/__init__.py", line 421, in format RuntimeError: instance.__dict__ not accessible in restricted mode I'm not sure what it means. Googling leads me to <http://docs.python.org/lib/restricted.htmlbut that says that those
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
7921
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...
1
8056
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
5870
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
3901
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...
0
3944
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1511
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.