473,492 Members | 4,301 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

network programming without goto

Please help:

I was really blocked here. without goto I really do
not known how to do it.

The problem is to use PyZ3950 to consult a lists of
hosts and for each of them to search for a list of
targets. Since the network is undetermined, there were
always some exceptions: I would like to allow it to
retry for 3 times. Moreover, during the query process,
the conn will timeout (set by the remote server).
Reconnect is preferred before fail the current search,
but the reconnect may fail even if the first try is
succeed.
for host in hostlist:
try:
# sometimes the host may fail
conn =zoom.Connecton(host.ip, host.port)
except:
continue # Next host? But How to give it some
chance? 3 times?
...
reconnect = 0
for t in targets:
# ?
if reconnect:
# if conn timeout, reconnect
try:
# Fail??? 3 chances rules here?
conn = zoom.Connection(host.ip,
host.port)
except:
# ? Where should I go?
q = buildquery(t)
try: # Hay, any things can be broken
# and after some iteration, conn should
timeout
r = conn.search(q)
except:
reconnect = 1
#??? how to retry this t?

Jul 18 '05 #1
7 1235
In article <ma**************************************@python.o rg>,
kent sin <ke*****@yahoo.com> wrote:
Please help:

I was really blocked here. without goto I really do
not known how to do it.

The problem is to use PyZ3950 to consult a lists of
hosts and for each of them to search for a list of
targets. Since the network is undetermined, there were
always some exceptions: I would like to allow it to
retry for 3 times. Moreover, during the query process,
the conn will timeout (set by the remote server).
Reconnect is preferred before fail the current search,
but the reconnect may fail even if the first try is
succeed.

[spaghetti code deleted for brevity]

The real problem you've got is that you're trying to smash too much
stuff into one function. You've got several things going on here at
once. First, you're iterating over several hosts to try. Next, you're
making several attempts to connect to each host. Lastly, you've got
some buildquery()/search() stuff going on (whatever that may be). I'm
not at all sure what you're trying to do with "for t in targets", but
I'm going to assume it's somehow related to iterating over the various
hosts.

What you want to do is refactor this into a number of smaller functions,
each one encapsulating one piece of the puzzle. To start, I'd build a
function which handled the multiple connection attempts to a given host.
Maybe something like this:

#
# Untested code -- this is just to give you some ideas
# and get you thinking in the right direction
#
def connectWithRetries (host, port, retryLimit):
attempts = 0
while attempts < retryLimit:
try:
connection = zoom.Connection (host, port)
return connection
except ConnectionError:
attempts += 1
throw ConnectionError

Then, I'd handle the iteration over multiple hosts:

def connectToSomeHost (hostlist, port):
for host in hostlist:
try:
connection = connectWithRetries (host, port)
return connection
except ConnectionError:
# ignore
throw ConnectionError

