473,806 Members | 2,735 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

concise code (beginner)

I have about 30 pages (10 * 3 pages each) of code like this
(following). Can anyone suggest a more compact way to
code the exception handling? If there is an exception, I need
to continue the loop, and continue the list.

Steve.

-----------------------------------
for dev in devs
try:
dev.read1()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read2()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read3()
except
print exception
remove dev from devs

etc.
Sep 5 '07 #1
22 1281
bambam wrote:
I have about 30 pages (10 * 3 pages each) of code like this
(following). Can anyone suggest a more compact way to
code the exception handling? If there is an exception, I need
to continue the loop, and continue the list.

Steve.

-----------------------------------
for dev in devs
try:
dev.read1()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read2()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read3()
except
print exception
remove dev from devs
for method in (DevClass.read1 , DevClass.read2, ...):
for dev in devs:
try:
method(dev)
except:
print execption
remove dev from devs

Diez
Sep 5 '07 #2
Try adding all the functions into a list such as;

funcList = [dev.read1, dev.read2, dev.read3]

for func in funcList:
for dev in devs:
try:
func()
except:
print exception
remove dev from devs

Wes.

On 05/09/07, bambam <da***@asdf.asd fwrote:
I have about 30 pages (10 * 3 pages each) of code like this
(following). Can anyone suggest a more compact way to
code the exception handling? If there is an exception, I need
to continue the loop, and continue the list.

Steve.

-----------------------------------
for dev in devs
try:
dev.read1()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read2()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read3()
except
print exception
remove dev from devs

etc.
--
http://mail.python.org/mailman/listinfo/python-list
Sep 5 '07 #3
bambam a écrit :
I have about 30 pages (10 * 3 pages each) of code like this
(following). Can anyone suggest a more compact way to
code the exception handling? If there is an exception, I need
to continue the loop, and continue the list.

Steve.

-----------------------------------
for dev in devs
try:
dev.read1()
except
print exception
remove dev from devs

for method_name in ['read1', 'read2', 'read3']:
for dev in devs:
try:
meth = getattr(dev, method_name)
except AttributeError, e:
# should not happen, but we want to handle it anyway
your_code_here( )
else:
try:
meth()
except (SomePossibleEx ception, SomeOtherPossib leException), e:
print e
# do what's needed to remove dev from devs
# paying attention not to screw the looping machinery...

(snip)
Sep 5 '07 #4
Sorry, just seen a mistake in my code, however Diez beat me to what I
was actually thinking!

Wes

On 05/09/07, Wesley Brooks <we*******@gmai l.comwrote:
Try adding all the functions into a list such as;

funcList = [dev.read1, dev.read2, dev.read3]

for func in funcList:
for dev in devs:
try:
func()
except:
print exception
remove dev from devs

Wes.

On 05/09/07, bambam <da***@asdf.asd fwrote:
I have about 30 pages (10 * 3 pages each) of code like this
(following). Can anyone suggest a more compact way to
code the exception handling? If there is an exception, I need
to continue the loop, and continue the list.

Steve.

-----------------------------------
for dev in devs
try:
dev.read1()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read2()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read3()
except
print exception
remove dev from devs

etc.
--
http://mail.python.org/mailman/listinfo/python-list
Sep 5 '07 #5
First, thank you.

All of the suggestions match what we want to do much better
than what we are doing. We have a script, written in python,
which is doing testing. But the python script doesn't look anything
like the test script, because the python script is written in python,
and the test script is a series of instrument command macros.

By putting the script sequence into a collection that is separate
from the python code, we will get script list that general engineering
will find much easier to understand:
def script(self)
def a0010(): global self; self.power_on([self.dev]);
def a0020(): global self; self.dev.addLog ([self.name, ' started']);
def a0030(): global self; self.resetMinut eReg([self.dev]);
def a0040(): global self; self.disablePLm essages([self.dev]);
def a0050(): global self; self.dev.testH. writePLram((PL. BCAL12<<8));

Most of these won't generate exceptions: exceptions are expected
only on the calculations following the reads, but of course the
problem is that the exceptions are unexpected... The semi-colons
were already there, I've just stripped out the loops and exception
handlers. The original code is a mixture of functions with internal
and external [dev] loops.

Because of the sequence names, I have a choice of using generated
call names (James), or a static list of some sort.

Other possibilities might be
1) Using dir(script) to get a list of line functions
2) Using frame.f_lineno instead of line functions
3) Use an expression list instead of line functions
4) Multiple script objects with yield on each line.

The devices are in a list, and are removed by using pop(i). This
messes up the loop iteration, so it is actually done by setting a
flag on each device in the exception handler, with ANOTHER
loop after each write/read/calculate sequence. I left that out also
because I wanted to show the intended logic.

