473,624 Members | 2,026 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

derivation: sick Python trick of the week

WARNING:

The following is NOT all Pythonic. However, it is Python. This is just
fun--nothing I'm going to put into production. I don't have any
questions or problems--just thought I'd share.
BACKGROUND:

I've been playing around for a couple of days with parsing and
derivation ("unparsing" ). My goal was and is to take snippets of Python
code and turn them into "equivalent " SQL statements. For example, the
Python snippet:

x.Group > 3 or x.Name == 'fumanchu'

....should equate to an SQL WHERE clause like:

Group > 3 or Name = 'fumanchu'

I tore into the compiler package, and hacked together a solution which
does just that. One invokes such a task with code like:

sqlstmt = derive.ADODeriv er().evaluate(" x.Group > 3 or x.Name ==
'fumanchu'")

However, it's parsing the output of a compiler.Transf ormer, which itself
is parsing an AST (lots of nested tuples), so it's not very quick. 1000
repetitions of the above example take over 1/2 second to run on my
laptop.
IT'S ALIVE!!!

In a fit of mad-scientist genius (get out the pitchforks and torches), I
wondered if it might be faster to let Python do *all* the parsing, and
just watch it work and take notes. That's what the code below does. The
sick and twisted part is how one invokes this technique:
import sick_derive
x = sick_derive.Exp ression()
(x.a == 3) & ((x.b > 1) | (x.b < -10))
x ['a', 3, <built-in function eq>, 'b', 1, <built-in function gt>, 'b',
-10, <built-in function lt>, <built-in function or_>, <built-in function
and_>] sick_derive.Der iver().derive(x )

'((a == 3) and ((b > 1) or (b < -10)))'

Yes, in line two we run comparisons and boolean operations on
non-existent attributes of x, and discard the results! Sick. However, we
were keeping track (as the repr of x shows on line 3); we built a
postfix list of the comparisons we performed. When we call
Deriver().deriv e(x), the Deriver traverses that list and rebuilds the
Python code. I made a similar ADODeriver which builds SQL code (too
complex to include here; it also used a different Adapter for the
object-to-DB mapper).

I had to replace boolean 'and' and 'or' with binary calls in order to
override them, and 'not' with 'neg'. That makes it even sicker. And it's
*far* from obvious that 'x.a' should reduce to just 'a'.

But it's about 7 times as fast as the first solution. ;)
So for a host of reasons, don't ever use this. I won't. But it was
interesting.
Robert Brewer
MIS
fu******@amor.o rg
---- sick_derive.py ----

import operator
def containedby(a, b):
"""Return the outcome of the test a in b. Note the operand order."""
return a in b

def startswith(a, b):
"""Return True if string starts with the prefix, otherwise return
False."""
return a.startswith(b)

def endswith(a, b):
"""Return True if the string ends with the suffix, otherwise return
False."""
return a.endswith(b)
class Operand(object) :
"""Push atoms onto a postfix expression stack."""
def __init__(self, expr, name=''):
self.expr = expr
self.name = name

def __neg__(self):
self.expr.appen d(operator.not_ )
return Operand(self.ex pr)

def __lt__(self, other):
self.expr.exten d([self.name, other, operator.lt])
return Operand(self.ex pr)

def __le__(self, other):
self.expr.exten d([self.name, other, operator.le])
return Operand(self.ex pr)

def __eq__(self, other):
if self.name:
self.expr.exten d([self.name, other, operator.eq])
else:
self.expr.exten d([other, operator.eq])
return Operand(self.ex pr)

def __ne__(self, other):
self.expr.exten d([self.name, other, operator.ne])
return Operand(self.ex pr)

def __ge__(self, other):
self.expr.exten d([self.name, other, operator.ge])
return Operand(self.ex pr)

def __gt__(self, other):
self.expr.exten d([self.name, other, operator.gt])
return Operand(self.ex pr)

def __and__(self, other):
self.expr.appen d(operator.and_ )
return Operand(self.ex pr)

def __or__(self, other):
self.expr.appen d(operator.or_)
return Operand(self.ex pr)

def __contains__(se lf, other):
self.expr.exten d([self.name, other, operator.contai ns])
return Operand(self.ex pr)

def contains(self, other):
self.expr.exten d([self.name, other, operator.contai ns])
return Operand(self.ex pr)

def containedby(sel f, other):
self.expr.exten d([self.name, other, containedby])
return Operand(self.ex pr)

def startswith(self , other):
self.expr.exten d([self.name, other, startswith])
return Operand(self.ex pr)

def endswith(self, other):
self.expr.exten d([self.name, other, endswith])
return Operand(self.ex pr)
class Expression(list ):
"""A postfix recorder and evaluator for operations on arbitrary
objects."""

unaries = (operator.not_, )
binaries = (operator.and_,
operator.or_,
operator.lt,
operator.le,
operator.eq,
operator.ne,
operator.gt,
operator.ge,
operator.contai ns,
containedby,
startswith,
endswith,
)

def __getattr__(sel f, name):
return Operand(self, name)

def evaluate(self, obj, ifEmpty=True):
"""Evaluate an object against self.
Names will be looked up in the object's attribute dictionary.
"""
stack = self[:]
if not stack:
return ifEmpty

def operate():
op = stack.pop()
if op in self.unaries:
a = operate()
return op(a)
elif op in self.binaries:
b = operate()
a = operate()
if a not in (True, False):
a = getattr(obj, a)
return op(a, b)
else:
return op
return operate()
class Adapter(object) :
"""Transfor m values according to their type."""

def __init__(self):
self.default_pr ocessor = repr
self.processors = {}

def process(self, value):
try:
xform = self.processors[type(value)]
except KeyError:
xform = self.default_pr ocessor
return xform(value)
class Deriver(object) :
"""Derive an Expression according to a grammar."""

def __init__(self, adapter=Adapter ()):
f = adapter.process
self.unaries = {operator.not_: lambda x: "(not %s)" % x}
self.binaries = {operator.and_: lambda x, y: "(%s and %s)" % (x,
y),
operator.or_: lambda x, y: "(%s or %s)" % (x,
y),
operator.lt: lambda x, y: "(%s < %s)" % (x,
f(y)),
operator.le: lambda x, y: "(%s <= %s)" % (x,
f(y)),
operator.eq: lambda x, y: "(%s == %s)" % (x,
f(y)),
operator.ne: lambda x, y: "(%s != %s)" % (x,
f(y)),
operator.gt: lambda x, y: "(%s > %s)" % (x,
f(y)),
operator.ge: lambda x, y: "(%s >= %s)" % (x,
f(y)),
operator.contai ns: lambda x, y: "(%s in %s)" %
(f(y), x),
containedby: lambda x, y: "(%s in %s)" % (x,
f(y)),
startswith: lambda x, y: "(%s.startswith (%s))"
% (x, f(y)),
endswith: lambda x, y: "(%s.endswith(% s))" %
(x, f(y)),
}
self.ifEmpty = ''

def derive(self, expr):
try:
stack = expr[:]
except TypeError, x:
x.args += (type(expr), )
raise x

if not stack:
return self.ifEmpty

def operate():
op = stack.pop()
if op in self.unaries:
a = operate()
return self.unaries[op](a)
elif op in self.binaries:
b = operate()
a = operate()
return self.binaries[op](a, b)
else:
return op
return operate()

Jul 18 '05 #1
5 1768
Robert Brewer wrote:
In a fit of mad-scientist genius (get out the pitchforks and torches), I
wondered if it might be faster to let Python do *all* the parsing, and
just watch it work and take notes. That's what the code below does. The
sick and twisted part is how one invokes this technique:
It's not really all that sick, or at least it's not a new
idea. I'm sure there's at least one DB module out there
somewhere that uses this technique.
Yes, in line two we run comparisons and boolean operations on
non-existent attributes of x, and discard the results! Sick.
That part is perhaps a bit too twisted. It's not really
necessary, you could just as well design it so you say

expr = (x.a == 3) & ((x.b > 1) | (x.b < -10))
And it's
*far* from obvious that 'x.a' should reduce to just 'a'.
In the case of database queries, you can make this seem
much more natural by having 'x' represent some meaningful
object such as a table.

db = open_database(" favourite_fruit s")
fruits = db.fruits
query = (fruits.kind == "apple") && (fruits.tastine ss >= 3)
I had to replace boolean 'and' and 'or' with binary calls in order to
override them, and 'not' with 'neg'. That makes it even sicker.


Yes, that's the main nuisance with this technique. I have
a PEP idea floating around to make and/or/not overridable,
for this very purpose. Hmmm... does that make me sick?-)

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg

