473,738 Members | 5,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python code written in 1998, how to improve/change it?

Hello,
I am trying to study/understand OOP principles using Python. I have
found following code http://tinyurl.com/a4zkn about FSM (finite state
machine) on this list, which looks quite useful for my purposes. As
this code was posted long time ago (November 1998) I would like to ask
if the principles used in this code are still valid in the "modern"
Python and if/how it can be improved (revrited) using futures of
current version of Python.
Thanks for your comments for a "newbie" and for your patience.
Petr Jakes

Jan 19 '06 #1
41 2528
Petr Jakes wrote:
Hello,
I am trying to study/understand OOP principles using Python. I have
found following code http://tinyurl.com/a4zkn about FSM (finite state
machine) on this list, which looks quite useful for my purposes. As
this code was posted long time ago (November 1998) I would like to ask
if the principles used in this code are still valid in the "modern"
Python and if/how it can be improved (revrited) using futures of
current version of Python.
Thanks for your comments for a "newbie" and for your patience.


Python places great store on backwards-compatibility. Consequently I'd
suggest you try the code out, and report any problems you find back on
this list. I'd give you odds it will work.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Jan 19 '06 #2
Petr Jakes wrote:
Hello,
I am trying to study/understand OOP principles using Python. I have
found following code http://tinyurl.com/a4zkn about FSM (finite state
machine) on this list, which looks quite useful for my purposes. As
this code was posted long time ago (November 1998) I would like to ask
if the principles used in this code are still valid in the "modern"
Python and if/how it can be improved (revrited) using futures of
current version of Python.
Thanks for your comments for a "newbie" and for your patience.
Petr Jakes


Python has no goto.