Finally, It's time to implement your query logic, which I'll leave as an
exercise for the reader (mostly because I don't really understand what
you're trying to do with that).

None of this is network-specfic or even Python-specific. The idea of
breaking up a complex operation into smaller steps and implementing each
one in its own function is pretty much a universal idea. Each function
can be easily designed and tested on its own (and, later, understood by
a future reader).

The question then becomes, how to decide what stuff to put in what
function? There's no hard and fast rules, but the general idea is that
each function should do one thing, or a small set of very closely
related things. For example, I could imagine possibly combining
connectWithRetries() and connectToSomeHost into a single larger function
that did both tasks, because they're both part of the basic "get a
connection to a host" concept. But, getting the connection and using it
to perform a query definitely don't belong together.

Here's some rules of thumb:

Several smaller functions are usually better than one larger one.

If you can't see the entire function code without scrolling in your
editor, it's too big. With todays windowing systems, that probably
means about 40 lines.

If it's got more than a couple of loops, or more than a couple of try
blocks, you're probably doing too much in a single function.

If you can't explain to somebody in a single sentence what your function
is doing, it's doing too much.

The take-home assignment is to DAGS for "refactoring". There's been a
lot written on the subject in the last 5-10 years. A lot of what's been
written assumes an object oriented environment (in a C++ or Java like
language), but the basic concepts hold for all languages, and for
procedural as well as OO styles.
Jul 18 '05 #2
On Thu, 25 Nov 2004 06:53:53 -0800 (PST), kent sin <ke*****@yahoo.com>
wrote:

for host in hostlist:
try:
# sometimes the host may fail
conn =zoom.Connecton(host.ip, host.port)
except:
continue # Next host? But How to give it some
chance? 3 times?
...


Roy really posted the definitive answer here, but there is something else
you may find it interesting to try: recursive functions. I played around
with this for a random POV-Ray texture generator I made a while ago
(anyone interested? It's decent :) - nesting levels were somewhat
flexible, and I made the number of nesting levels in different sections
(texture maps, normal maps, etc.) randomised as well.

You do something like

***
def funnyWalk(stuff, NUMBER_OF_THIS_TRY, NESTING_LEVEL)
if NUMBER_OF_THIS_TRY > NESTING_LEVEL:
# We're done.
break # Is this valid??? I confuse pascal and python easily :(
NailParrotsFeet()
if NEED_ANOTHER_CALL == true:
funnyWalk(stuff,NUMBER_OF_THIS_TRY+1)

NESTINGLEVEL = 3
funnyWalk(stuff,1,NESTINGLEVEL)
***

And "NailParrotsFeet()" function will get run 3 times.

Jul 18 '05 #3
Roy Smith wrote:
What you want to do is refactor this into a number of smaller functions,
each one encapsulating one piece of the puzzle. To start, I'd build a
function which handled the multiple connection attempts to a given host.
Maybe something like this:

#
# Untested code -- this is just to give you some ideas
# and get you thinking in the right direction
#
def connectWithRetries (host, port, retryLimit):
attempts = 0
while attempts < retryLimit:
try:
connection = zoom.Connection (host, port)
return connection
except ConnectionError:
attempts += 1
throw ConnectionError


IMO, Roy's advice here is spot-on, with one minor technical detail. In
Python, exceptions use 'raise', not 'throw'...

Jeff Shannon
Technician/Programmer
Credit International
Jul 18 '05 #4
In article <10*************@corp.supernews.com>,
Jeff Shannon <je**@ccvcorp.com> wrote:
In Python, exceptions use 'raise', not 'throw'...


Doh! I guess it shows that I've been doing a lot of C++ lately :-)
Jul 18 '05 #5
Roy Smith wrote:
In article <10*************@corp.supernews.com>,
Jeff Shannon <je**@ccvcorp.com> wrote:

In Python, exceptions use 'raise', not 'throw'...

Doh! I guess it shows that I've been doing a lot of C++ lately :-)


Heh. I'm working on a Python test harness that uses a C++ hardware interface
module. I keep writing raise on the C++ side and throw on the Python side.

However, that's nothing compared to the amount of swearing regarding the
uselessness of C++ vectors as compared to Python lists. . .

Cheers,
Nick.
Jul 18 '05 #6
Nick Coghlan schrieb:
Roy Smith wrote:
Jeff Shannon <je**@ccvcorp.com> wrote:
In Python, exceptions use 'raise', not 'throw'...


Doh! I guess it shows that I've been doing a lot of C++ lately :-)


Heh. I'm working on a Python test harness that uses a C++ hardware
interface module. I keep writing raise on the C++ side and throw on the
Python side.

Isn't "throw something" a much more aggressive act than "raise
something", and might that help? But English isn't my native language so
I may be quite wrong.

--
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg

Tel.: (0821) 598-2400, Fax : (0821) 598-2410
e-mail : Si*************@Bibliothek.Uni-Augsburg.DE
Jul 18 '05 #7
On Mon, 29 Nov 2004 16:02:01 +0100, Sibylle Koczian
<Si*************@Bibliothek.Uni-Augsburg.de> declaimed the following in
comp.lang.python:
Isn't "throw something" a much more aggressive act than "raise
something", and might that help? But English isn't my native language so
I may be quite wrong.
Well... "throw" has the imagery that one it tossing it to a
known target, while "raise" is more "hey, I've got a problem here"...
<G>

So do we

raise cain

or

throw aFit

<G>

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #8

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

Similar topics

8
50521
by: Alex Ang | last post by:
I have written the following VBScript program. It is stored into a file "map_drive.vbs". It successfully mapped to a network drive \\server1\data. Dim WshNetwork Set WshNetwork =...
3
14844
by: Jay | last post by:
Hi, I implemeneted an FTP client and server long time back using Java. I found sockets porgramming in java quite useful and easy to handle. I now wanted to implement a similar program using C++....
16
660
by: John Baker | last post by:
HI; I feel like a fool..I put CUTE FTP in my last request for help --it should have been CUTE PDF! I have FTP on my mind because I have been working on a web based application, and somehow my...
134
7873
by: evolnet.regular | last post by:
I've been utilising C for lots of small and a few medium-sized personal projects over the course of the past decade, and I've realised lately just how little progress it's made since then. I've...
20
2910
by: JL | last post by:
I have a need to compute least cost formulations. This seems to be in the domain of "linear programming" of which I know practially nothing. Can anyone in the group give me a point in the right...
56
5665
by: valentin tihomirov | last post by:
{ int i = 2; } int i = 1; There is no 'i' defined in the 'parent' context from the moment of declaration on. So what is the problem? They tell us they pursue language simplicity. The rule "do...
9
2346
by: Mex | last post by:
Hi, I'm looking for a good book for beginners about Network Programming. Besides Stevens' book, I would like something specific for C++ language. Any suggestions? Thanks in advantage, Massimo
1
20543
by: Ryan Liu | last post by:
Hi, I have a 100 clients/ one server application, use ugly one thread pre client approach. And both side user sync I/O. I frequently see the error on server side(client side code is same, but...
43
3615
by: Adem24 | last post by:
The World Joint Programming Language Standardization Committe (WJPLSC) hereby proclaims to the people of the world that a new programming language is needed for the benefit of the whole mankind in...
0
7118
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
6980
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...
0
7157
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,...
1
6862
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...
0
5452
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,...
1
4886
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...
0
3078
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
282
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...

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.