473,387 Members | 1,535 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

design a Condition class

Hello,

i posted for suggestions a little idea even if it still needs further
thoughts but as i'm sure you could help :)

if would like to implement some kind of Condition class which i coud
use to build bricks of more complex condition, conditions are based on
fields by using regexp

class Condition:
def __init__(self, field0, field1, field2):
self.field0 = field0
self.field1 = field1
self.field2 = field2
def match(self, against):
w, t, l = against
f0 = False
if self.field0 is None:
f0 = True
else:
f0 = self.field0.search(w)
if self.field1 is None:
f1 = True
else:
f1 = self.field1.search(t)
if self.field2 is None:
f2 = True
else:
f2 = self.field2.search(l)
return f0 and f1 and f2

c0 = Condition(re.compile("something"), None,
re.compile("somethingelse"))
c1 = Condition(re.compile("another"), None, None)

i can use

if c0.search(myitem)

but i would like to be able to have composition such as :

c2 = c0 | c1

which should be understood as defining a new c2 which is able to match
(c0 or c1) from c0 and c1 already defined.

actually i can imagine a

def OR(c0, c1):
# here => missing None support 'a or None' is 'a'
return Condition(re.compile("|".join((c0.field0.pattern,
c1.field0.pattern)),
re.compile("|".join((c0.field1.pattern,
c1.field1.pattern)),
re.compile("|".join((c0.field2.pattern,
c1.field2.pattern))

the idea is to build c2 = Condition(re.compile("something|another"),
None, re.compile("somethingelse"))
c2 = OR(c0, c1)

but maybe have you clever suggestions ?

best regards.

May 10 '06 #1
4 1881


jo******@yahoo.fr wrote:
Hello,

i posted for suggestions a little idea even if it still needs further
thoughts but as i'm sure you could help :)

if would like to implement some kind of Condition class which i coud
use to build bricks of more complex condition, conditions are based on
fields by using regexp

I just wanted to make the comment that there already exists a
Condition() class in the threading module. If you plan on using your
class with the threading module you might wish to use another name.

-carl
--

Carl J. Van Arsdall
cv*********@mvista.com
Build and Release
MontaVista Software

May 10 '06 #2
<jo******@yahoo.fr> wrote in message
news:11**********************@v46g2000cwv.googlegr oups.com...
Hello,

i posted for suggestions a little idea even if it still needs further
thoughts but as i'm sure you could help :)

if would like to implement some kind of Condition class which i coud
use to build bricks of more complex condition, conditions are based on
fields by using regexp

class Condition:
def __init__(self, field0, field1, field2):
self.field0 = field0
self.field1 = field1
self.field2 = field2
def match(self, against):
w, t, l = against
f0 = False
if self.field0 is None:
f0 = True
else:
f0 = self.field0.search(w)
if self.field1 is None:
f1 = True
else:
f1 = self.field1.search(t)
if self.field2 is None:
f2 = True
else:
f2 = self.field2.search(l)
return f0 and f1 and f2

c0 = Condition(re.compile("something"), None,
re.compile("somethingelse"))
c1 = Condition(re.compile("another"), None, None)

i can use

if c0.search(myitem)

but i would like to be able to have composition such as :

c2 = c0 | c1

which should be understood as defining a new c2 which is able to match
(c0 or c1) from c0 and c1 already defined.

actually i can imagine a

def OR(c0, c1):
# here => missing None support 'a or None' is 'a'
return Condition(re.compile("|".join((c0.field0.pattern,
c1.field0.pattern)),
re.compile("|".join((c0.field1.pattern,
c1.field1.pattern)),
re.compile("|".join((c0.field2.pattern,
c1.field2.pattern))

the idea is to build c2 = Condition(re.compile("something|another"),
None, re.compile("somethingelse"))
c2 = OR(c0, c1)

but maybe have you clever suggestions ?

best regards.


Your composition of expressions to match is very similar to the definition
of grammars in pyparsing. Here's a small example, to parse "Hello,
World!"-type strings.
from pyparsing import Word, alphas

# define grammar
greet = Word( alphas ) + "," + Word( alphas ) + "!"

# input string
hello = "Hello, World!"

# parse input string
print hello, "->", greet.parseString( hello )
The Word class matches any group of characters composed of the letters in
the string passed to the constructor. alphas is a string constant of the
upper and lower case letters A thru Z. This sample program prints out:

Hello, World! -> ['Hello', ',', 'World', '!']

pyparsing has many more expression types, including Literal,
CaselessLiteral, Optional, ZeroOrMore, and OneOrMore. There are also
combining forms, And, Or, MatchFirst, and Each. The handy part of these
combining forms is that there are operator short-cuts:
a + b is the same as And([a,b]) (that is, a followed by b)
a | b is the same as MatchFirst([a,b]) (if not match a, then try to match b)
a ^ b is the same as Or([a,b]) (try matching a and b, choose longest match)
a @ b is the same as Each([a,b]) (match a and b in any order - good for
matching options that can be specified in any order)

The resulting grammar expressions are fairly readable. The greet expression
above translates to

greet is a word group of alphabetic characters, followed by a ",", followed
by another word group of alphabetic characters, followed by a "!". Note
that there is no explicit specification of whitespace - whitespace will
terminate a word group, but is not necessary if the grammar is unambiguous
without it. For instance, this expression will match any of:

Hello,World!
Hello , World !
Hello ,World !
.... and so on.

Of course it will also match:
Howdy, pardner!
Greetings, Earthling!
Aloha, wahini!

The matched results are returned as an object of type ParseResults, which
can be accessed like a list, a dictionary, or an object with attributes (if
you associated names with individual elements of the parse expression).

You can get more info and download info at pyparsing.wikispaces.com. Even
if you choose not to use pyparsing, you might get some ideas on your own
implementation.

-- Paul
May 10 '06 #3
Carl J. Van Arsdall wrote:
(snip)
I just wanted to make the comment that there already exists a
Condition() class in the threading module. If you plan on using your
class with the threading module you might wish to use another name.

As far as I remember, Python has namespaces, so I don't see the point
here...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
May 12 '06 #4
jo******@yahoo.fr wrote:
Hello,

i posted for suggestions a little idea even if it still needs further
thoughts but as i'm sure you could help :)

if would like to implement some kind of Condition class which i coud
use to build bricks of more complex condition, conditions are based on
fields by using regexp

class Condition:
Do yourself a favor and use newstyle classes:
class Condition(object): def __init__(self, field0, field1, field2):
self.field0 = field0
self.field1 = field1
self.field2 = field2
def match(self, against):
w, t, l = against
f0 = False
if self.field0 is None:
f0 = True
else:
f0 = self.field0.search(w)
if self.field1 is None:
f1 = True
else:
f1 = self.field1.search(t)
if self.field2 is None:
f2 = True
else:
f2 = self.field2.search(l)
return f0 and f1 and f2 c0 = Condition(re.compile("something"), None,
re.compile("somethingelse"))
c1 = Condition(re.compile("another"), None, None)

i can use

if c0.search(myitem)
Have you actually tested this ?-)
(hint : the method name is 'match', not 'search')


but i would like to be able to have composition such as :

c2 = c0 | c1

which should be understood as defining a new c2 which is able to match
(c0 or c1) from c0 and c1 already defined.

actually i can imagine a

def OR(c0, c1):
# here => missing None support 'a or None' is 'a'
return Condition(re.compile("|".join((c0.field0.pattern,
c1.field0.pattern)),
re.compile("|".join((c0.field1.pattern,
c1.field1.pattern)),
re.compile("|".join((c0.field2.pattern,
c1.field2.pattern))

the idea is to build c2 = Condition(re.compile("something|another"),
None, re.compile("somethingelse"))
c2 = OR(c0, c1)

but maybe have you clever suggestions ?


use the __or__(self, other) special method.
http://www.python.org/doc/2.4.2/ref/numeric-types.html
Here is a somewhat rewritten, hopefully more pythonic version - will
need some more works, specially wrt/ error handling :

class Condition(object):
def __init__(self, *exps):
self._exps = exps

def match(self, *targets):
# don't know how you want to handle this case
assert len(targets) == len(self._exps), \
"expected %d args, got %d" % (len(self._exps), len(targets))

for exp, target in zip(self._exps, targets):
# takes care of None in the expression list
if not (exp is None or exp.search(target)):
return False
return True

def __or__(self, other):
""" cf http://www.python.org/doc/2.4.2/ref/numeric-types.html

"""
# I let you take care of all error handling...
# take care of what happens if
# len(other._exps) != len(self._exps)
# NB : itertools might be of some help here
exps = [re.compile("(%s)|(%s)" % (e1.pattern, e2.pattern)) \
for e1, e2 in zip(self._exps, other._exps)]
return self.__class__(*exps)
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
May 12 '06 #5

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

Similar topics

3
by: Neil Zanella | last post by:
Hello, It seems to me that using too many variables at class scope in C++ (e.g. private data members) can be just as bad as having a C program with lots of global variables. This is especially...
4
by: cmo63126 | last post by:
I'm not sure if this is bad design or not. It seems flawed, but I'm not sure. Is it wrong to create an instance of a class within the class itself? Any feedback appreciated. public class...
3
by: Angus Comber | last post by:
Hello I am attempting to build a set of classes which handle telephony. Basically the handling of phone calls. My design currently has two main classes - one dealing with the device and the...
4
by: lorirobn | last post by:
Hello, I'd be curious to hear other thoughts on my database and table design. My database is for 'space use' in a lodging facility - will hold all spaces, like rooms (lodging rooms, dining...
29
by: MP | last post by:
Greets, context: vb6/ado/.mdb/jet 4.0 (no access)/sql beginning learner, first database, planning stages (I think the underlying question here is whether to normalize or not to normalize this...
4
weaknessforcats
by: weaknessforcats | last post by:
Design Patterns – State Often computer software operates based on a condition called a state. These states traditionally have been implemented using a switch statement. The cases of the switch...
4
by: 1230987za | last post by:
Hi, Let's say I have the following class: class foo { public: foo(); void addItem(int item); private:
37
by: Phlip | last post by:
1230987za wrote: Kanze is a classically-trained "unit tester". In some circles "unit" is a QA concept - specifically, if a test fails, you only need to inspect one unit. So "units" are...
4
by: Pallav singh | last post by:
Hi , when should i select Factory Method / Prototype Design Pattern during my design phase ?? as both look similar to me Thanks in Advance Thanks Pallav
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
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...

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.