If you think about the possible execution paths through a function, you
can represent that as a finite state machine: A FSM is just a graph, and
in a function, you get a FSM by treating each statement as a node, and
statements that can follow that statement (in the execution order) have
a (directed) edge to them (let's ignore exceptions for the moment). So for:

a=b
if a == 3:
z = 0
else:
z = 1
print 'spam'

we get:
(a=b) -> (if a == 3) -> (z = 0)
| |
(z = 1) -> (print 'spam)

Now, when we want to emulate a FSM in a function directly (rather than
some slower table-driven scheme), we need to use the constructs provided
by the language. But simple 'if' statements just don't cut it. We end up
with:

while state != 'final':
if state == 1:
# do state 1 stuff here
state = 3
elif state == 2:
# if cond:
state == 1
else:
state == 99
elif
...
else:
# unknown state

Problem with this approach is that, on average, you'll have n/2
comparisons of the state variable. What you want is to jump directly
from state 1 to state 3 without having to go anywhere else. You want a goto.

Another goto-less way is with functions. Each function is a state, which
sets a global function variable to the next state-function:

def f_state_1():
global func
# do state 1
func = f_state_3

def f_state_2():
global func
# do state_2 stuff
if cond:
func = f_state_1
else:
func = f_state_99

#etc.

func = f_state_1 # start_state

while func != None:
func()
We've eliminated the numerous comparisons, and it is, arguably, more
pythonic. But now you have a function-call overhead on each state
transition, and any information shared between states has to be in an
enclosing scope.

We want a goto.

Unfortunately, this is about the only problem I can think of where gotos
are useful. And for reasons well explained elsewhere, gotos are Not Good.

I've solved this in a very efficient, but rather unpythonic way.

First, you write (or generate) the code in the first way indicated
above. Lots of inefficient 'if' statements in one big function (say,
'fsm'). Then, you write another function (say 'gotoize') which takes fsm
as an argument, and *changes the byte code* of the fsm code object to
add JUMP_ABSOLUTE bytecodes (i.e. gotos) where the 'state' variable gets
reassigned.
fsm can then be decorated with gotoize, and you have a very fast (for
python) FSM. You are, essentially, doing some (fairly simple) byte-code
optimisation.

I can dig out the code if you are interested (except it's pretty untidy
at the moment. I'd be ashamed to show it in it's current state :-)

Ooops. I just reread your post and you claim (or is that plead?)
"newbie" status. Sorry if this is over your head. Hope it helps anyway.

Cheers,
Carl.
Jan 19 '06 #3
On Fri, 20 Jan 2006 10:27:58 +1300,
Carl Cerecke <cd*@maxnet.co. nz> wrote:
Petr Jakes wrote:
[ a query regarding some 1998 python code that implements a finite state
machine ]
Python has no goto.
Thank goodness!
func = f_state_1 # start_state while func != None:
func() We've eliminated the numerous comparisons, and it is, arguably, more
pythonic ...
Agreed.
... now you have a function-call overhead on each state transition ...
Have you profiled your code and demonstrated that this particular
function call consumes too much time?

If you can't stand the overhead of one [extra, parameterless] function
call per transition, especially *after* having eliminated the numerous
comparisons, then Python may not be the best tool for the job.
... and any information shared between states has to be in an
enclosing scope.
Well, no, not exactly. Consider an instance of a class that contains
its own data (and perhaps some of its own transition functions) but
inherits the basic state machine machinery from a finite state machine
class (or simply passes itself to a function that implements a finite
state machine by examining attributes of its argument).

And then there are (or should be!) purists who will claim that if your
state machine requires information to be shared between states, then you
don't have enough states! ;-)
We want a goto.


No, we don't.

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Jan 19 '06 #4
On Fri, 20 Jan 2006 10:27:58 +1300 in comp.lang.pytho n, Carl Cerecke
<cd*@maxnet.co. nz> wrote:

[...]

Python has no goto.
+1

[...]
We want a goto.


-1

Regards,
-=Dave

--
Change is inevitable, progress is not.
Jan 19 '06 #5
Carl Cerecke wrote:
Python has no goto.


Not in the standard library. You have to download the module:
http://www.entrian.com/goto/

;)

STeVe
Jan 19 '06 #6
Dave Hansen wrote:
On Fri, 20 Jan 2006 10:27:58 +1300 in comp.lang.pytho n, Carl Cerecke
<cd*@maxnet.co. nz> wrote:

[...]
Python has no goto.

+1

[...]
We want a goto.

-1


I agree entirely. My (rather unclearly made) point was that, for the
particular application (FSM), an unrestricted jump is really handy. Not
that we want goto in python (Eurghhhh!!) just to make this one case easier.

I learnt programming on a Commodore-64 where BASIC programs where
required to be liberally sprinkled with gotos (No else. Only one,
global, scope. No real functions). I know first hand the pain gotos can
inflict. We don't want to go back there.

But. They are still really handy for directly implementing a FSM in
code! Hence my JUMP_ABSOLUTE bytecode rewrite hack for FSMs.

Cheers,
Carl.
Jan 19 '06 #7
Dan Sommers wrote:
On Fri, 20 Jan 2006 10:27:58 +1300,
Carl Cerecke <cd*@maxnet.co. nz> wrote:
... now you have a function-call overhead on each state transition ...

Have you profiled your code and demonstrated that this particular
function call consumes too much time?


Yes. For a parser reading a reasonable size input file, the difference
is large enough to be noticeable.
If you can't stand the overhead of one [extra, parameterless] function
call per transition, especially *after* having eliminated the numerous
comparisons, then Python may not be the best tool for the job.


Maybe. Except the bytecode *is* quite fast enough. There is just no way
of writing python code so the compiler can generate that bytecode. Hence
the JUMP_ABSOLUTE bytecode rewrite hack.

Cheers,
Carl.
Jan 19 '06 #8
Thanks for your comments,
The mentioned "8 years old" code actually works somehow.

I am trying to solve very similar problem about FSM as the code in the
example does and I do not want to be overburden by the if/elif stuff or
by declaring state functions (which IMHO is very similar approach as
if/elif).

Because of above mentioned, something like FSM-generator looks as a way
to go for me (if I can judge with my poor skills).

I am using Steve's book "Python Web Programming" which is actually the
best I have found about OOP, classes etc. but as a newbie I am just
lost with subclass and mapping attributes etc. while trying to study
the code in the example (http://tinyurl.com/a4zkn).

All I wanted to know, if, thanks to the improvements in the Python
functionality over the years, it is possible to simplify somhow the old
code.

Otherwise I have to dig through :)

Petr Jakes

PS:
I agree and I do understand the reasons why NOT to use GOTO statements
in the code (aka spaghetti code).

Jan 20 '06 #9
Steven Bethard wrote:
Carl Cerecke wrote:
Python has no goto.

Not in the standard library. You have to download the module:
http://www.entrian.com/goto/


Haha! Sure. But have you seen how it's implemented? I don't think it
will win many performace prizes. Nifty hack though.

Cheers,
Carl.
Jan 20 '06 #10

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

Similar topics

68
5877
by: Lad | last post by:
Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.
82
4424
by: Edward Elliott | last post by:
This is just anecdotal, but I still find it interesting. Take it for what it's worth. I'm interested in hearing others' perspectives, just please don't turn this into a pissing contest. I'm in the process of converting some old perl programs to python. These programs use some network code and do a lot of list/dict data processing. The old ones work fine but are a pain to extend. After two conversions, the python versions are...
47
2181
by: John Salerno | last post by:
I have to say, I'm having a very enjoyable time learning and using Python. I spent a year playing around with C# and I feel like I learned/know less about it than I do about Python from just the past couple of months. Of course it's easier, but there's just something about it that makes me keep coming back to it and try to think of new ways to use it. Lately I've started to branch away from the "core" Python and I started learning...
1
2083
by: Petr Prikryl | last post by:
Do you think that the following could became PEP (pre PEP). Please, read it, comment it, reformulate it,... Abstract Introduction of the mechanism for language extensions via modules written using other languages. Extensions of Python could be done via special interpreter extensions. From Python sources, the special modules would look like other modules, with the Python API (the key feature from
0
8969
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
9335
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
9263
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
9208
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...
1
6751
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
6053
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
4570
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
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.