On Nov 7, 7:48*am, jim...@gmail.com wrote:

I am trying to simulate the execution of some PLC ladder logic in

python.

I manually modified the rungs and executed this within python as a

proof of concept, but I'd like to be able to skip the *modification

step. *My thought was that this might be able to be completed via

overloading, but I am not sure if (or how) it could be done.

overloadings:

* * + ==OR

* * * ==AND

* * / ==NOT

Example original code:

* * *A=/B+C*D

translates to:

* * A=not B or C and D

I tried

* * def __add__ (a,b):

* * * * return (a or b)

which gives me this:

* * >>x=False

* * >>y=True

* * >>x+y

* * * * 1

* * >>x=True

* * >>x+y

* * * * 2

How can this be done?

This reminds me of a little project I wrote a long time ago to use

operator overloading to compute the overall resistance of a network of

resistors - I used - for series connections and | for parallel. You

can see the code here:

http://pastebin.com/m1e89aae9
If you are going to design a mini-DSL using overloading, you'll first

have to choose which operators correspond to your syntax, working

within those offered by Python. For NOT, you have only have two unary

operators to choose from, ~ (__invert__) or - (__neg__). / is not

supported as a unary operator, only as binary division (__div__ or

__truediv__). For AND and OR, you have a wealth of binary operators

from which to pick. But first, think about any precedence of

operations. As I recall from my ladder diagramming days, logic was

strictly left-to-right, with no precedence for one operation over the

other (as opposed to common arithmetic operator precedence, in which

in 4+2*3 evaluates as 4+(2*3), as opposed to (4+2)*3, which would be

strict left-to-right evaluation). When you implement your DSL, you

will still be subject to Python's definitions for operator

precedence. So if you want strict left-to-right evaluation, then

choose two operators at the same level of precedence, such as + and -,

or * and /. On the other hand, if you want AND evaluated before OR

(which is typical precedence in programming), then pick operators from

two different levels of precedence.

-- Paul