Jul 18 '05 #2
"Greg Ewing (using news.cis.dfn.de )" <wm*******@snea kemail.com> writes:
Yes, that's the main nuisance with this technique. I have
a PEP idea floating around to make and/or/not overridable,
for this very purpose. Hmmm... does that make me sick?-)


I'd say so.

Cheers,
mwh

--
. <- the point your article -> .
|------------------------- a long way ------------------------|
-- Cristophe Rhodes, ucam.chat
Jul 18 '05 #3
has
"Greg Ewing (using news.cis.dfn.de )" <wm*******@snea kemail.com> wrote in message news:<c1******* ******@ID-169208.news.uni-berlin.de>...
Robert Brewer wrote:
In a fit of mad-scientist genius (get out the pitchforks and torches), I wondered if it might be faster to let Python do *all* the parsing, and just watch it work and take notes. That's what the code below does. The sick and twisted part is how one invokes this technique:
It's not really all that sick, or at least it's not a new
idea.


And a lot less sick that hacking the language compiler in my
opinion/experience... (I came to Python from a certain language whose
use of clever-clever compiler hackery makes it ludicrously tetchy
about how you structure your code. ("No, no! You must write it THIS
way!") Such contextual confusion and pain in the brain that you
wouldn't believe, the moment you try writing anything but the most
trivial code in the most trivial fashion.)

I'm sure there's at least one DB module out there
somewhere that uses this technique.
Can't speak for DB modules, but must confess to using a close
variation of this technique in my current project - a
MacPython-to-Apple Event Manager bridge - where it's used to assemble
AEM references and test expressions.

Main difference in my design to Robert's is that call capture objects
don't share mutable state. This means users can safely define new
references/test expressions by extending existing ones if they like,
rather than having to create a new one from scratch each time; the
original object won't be changed by this. eg:

import sick_derive

x = sick_derive.Exp ression()

e1 = ((x.b > 1) | (x.b < -10))
e2 = (e1 == 4)

print sick_deriver.De river().derive( e2.expr)
--> (((b > 1) or (b < -10)) == 4)

print sick_derive.Der iver().derive(e 1.expr)
--> (((b > 1) or (b < -10)) == 4) # !!! e1 has also changed!
vs:

from appscript import its

e3 = its.name_extens ion.isin(['jpg', 'jpeg'])
e4 = e3 .OR (its.file_type == 'JPEG')

print e4
# --> OR(its.name_ext ension.isin(['jpg', 'jpeg']), its.file_type
== 'JPEG')

