[melbourne-pug] mapping strings to class attributes/operators etc.
Justin Warren
daedalus at eigenmagic.com
Thu Jan 5 23:58:09 CET 2006
On Fri, 2006-01-06 at 00:13 +1100, lemeia wrote:
> Hi all,
>
> I'm a new member so hello everyone. I'm also a very new Python programmer.
> I'm really impressed with how quick it was to pick up Python. I've only really explored it as an option once I moved to the Linux platform from Windows.
>
> There's several things I'd like to do with Python as an all purpose utility language, but right now I would like to ask some advice on something in particular.
>
> I've got a program I use to read in large files of data which I use to create temporary objects and apply various comparisons and criteria against the objects I create and write to different output files and increment various statistic attributes in my application object for later reporting.
>
> The problem is that this isn't a fixed operation at all. It would be much better for these comparisons and actions to be very dynamic and prevent me from constantly changing the code and rerunning it.
>
> I was thinking I would like to develop some sort of mini-query language. Very simplified and fairly specific to the objects I am creating during my run.
>
> Is there a way in Python (using Dictionaries or something) to map strings to attributes, operators, functions etc...
>
> So if I wanted to say
> object: dimensions
> condition: height < 8.4 action: writeReject(height) exception: none
>
> then the application would parse it into a statement like:
> if dimension.height < 8.4:
> self.writeReject(height)
>
> In this way, I could save various conditions and even build them into a string of conditions called a criteria system (for example). I could also use the same mechanism to design reports based on alterable (and storable) conditions that the user specifies.
> Can this sort of thing be done cleverly in Python?
Python can do anything. :)
We do something along these lines in our seafelt software in that
there's a dynamic mapping of a given object class to a specific piece of
code that is executed in a semi-known way. What you'll need to do is
create a kind of templating system, which is basically what you've
referred to above.
Using your example above, you have a dimensions object, so it would
instanciate something like:
def __init__(self, name, condition, success, fail):
self.name = name
self.condition = condition
...
then you could have a function that gets called on all your template
created objects:
def process(self):
if eval(condition):
self.success()
else:
self.fail()
Processed like this:
for obj in template_objs:
obj.process()
If you want to pass arguments to dynamically called functions, you'll
need to pass in *args or **kwargs so that the correct arguments can be
looked up, as in your writeReject(height) example.
Hope that helps.
--
Justin Warren <daedalus at eigenmagic.com>
More information about the melbourne-pug
mailing list