I'm not wedded to the idea of using sequence numbers for
line functions. Comments are welcome. Sorry I didn't include
this level of detail in the original, but I am interested in the
question at all levels.

Note that this achieves synchronous parallel processing --
another area I know nothing about -- but I'm just starting
with the code as I got it, and coding so far was focused
on hardware integration.

Steve.

"bambam" <da***@asdf.asd fwrote in message
news:13******** *****@corp.supe rnews.com...
>I have about 30 pages (10 * 3 pages each) of code like this
(following). Can anyone suggest a more compact way to
code the exception handling? If there is an exception, I need
to continue the loop, and continue the list.

Steve.

-----------------------------------
for dev in devs
try:
dev.read1()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read2()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read3()
except
print exception
remove dev from devs

etc.

Sep 6 '07 #6
On Thu, 06 Sep 2007 15:44:57 +1000, bambam wrote:
def script(self)
def a0010(): global self; self.power_on([self.dev]);
def a0020(): global self; self.dev.addLog ([self.name, ' started']);
def a0030(): global self; self.resetMinut eReg([self.dev]);
def a0040(): global self; self.disablePLm essages([self.dev]);
def a0050(): global self; self.dev.testH. writePLram((PL. BCAL12<<8));
What is this ``global self`` meant to do? And the first line is missing a
colon at the end.

Ciao,
Marc 'BlackJack' Rintsch
Sep 6 '07 #7
On Thu, 06 Sep 2007 15:44:57 +1000, bambam wrote:
First, thank you.

All of the suggestions match what we want to do much better than what we
are doing. We have a script, written in python, which is doing testing.
But the python script doesn't look anything like the test script,
because the python script is written in python, and the test script is a
series of instrument command macros.

By putting the script sequence into a collection that is separate from
the python code, we will get script list that general engineering will
find much easier to understand:
def script(self)
def a0010(): global self; self.power_on([self.dev]);
def a0020(): global self; self.dev.addLog ([self.name, ' started']);
def a0030(): global self; self.resetMinut eReg([self.dev]);
def a0040(): global self; self.disablePLm essages([self.dev]);
def a0050(): global self; self.dev.testH. writePLram((PL. BCAL12<<8));
That's rather hideous code, and I'm not sure I understand what it's
supposed to do. As far as I can tell, you have a function called "script"
which takes a single argument. It then defines five functions, throws
them away, and returns None.

"self" is not a reserved word in Python (although perhaps it should
be...) but it has a VERY strong convention for when to use it: when
defining instance methods, it is used for the automatically-supplied
instance argument. The above functions look like they were written by
somebody who has just copied some methods from another piece of code
without understanding what they were seeing. (Sorry.)

Most of these won't generate exceptions: exceptions are expected only on
the calculations following the reads, but of course the problem is that
the exceptions are unexpected...
I don't think so. I think they are expected. You say so yourself.

The semi-colons were already there,
Fine. Time to remove them.

I've just stripped out the loops and exception handlers. The original
code is a mixture of functions with internal and external [dev] loops.

Because of the sequence names, I have a choice of using generated call
names (James), or a static list of some sort.

Other possibilities might be
1) Using dir(script) to get a list of line functions 2) Using
frame.f_lineno instead of line functions 3) Use an expression list
instead of line functions 4) Multiple script objects with yield on each
line.
My brain hurts.

The devices are in a list, and are removed by using pop(i). This messes
up the loop iteration, so it is actually done by setting a flag on each
device in the exception handler, with ANOTHER loop after each
write/read/calculate sequence. I left that out also because I wanted to
show the intended logic.
Try something like this: define a module holding the device functions.
Rather than have the functions access a global variable, which is almost
always a bad thing to do, have them take a single argument.

# module device

__all__ = [a0010, a002, a0030, a0040, a0050]

def a0010(obj):
obj.power_on([obj.dev])
def a0020(obj):
obj.dev.addLog([obj.name, ' started'])
def a0030(obj):
obj.resetMinute Reg([obj.dev])
def a0040(obj):
obj.disablePLme ssages([obj.dev])
def a0050(obj):
obj.dev.testH.w ritePLram((PL.B CAL12<<8))
Now define a second module to call those functions.

# module tester

import device
passed = device.__all__[:] # a copy of the list
some_object = Something() # I have no idea what this should be...

for function in device.__all__:
try:
function(some_o bject)
except Exception, e:
print e
passed.remove(f unction)

print "The following functions passed:"
for function in passed:
print function
And then I suggest you spend some time reading up about doc tests and
unit tests.

Hope this helps,

--
Steven.

Sep 6 '07 #8
Hi Steven.

Looking at your code, why are you naming the value
__all__? It looks like a built-in variable?

Unless there is an automatic way to correctly get the
function list, I will probably be better off giving the lines
sequence numbers, and generating the function list from
that.

Steve.