print e3
# --> its.name_extens ion.isin(['jpg', 'jpeg'])

In the case of database queries, you can make this seem
much more natural by having 'x' represent some meaningful
object such as a table.

db = open_database(" favourite_fruit s")
fruits = db.fruits
query = (fruits.kind == "apple") && (fruits.tastine ss >= 3)
Once you solve the mutating state problem, you can simply have your
module define a single (generic) 'root' object that users can use to
build any expression. (Appscript stores this object in its global
'its' variable, allowing it to be exported.)

I had to replace boolean 'and' and 'or' with binary calls in order to override them, and 'not' with 'neg'. That makes it even sicker.


Yes, that's the main nuisance with this technique.


Yup. (Trouble with these sorts of exercises is sooner or later you
start knocking against the boundaries of what the language can do,
and'll just tie yourself in knots with outrageous acrobatics if you're
not careful.)

I have
a PEP idea floating around to make and/or/not overridable,
for this very purpose. Hmmm... does that make me sick?-)


Raised this idea on the PythonMac SIG last week; it died a quick death
once someone pointed out that boolean operators also perform flow
control (lazy evaluation of operands). Implementing a suitable
override mechanism would be a non-trivial exercise (and seems unlikely
the BDFL would support it).
Jul 18 '05 #4
has wrote:
Raised this idea on the PythonMac SIG last week; it died a quick death
once someone pointed out that boolean operators also perform flow
control


I do have a plan for handling that. Yes, it'll be non-trivial
(although not too complicated, I hope), and yes, Guido probably
won't like it much, but you never know 'till you try...

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg

Jul 18 '05 #5
has
"Greg Ewing (using news.cis.dfn.de )" <wm*******@snea kemail.com> wrote in message news:<c1******* ******@ID-169208.news.uni-berlin.de>...
has wrote:
Raised this idea on the PythonMac SIG last week; it died a quick death
once someone pointed out that boolean operators also perform flow
control


I do have a plan for handling that. Yes, it'll be non-trivial
(although not too complicated, I hope), and yes, Guido probably
won't like it much, but you never know 'till you try...


You certainly have my interest...

has
Jul 18 '05 #6

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

Similar topics

0
1514
by: Peter Otten | last post by:
QOTW: "It seems to me that in many respects Python is a programmer's programming language." - Arthur "My code did NOT have any leaks in it! :-D That's almost a miraculous occurrence when programming in C." - Kamilche Did you know the zip() trick? Christopher T King explains the effect of preceding a function argument with an asterisk to Garett. http://groups.google.com/groups?th=bab2fa27521fc8c5
0
1522
by: Simon Brunning | last post by:
QOTW: "" - John Machin, snipping a section of Perl code. "What sort of programmer are you? If it works on your computer, it's done, ship it!" - Grant Edwards Guido invites us to comment on PEP 343. This Python Enhancement Proposal includes a 'with' statement, allowing you simply and reliably wrap a block of code with entry and exit code, in which resources can be acquired and released. It also proposes enhancements
0
921
by: Simon Brunning | last post by:
QOTW: "" - John Machin, snipping a section of Perl code. "What sort of programmer are you? If it works on your computer, it's done, ship it!" - Grant Edwards Guido invites us to comment on PEP 343. This Python Enhancement Proposal includes a 'with' statement, allowing you simply and reliably wrap a block of code with entry and exit code, in which resources can be acquired and released. It also proposes enhancements
1
1648
by: Gabriel Genellina | last post by:
QOTW: "That's the Martellibot for you. Never use a word where a paragraph with explanatory footnotes will do. Sigh. I miss him on c.l.py." - Simon Brunning "Conclusion: advice to 'try Python for yourself' is apt in a way the original questioner might not realize." - Cameron Laird A small survey revealing so many people using Python
0
8680
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8624
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
8336
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,...
0
8478
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
7164
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...
0
5565
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
4082
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
4176
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1485
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.