"Steven D'Aprano" <st***@REMOVE-THIS-cybersource.com .auwrote in message
news:13******** *****@corp.supe rnews.com...
On Thu, 06 Sep 2007 15:44:57 +1000,
"bambam" <da***@asdf.asd fwrote in message
news:13******** *****@corp.supe rnews.com...
>
Try something like this: define a module holding the device functions.

# module script

__all__ = [a0010, a002, a0030, a0040, a0050]
....
# module test1
import script
class Test1(pl_test.P l_test)
"""ADC calibration and Battery Voltage calibration"""
def run(self,devlis t):
for line in script.__all__:
for self.dev in devlist
if self.dev.active and not self.dev.failed
try
line(self)
except Exception,e:
print e
self.dev.active =False

print "The following devices passed:"
for dev in devlist
if dev.active and not dev.failed
print dev

print "The following devices need to be re-tested"
for dev in devlist
if not dev.active
print dev

print "The remaining devices failed"
for dev in delist
if dev.active and dev.failed
print dev
--
Steven.

Sep 7 '07 #9
On Fri, 07 Sep 2007 12:03:26 +1000, bambam wrote:
Hi Steven.

Looking at your code, why are you naming the value __all__? It looks
like a built-in variable?
When you say:

from module import *

Python looks in the module for a list of names called "__all__", and
imports only the names in that list. It is recommended that your modules
take advantage of that feature. I'm just using the same name.

Unless there is an automatic way to correctly get the function list, I
will probably be better off giving the lines sequence numbers, and
generating the function list from that.
I don't understand what you mean by "giving the lines sequence numbers".
Where do they come from? How do you go from sequence numbers to functions?

As far as I am concerned, the right behavior is for the module containing
the functions to define which functions need to be tested. Since modules
aren't actually intelligent, that means some person needs to list the
functions. Why list the function NAME when you can list the function
itself?

Sep 7 '07 #10

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

Similar topics

5
3083
by: Richard B. Kreckel | last post by:
Hi! I was recently asked what book to recommend for a beginner in C++. I am convinced that you needn't study C in depth before learning C++ (though it helps), but cannot find any beginner's book which isn't aimed at people coming from C/Pascal/Java/Delpi/whatever... However, there seem to be plenty such books for all those other languages. Is there really no literature for people trying to learn programming by starting with C++? ...
8
2383
by: Grrrbau | last post by:
I'm a beginner. I'm looking for a good C++ book. Someone told me about Lafore's "Object-Oriented Programming in C++". What do you think? Grrrbau
7
2946
by: Rensjuh | last post by:
Hello, does someone have / know a good C++ tutorial for beginnners? I would prefer Dutch, but English is also fine. Hoi, heeft / kent iemand nog een goede C++ tutorial voor beginners? Het liefste in Nederlands, maar Engels is ook goed. Thnx, Rensjuh
2
2504
by: Dean Arnold | last post by:
I checked the 7.4 PL/pgSQL docs but couldn't find a concise grammar description e.g. a BNF diagram...is any such thing available online ? I'm looking to possibly port a stored procedure debugger I'm writing to support Pg. (I'd prefer *not* to wade thru a lex/yacc definition) TIA, Dean Arnold Presicient Corp.
3
1720
by: kim | last post by:
Does anyone know of concise c# & .NET study materials...like all the keywords in one place, etc?
2
1404
by: mark4asp | last post by:
Hello, I am converting an app from JavaScript to ASP.NET I have the following JavaScript 'associative array'. Is there a concise way to create an analogous structure in .NET Framework using c# or VB.NET? I don't want to use JScript. consFin = {2:'m',4:'n',6:'ng',8:'r',10:'l',12:'kh',14:'k',16:'s',18:'hl',19:'tl',20:'s
43
1636
by: chookeater | last post by:
Hi All. My introduction to VB was through VB.Net but I am working with a lot of code that was written by programmers with pre-dotnet experience. As a result there are lots of function calls and "non-OOP aware" code. Is there any program available that I can get to sweep through VB.Net projects and flag these older VB functions/things ? I don't want to have to learn pre-dotnet VB to just to know what I
18
2931
by: mitchellpal | last post by:
Hi guys, am learning c as a beginner language and am finding it rough especially with pointers and data files. What do you think, am i being too pessimistic or thats how it happens for a beginner? Are there better languages than c for a beginner? For instance visual basic or i should just keep the confidence of improving?
4
16077
by: Kurien Mathew | last post by:
Hello, What will be a concise & efficient way to convert a list/array.array of n elements into a hex string? For e.g. given the bytes I would like the formatted string 0x74 0x6f 0x6e 0x67 0x6b 0x61 Is there an approach better than below: hex = ''
0
10624
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
10111
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
9193
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...
1
7650
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
6877
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
5546
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
5684
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4330
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
3
3010
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.