Re: What's an elegant way to test for list index existing?

2018-09-29 Thread Glen D souza
i have a approach, it may not be best

fld = [ ]
for data in shlex.split(ln):
   fld.append(data)



On Sat, 29 Sep 2018 at 07:52,  wrote:

> On Friday, September 28, 2018 at 11:03:17 AM UTC-7, Chris Green wrote:
> > I have a list created by:-
> >
> > fld = shlex.split(ln)
> >
> > It may contain 3, 4 or 5 entries according to data read into ln.
> > What's the neatest way of setting the fourth and fifth entries to an
> > empty string if they don't (yet) exist? Using 'if len(fld) < 4:' feels
> > clumsy somehow.
>
> How about this?
>
> from itertools import chain, repeat
> temp = shlex.split(ln)
> fld = list(chain(temp, repeat("", 5-len(temp
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What's an elegant way to test for list index existing?

2018-09-29 Thread Glen D souza
fld = [ ]
data = shlex.split(ln)
for item in data:
   fld.append(item)
fld = fld + [0] * (5 - len(data))


On Sat, 29 Sep 2018 at 11:03, Glen D souza  wrote:

> i have a approach, it may not be best
>
> fld = [ ]
> for data in shlex.split(ln):
>fld.append(data)
>
>
>
> On Sat, 29 Sep 2018 at 07:52,  wrote:
>
>> On Friday, September 28, 2018 at 11:03:17 AM UTC-7, Chris Green wrote:
>> > I have a list created by:-
>> >
>> > fld = shlex.split(ln)
>> >
>> > It may contain 3, 4 or 5 entries according to data read into ln.
>> > What's the neatest way of setting the fourth and fifth entries to an
>> > empty string if they don't (yet) exist? Using 'if len(fld) < 4:' feels
>> > clumsy somehow.
>>
>> How about this?
>>
>> from itertools import chain, repeat
>> temp = shlex.split(ln)
>> fld = list(chain(temp, repeat("", 5-len(temp
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Several Topics - Nov. 19, 2013

2013-11-19 Thread glen herrmannsfeldt
In comp.lang.fortran Rainer Weikusat  wrote:
> glen herrmannsfeldt  writes:
>> In comp.lang.fortran E.D.G.  wrote:
>>>>> "E.D.G."  wrote in message 
>>>>> news:ro-dnch2dptbrhnpnz2dnuvz_rsdn...@earthlink.com...
>>> Posted by E.D.G. on November 19, 2013
  
>>> 1.  PERL PDL CALCULATION SPEED VERSUS PYTHON AND FORTRAN
  
 (snip)

>>>   This program translation project has become one of the most 
>>> surprisingly successful programming projects I have worked on to date.  A 
>>> considerable amount of valuable information has been sent to me by E-mail 
>>> in 
>>> addition to all of the information posted to the Newsgroups.

(snip, I wrote)

>> In general, language processors can be divided into two categories
>> called compilers and interpreters.  Compilers generate instructions for
>> the target processors. Interpreters generate (usually) an intermediate
>> representation which is then interpreted by a program to perform the
>> desired operations. That latter tends to be much slower, but more
>> portable.

>> There are a few langauges that allow dynamic generation of code, which
>> often makes compilation impossible, and those languages tend to be
>> called 'interpreted langauges'.
 
> These two paragraphs use the same terms in conflicting ways and the
> assertions in the second paragraph are wrong: Lisp is presumably the
> oldest language which allows 'dynamic code creation' and implementations
> exist which not only have a compiler but actually don't have an
> interpreter, cf
 
> http://www.sbcl.org/manual/index.html#Compiler_002donly-Implementation
 
> The main difference between a compiler and an interpreter is that the
> compiler performs lexical and semantical analysis of 'the source code'
> once and then transforms it into some kind of different 'directly
> executable representation' while an interpreter would analyze some part
> of the source code, execute it, analyze the next, execute that, and so
> forth, possibly performing lexical and semantical analysis steps many
> times for the same bit of 'source code'.

OK, but many intepreters at least do a syntax check on the whole file,
and many also convert the statements to a more convenient internal
representation.

For an example of something that can't be compiled, consider TeX which
allows the category code of characters to be changed dynamically.

I once wrote self-modifying code for Mathematica, where the running code
(on what Mathematica calls the back end) asked the front end (which does
editing of input data) to change the code. 
 
> Some compilers produce 'machine code' which can be executed directly by
> 'a CPU', others generate 'machine code' for some kind of virtual machine
> which is itself implemented as a program. The distinction isn't really
> clear-cut because some CPUs are designed to run 'machine code'
> originally targetted at a virtual machine, eg, what used to be ARM
> Jazelle for executing JVM byte code directly on an ARM CPU, some virtual
> machines are supposed to execute 'machine code' which used to run
> 'directly on a CPU' in former times, eg, used for backwards
> compatibility on Bull Novascale computers.

Yes. There are also systems that do simple processing on each statement,
with no interstatement memory. Converting numerical constants to
internal form, encoding keywords to a single byte, and such. 

It is interesting to see the program listing look different than the way
it was entered, such as constants coming out as 1e6 when you entered
it as 100.  The HP2000 BASIC system is the one I still remember.

The popular microcomputer BASIC systems, mostly from Microsoft, allowed
things like:

IF I=1 THEN FOR J=1 TO 10
PRINT J
IF I=1 THEN NEXT J

If you left out the IF on the last line, it would fail when it reached
the NEXT J statement if the FOR hadn't been executed. Compare to C:

if(i==1) for(j=1;j<=10;j++) {
   printf("%d\n",j);
}

A compiler would match up the FOR and NEXT at compile time. Many 
interpreters do it at run time, depending on the current state.

I also used to use a BASIC system that allowed you to stop a program
(or the program stopped itself), change statements (fix bugs) and
continue on from where it stopped. Not all can do that, but pretty
much compilers never do.
 
> Prior to execution, Perl source code is compiled to 'machine code' for a
> (stack-based) virtual machine. Both the compiler and the VM are provided
> by the perl program. There were some attempts to create a standalone
> Perl compiler in the past but these never gained much traction.

And, importantly, the code runs fairly slow. Some years ago, I was
working with simple PERL programs that could process data at 1 megabyte
per minute. Rewriting in C, I got one megabyte per second. It is not too
unusual to run 10 times slower, but 60 was rediculous.

-- glen
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Several Topics - Nov. 19, 2013

2013-11-19 Thread glen herrmannsfeldt
In comp.lang.fortran E.D.G.  wrote:
>>> "E.D.G."  wrote in message 
>>> news:ro-dnch2dptbrhnpnz2dnuvz_rsdn...@earthlink.com...
> Posted by E.D.G. on November 19, 2013
 
> 1.  PERL PDL CALCULATION SPEED VERSUS PYTHON AND FORTRAN
 
(snip)

>   This program translation project has become one of the most 
> surprisingly successful programming projects I have worked on to date.  A 
> considerable amount of valuable information has been sent to me by E-mail in 
> addition to all of the information posted to the Newsgroups.
 
>   The original posts actually discussed calculation speed matters 
> involving Perl and Python.  And responses indicated that there were ways to 
> develop routines that could dramatically accelerate Python calculations. 
> But it did not sound like there were any for Perl.

In general, language processors can be divided into two categories
called compilers and interpreters.  Compilers generate instructions for
the target processors. Interpreters generate (usually) an intermediate
representation which is then interpreted by a program to perform the
desired operations. That latter tends to be much slower, but more
portable.

There are a few langauges that allow dynamic generation of code, which
often makes compilation impossible, and those languages tend to be
called 'interpreted langauges'. 

Some years ago when working with perl programs that ran too slow, we
found a perl to C translator. Surprisingly, the result ran just as slow!
It turns out that the perl to C translator generates a C program
containing the intermediate code and the interpreter, and so runs just
the same speed.

More recently, there are JIT systems which generate the intermediate
code, but then at the appropriate time (Just In Time) compile that to
machine code and execute it. This is common for Java, and more recently
for languages like Matlab.

-- glen
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: struct calcsize discrepency?

2011-12-04 Thread Glen Rice
On Dec 4, 9:38 am, Duncan Booth  wrote:
> Glen Rice  wrote:
> > In IPython:
> >>import struct
> >>struct.calcsize('4s')
> > 4
> >>struct.calcsize('Q')
> > 8
> >>struct.calcsize('4sQ')
> > 16
>
> > This doesn't make sense to me.  Can anyone explain?
>
> When you mix different types in a struct there can be padding inserted
> between the items. In this case the 8 byte unsigned long long must always
> start on an 8 byte boundary so 4 padding bytes are inserted.
>
> Seehttp://docs.python.org/library/struct.html?highlight=struct#byte-order-
> size-and-alignment in particular the first sentence:
>
> "By default, C types are represented in the machine s native format and
> byte order, and properly aligned by skipping pad bytes if necessary
> (according to the rules used by the C compiler)."
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com

Chris / Duncan, Thanks. I missed that in the docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


struct calcsize discrepency?

2011-12-04 Thread Glen Rice
In IPython:
>import struct
>struct.calcsize('4s')
4
>struct.calcsize('Q')
8
>struct.calcsize('4sQ')
16

This doesn't make sense to me.  Can anyone explain?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/Fortran interoperability

2009-08-24 Thread glen herrmannsfeldt
In comp.lang.fortran n...@cam.ac.uk wrote:
(snip)
 
< Precisely.  And the kludge does NOT work under all circumstances,
< which is why I said that it doesn't work very well.
 
< Consider, for example:
 
<SUBROUTINE Fred (X) BIND(C)
<CHARACTER*(*) :: X
<END SUBROUTINE Fred
 
<CHARACTER(LEN=100) :: string
<CALL Fred(string(40:60))
<CALL Fred(string(5:50))
 
< This is not currently allowed and raises all sorts of 'interesting'
< implementation and portability questions.  For example, I defy anyone
< to write Fred portably in C :-)

You mean, how does FRED know the length?  It seems to me the
usual question for Fortran assumed size arrays.  Assuming that
FRED can tell from the passed string, it seems fine to me.
If not, it is a problem.  

Null terminated strings are a C convention, supported by
the library and compiler (string constants).  Others are legal C,
though you have to be careful which library routines you use.
 
< It gets really hairy if you have functions that have assumed length
< results, but those are obsolescent.
 
< Even when Fred has an explicit length, there are some problematic
< cases, which could catch out programmers in one language that don't
< know the other fairly well.  But those are much less of a problem
< than the common need for assumed length CHARACTER arguments.

Maybe Fortran programmers who started in Fortran 66 will not
have so much problem with this.  The usual way would be to
pass the length, as with assumed size arrays.  I believe terminating
strings with unusual (likely not null) characters was also done.

-- glen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric literal syntax

2008-09-09 Thread glen stark
On Tue, 09 Sep 2008 08:32:29 +1000, Tom Harris wrote:

> I agree. So did Forth's early designers. That is why Forth's number
> parser considers a word that starts with a number and has embedded
> punctuation to be a 32 bit integer, and simply ignores the punctuation.
> I haven't used Forth in years, but it seems a neat solution to the
> problem of decoding a long string of numbers: let the user put in
> whatever they want, the parser ignores it. I usually used a comma (with
> no surrounding whitespace of course), but it was your choice. You could
> also do this in whatever base you were working in, so you could
> punctuate a 32 bit hex number to correspond to the bit fields inside it.
> Of course not applicable to Python.


That sounds like a great idea, except I'd specify non-period (.) 
punctuation, so it would go for floating points as well.  

Is there a language design guru who can say why inputs like 123,456.00 
couldn't be handles as above?  the only problem I can see is an abiguity 
in argument lists (e.g. mult(2,4) ) which could be handled by the 
inclusion of whitespace.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What can we do about all the spam that the list is getting?

2008-04-18 Thread glen stark
On Thu, 17 Apr 2008 13:30:18 -0500, Grant Edwards wrote:

> When using Google Groups can one kill all posts made via Google Groups? 
> Presuming he has no burning need to see his own posts (something that
> can't be said for everybody in the history of Usenet), it might still be
> a viable approach.

The problem is, if we had followed that advice, none of us would have seen 
his post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lowercase class names, eg., qtgui ? (PyQt4)

2007-04-26 Thread Glen
On Thu, 26 Apr 2007 09:09:44 +0200, Tina I wrote:

Hi Tina,

Thanks for the reply.  Of course, by now I've run pyuic4 again on my .ui
file and things are back to normal.  Believe it or not, my example was a
copy/paste directly from my .py file.  Some strange anomoly, I guess. 
Everything's ok now.  Maybe vim was just displaying the text wrong for a
minute.  Had me going though.  

Thanks again.

Glen

> Are you sure? That's strange. I have never seen that. Here is a
snippet
> of one of my typical .py files generated by 'pyuic4':
> 
> self.gridlayout = QtGui.QGridLayout(self.centralwidget)
> self.gridlayout.setMargin(9)
> self.gridlayout.setSpacing(6)
> self.gridlayout.setObjectName("gridlayout")
> 
> self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0)
> self.hboxlayout.setSpacing(6)
> self.hboxlayout.setObjectName("hboxlayout")
> 
> self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0)
> self.hboxlayout1.setSpacing(6)
> self.hboxlayout1.setObjectName("hboxlayout1")
> 
> Upper case all the way...
> 
> Tina

-- 
http://mail.python.org/mailman/listinfo/python-list


lowercase class names, eg., qtgui ? (PyQt4)

2007-04-25 Thread Glen
Hello,

In the file generated by pyuic4 from Designer's .ui file I noticed the use
of lower case class names (I'm assuming these are the names of classes,
not modules).  For example:

It imports thusly:

from PyQt4 import QtGui

then uses things like:
self.gridlayout = qtgui.qgridlayout(dldialog)

What exactly is going on here?  Are these instances that are defined
somewhere else (their not in the local scope.)? Can I do the same in my
code when I import something?

Thanks,

Glen

Glen

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner: Simple Output to a Dialog PyQt4

2007-04-23 Thread Glen
On Sat, 21 Apr 2007 03:15:00 +0200, David Boddie wrote:

> On Tuesday 17 April 2007 07:42, Glen wrote:

> 
# Just to avoid any misunderstanding: the form is actually stored as XML.
# You can create C++ code with uic or Python code with pyuic4.
Right.  I do remember noticing that when I opened one of the .ui files.

Thanks for the instructions.  I'm tackling signals and slots next.  I'll
be reading your post a few times, I'm sure.  For the time being, just to
get myself off the ground and see some output, I imported my functions
from cnt.py into my main with 'from cnt import cnt'.  Then I passed my
QTextEdit object into my python code and output the contents of my file
with:
f = file("filename", 'r')
for line in f:
QTxtObj.insertPlainText(line)

Maybe you could point out some problems with doing it this way, but I'm at
the point now where I have to learn how to handle signals and slots.  I'm
setting up an input dialog with several options, such as download a URL,
choose an existing file.

Your information will come in handy.

Glen

>
>> [quoted text muted]
> 
> OK. Ideally, your window will contain a button (or some other control)
> that the user can click to execute the functions.
> 
>> [quoted text muted]
> 
> If, for example, you included a push button (QPushButton) in the form
> you created with Qt Designer, and called it executeButton, you could
> connect its clicked() signal to a function in cnt by including the
> following line after setting up the user interface:
> 
>   window.connect(ui.executeButton, SIGNAL("clicked()"), cnt.myFunction)
> 
> This assumes that your function is called myFunction(), of course.
> However, you wouldn't be able to get the output from this function back
> to the dialog just by using a signal-slot connection like this.
> 
> One way to solve this would be to wrap the function using another
> function or instance that is able to modify the contents of the dialog.
> Another cleaner approach would be to subclass the user interface class
> (Ui_Dialog) and implement a custom slot that can both call the function
> and modify the dialog.
> 
> For example:
> 
> class Dialog(QDialog, Ui_Dialog)
> 
> def __init__(self, parent = None):
> 
> QDialog.__init__(self, parent)
> self.setupUi(self)
> 
> self.connect(self.executeButton, SIGNAL("clicked()"),
>  self.callFunction)
> 
> def callFunction(self):
> 
> data = cnt.myFunction()
> # Do something with the data.
> 
> Hope this gets you started,
> 
> David

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner: Formatting text output (PyQt4) Solved

2007-04-23 Thread Glen
Sorry I've been away a while, figuring stuff out.  It absolutely wasn't a
monospaced font that I was using.  I'm still getting used to Qt Designer
and didn't see the expandable item under 'font' where I could easily
select another font.  I felt pretty stupid when I saw it.  My program
output the contents of my data file perfectly once I selected a fixed
pitch font.

Thanks a lot for the replies.  I didn't know how long to wait, since I'm
new around here, and I kind of gave up.  I got some good info from you
guys anyway.  Thanks.  You'll probably be hearing from me pretty
regularly, since I'm in the process of learning Python and PyQt
simultaneously.

Glen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner: Formatting text output (PyQt4)

2007-04-18 Thread Glen
On Wed, 18 Apr 2007 22:50:14 +, Glen wrote:

Ok, obviously, my post didn't come out the way I wanted it to.  In the
first example from my text file below, the dictionary pairs, constructed
from sorted tuples were in straight columns.  When I write them to my
QTextEdit, however, the columns are no longer straight.  Some of the
padding inserted by my call to rightJustified() are not equal to the
actual size of the text, so some rows are longer than others in the text
browser.  I know I've encountered this before, perhaps with Java, but I
can't remember the solution.  How do I get the formatting of my output to
the gui to reflect the output I would get to a file using the builtin
write() function?  Any help is appreciated.  Sorry about the confusion. 

Thanks,
G

> Hello again,  I don't blame anyone for not answering my last post,
since
> I obviously hadn't spent much time researching, but I've come a little
> ways and have another question.
> 
> How can I better format text output to a QTextEdit object?  I'm
> inserting 5 columns into each row.  When I write the info to a file, it
> looks like the following:
> 
> 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40:
> 106  5: 105 41: 104  2: 103
>  9: 102 48: 102 15: 101 22: 101 27: 101
> 39: 101 43: 101 10: 100  6:  99 34:  99 32:  98 49:
> 98 20:  97 30:  97  8:  96 17:  96 38:  96 12:  95
> 14:  95 37:  95
>  4:  94 13:  94 44:  94 36:  93  3:  92
> 24:  92 28:  92 31:  91 29:  89  7:  88
>  1:  87 18:  85 46:  85 33:  84 11:  83
> 23:  83 47:  82 25:  80 21:  79 50:  56 52:  39 51:
> 38 53:  36 54:  25 55:  18
> 
> When I write the contents of the file to my TextEdit object it comes out
> uneven, something like this:
> 42: 11526: 11435: 11219: 10816: 107 45: 10740: 106
> 5: 10541: 104 2: 103 9: 10248: 10215: 10122: 101 27:
> 101 39: 10143: 10110: 1006:  9934:  99 32:  9849: 98
>20:  9730:  978:  96 17:  9638:  9612:  9514: 95
>   37:  95 4:  9413:  9444:  9436:  933:  92 24:  92 28:
> 9231:  9129:  897:  88
>  1:  8718:  8546:  8533:  8411:  83
> 23:  8347:  8225:  8021:  7950:  56 52:  3951:  38
> 53:  3654:  2555:  18
> 
> What seems to be happening is that the font that pyqt is using is not
> fixed width, so I did this:
>   qTxtFormat = QTextCharFormat()
>   qTxtFormat.setFontFixedPitch(True)
>   ui.textEdit.setCurrentCharFormat(qTxtFormat)
> 
> Also, I tried using the pyqt formatting such as the following:
> 
>   qStr = QtCore.QString( QtCore.QString( str(tL2[i][0])
>   ).rightJustified(2) + ':' + QtCore.QString( str(tL2[i][1])
>   ).rightJustified(4) )
> This still gives me uneven columns.
> 
> Any suggestions?
> 
> Thanks,
> 
> Glen

-- 
http://mail.python.org/mailman/listinfo/python-list


Beginner: Formatting text output (PyQt4)

2007-04-18 Thread Glen
Hello again,  I don't blame anyone for not answering my last post, since I
obviously hadn't spent much time researching, but I've come a little ways
and have another question.

How can I better format text output to a QTextEdit object?  I'm inserting
5 columns into each row.  When I write the info to a file, it looks like
the following:

42: 115 26: 114 35: 112 19: 108 16: 107 
45: 107 40: 106  5: 105 41: 104  2: 103 
 9: 102 48: 102 15: 101 22: 101 27: 101 
39: 101 43: 101 10: 100  6:  99 34:  99 
32:  98 49:  98 20:  97 30:  97  8:  96 
17:  96 38:  96 12:  95 14:  95 37:  95 
 4:  94 13:  94 44:  94 36:  93  3:  92 
24:  92 28:  92 31:  91 29:  89  7:  88 
 1:  87 18:  85 46:  85 33:  84 11:  83 
23:  83 47:  82 25:  80 21:  79 50:  56 
52:  39 51:  38 53:  36 54:  25 55:  18 

When I write the contents of the file to my TextEdit object it comes out
uneven, something like this:
42: 11526: 11435: 11219: 10816: 107
45: 10740: 1065: 10541: 104 2: 103
9: 10248: 10215: 10122: 10127: 101
39: 10143: 10110: 1006:  9934:  99
32:  9849:  9820:  9730:  978:  96
17:  9638:  9612:  9514:  9537:  95
4:  9413:  9444:  9436:  933:  92
24:  9228:  9231:  9129:  897:  88
 1:  8718:  8546:  8533:  8411:  83
23:  8347:  8225:  8021:  7950:  56
52:  3951:  3853:  3654:  2555:  18  

What seems to be happening is that the font that pyqt is using is not
fixed width, so I did this:
qTxtFormat = QTextCharFormat()
qTxtFormat.setFontFixedPitch(True)
ui.textEdit.setCurrentCharFormat(qTxtFormat)

Also, I tried using the pyqt formatting such as the following:

qStr = QtCore.QString( QtCore.QString( str(tL2[i][0]) 
).rightJustified(2)
+ ':' + QtCore.QString( str(tL2[i][1]) ).rightJustified(4) )
This still gives me uneven columns.

Any suggestions?

Thanks,

Glen

-- 
http://mail.python.org/mailman/listinfo/python-list


Beginner: Simple Output to a Dialog PyQt4

2007-04-17 Thread Glen
Hello,
  I've written a script in python and put together a simple QFrame with a
  QTextBrowser with Designer.  I've translated the C++ into python using
  puic4.  The .py file is called outputWin.py.  My Script and its
  functions are in cnt.py.  Finally, my main is in pball.py which follows
  here:
import sys
from PyQt4 import Qt, QtCore 
from outputWin import *
from cnt import *
if __name__ == "__main__":
app = Qt.QApplication(sys.argv)
window = Qt.QDialog()
ui = Ui_Dialog()
ui.setupUi(window)
window.show()
app.exec_()

I want to call my functions in cnt and have an output to my QDialog.  Can
somebody give me a clue as to how to proceed?  I can't find good an easy
tutorial for PyQt4 and I've never used Qt before.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to static members from inside a method decorator?

2006-10-08 Thread glen . coates . bigworld
Peter Otten wrote:
> [EMAIL PROTECTED] wrote:
>
> You define one base type with a custom metaclass and inherit from that. Your
> example then becomes:
>
> import sys
>
> class ExposedType( type ):
> def __init__( cls, *args, **kw ):
> # Track marked exposed methods
> cls.s_exposedMethods = []
> for superclass in cls.__mro__:
> for name, meth in superclass.__dict__.items():
> if hasattr( meth, "exposed" ):
> cls.s_exposedMethods.append( name )
>
> class Exposed:
> __metaclass__ = ExposedType
> def getExposedMethods(self):
> return self.s_exposedMethods
> def bar(self):
> print "bar\n"
> @staticmethod
> def expose( f ):
> f.exposed = True
> return f
>
> class Process( Exposed):
> @Exposed.expose
> def foo( self ):
> pass
> def bar( self ):
> print "BAR"
>
>
> class BotProcess( Process ):
> @Exposed.expose
> def addBots( self ):
> pass
>
> p = Process()
> p.bar()
>
> This prints "BAR" as expected.
>
> Peter

Thanks Peter.  Yeah I had thought of that earlier, but wasn't sure if
this is a standard design pattern for what I'm trying to achieve.  It
seems ugly to me to use 2 classes when you are essentially describing a
single type.  Is the Splat/SplatType pairing really a common design
pattern when trying to use metaclasses in this way?

Also ... as for the 'inspect' based solution, yeah I can see that would
work, but it seems very hacky to me and my gut reaction is to avoid
that kind of thing ...

Cheers,
Glen

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to static members from inside a method decorator?

2006-10-05 Thread glen . coates . bigworld
Thanks for all the help guys ... in almost every way using a metaclass
seems to be the right solution for what I'm trying to do here.  I say
almost because there is one thing that is still confusing me: what is
the most elegant way to provide base-class implementations of methods
that are expected to be overriden by some of the derived classes (or in
the case of metaclasses, the classes that either declare __metaclass__
= Exposed or are derived from such classes).

Here's what I've just knocked out:

import sys

class Exposed( type ):

def __init__( cls, *args, **kw ):

# Track marked exposed methods
cls.s_exposedMethods = []
for superclass in cls.__mro__:
for name, meth in superclass.__dict__.items():
if hasattr( meth, "exposed" ):
cls.s_exposedMethods.append( name )

# Add getExposedMethods method
cls.getExposedMethods = lambda self: self.s_exposedMethods
cls.bar = lambda self: sys.stdout.write( "bar\n" )

@staticmethod
def expose( f ):
f.exposed = True
return f


class Process( object ):

__metaclass__ = Exposed

@Exposed.expose
def foo( self ):
pass


def bar( self ):
print "BAR"
pass


class BotProcess( Process ):

@Exposed.expose
def addBots( self ):
pass

p = Process()
p.bar()

#

The problem here is that the implementation of 'bar' inside
Exposed.__init__ overrides the implementation of bar() in Process,
which makes sense I guess seeing as Exposed.__init__() is called after
the class has been initialised.  It's not a problem for
getExposedMethods() seeing as it's not overriden by any derived
classes.

So what is the accepted way of doing this?  Do I need two Exposed
classes, one is the metaclass that handles all the static mapping
stuff, and another provides base implementations of methods and is what
is actually derived from? E.g.:

class ExposedMeta( type ):
  ...

class Exposed( object ):
  ...

class Process( Exposed ):
  __metaclass__ = ExposedMeta
  ...

class BotProcess( Process ):
  ...

Hmmm ... that seems a bit ugly too.  If I change the assignments in
Exposed.__init__() I guess I can avoid the two-class thing:

  cls.getExposedMethods = getattr( cls, "getExposedMethods", lambda
self: self.s_exposedMethods )
  cls.bar = getattr( cls, "bar", lambda self: sys.stdout.write( "bar\n"
) )

That's better, but still ugly.  Is there a better way?

Thanks for all the help thus far guys,
Glen

Maric Michaud wrote:
> Le jeudi 05 octobre 2006 17:18, [EMAIL PROTECTED] a écrit :
> > I guess my solution is slightly less elegant because
> > it requires this ugly explicit init call outside the classes that it
> > actually deals with, however it is more efficient because the dir()
> > pass happens once on module load, instead of every time I want the list
> > of exposed methods.
>
> You can always replace the need of the init method on classes using a
> metaclass.
>
> This demonstrates it with Bruno's expose decorator, but it can be done with
> your actual init func too.
>
> In [6]: class m(type) :
>...: def __init__(self, *a,**kw) :
>...: for name, meth in self.__dict__.items() :
>...: if getattr(meth, '_exposed', False) :
>...: print 'exposed :', name
>...:
>...:
>
> In [7]: class a(object):
>...: __metaclass__ = m
>...: def f(self) :pass
>...: @expose
>...: def g(self) :pass
>...:
>...:
> exposed : g
>
> In [8]: class b(a) :
>...: @expose
>...: def h(self) :pass
>...:
>...:
> exposed : h
>
>
>
>
> --
> _
>
> Maric Michaud
> _
>
> Aristote - www.aristote.info
> 3 place des tapis
> 69004 Lyon
> Tel: +33 426 880 097

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to static members from inside a method decorator?

2006-10-05 Thread glen . coates . bigworld
Bruno Desthuilliers wrote:
> [EMAIL PROTECTED] wrote:
> > I'm developing a library at the moment that involves many classes, some
> > of which have "exposed" capabilities.  I'm trying to design a nice
> > interface for both exposing those capabilities, and inspecting
> > instances to find out what capabilities they have.
> >
> > At the moment, I'm leaning towards a superclass (Exposed) that defines
> > a static method which is a decorator (expose) such that any derived
> > class can mark a method with @Exposed.expose and it will then be later
> > returned by getExposedMethods(), a la:
> >
> > class Exposed:
> >   @staticmethod
> >   def expose( f ):
> > ...
> >
> >   def getExposedMethods( self ):
> > ...
> >
> > class Person( Exposed ):
> >   @Exposed.expose
> >   def talk( self, ... ):
> > ...
> >
> > I'm trying to implement the decorator by having it populate a static
> > member list of whatever class it's in with a reference to the method.
> > getExposedMethods() would then return the contents of each of those
> > lists from itself back to Exposed in the class hierarchy.  The first
> > problem was that having a reference to the method (i.e. talk()) does
> > not allow you to get a reference to the enclosing class (I had hoped
> > im_class would lead me there).
>
> Not yet. When your decorator is called, the class object is not yet
> created, and what you are decorating is a plain function.
>
> > The real hiccup was that explicitly
> > passing the class as an argument to the decorator generates a undefined
> > global name error, presumably because at that point of execution the
> > class object hasn't been fully created/initialised.
>
> Exactly.
>
> > So how can this be done?
>
> The simplest thing is to use a two-stages scheme : mark the functions as
> exposed, then collect them:
>
> def expose(func):
>   func._exposed = True
>   return func
>
> def exposed(obj):
>   return callable(obj) and getattr(obj, '_exposed', False)
>
> class Exposing(object):
>   @classmethod
>   def get_exposed_methods(cls):
> try:
>   exposeds = cls._exposed_methods
> except AttributeError:
>   exposeds = []
>   for name in dir(cls):
> obj = getattr(cls, name)
> if exposed(obj):
>   exposeds.append(obj)
>   cls._exposed_methods = exposeds
> return exposeds
>
> class Parrot(Exposing):
>   @expose
>   def parrot(self, what):
> return "%s says %s" % (self, str(what))
>
>
>
> HTH
> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"

Thanks Bruno.  I came up with a similar solution today at work, which
involves an 'init' method which is called at the bottom of each module
that defines subclasses of Exposed and sets up static mappings for the
exposed methods.  I guess my solution is slightly less elegant because
it requires this ugly explicit init call outside the classes that it
actually deals with, however it is more efficient because the dir()
pass happens once on module load, instead of every time I want the list
of exposed methods.

Thanks for the help though,
Glen

-- 
http://mail.python.org/mailman/listinfo/python-list


Access to static members from inside a method decorator?

2006-10-04 Thread glen . coates . bigworld
I'm developing a library at the moment that involves many classes, some
of which have "exposed" capabilities.  I'm trying to design a nice
interface for both exposing those capabilities, and inspecting
instances to find out what capabilities they have.

At the moment, I'm leaning towards a superclass (Exposed) that defines
a static method which is a decorator (expose) such that any derived
class can mark a method with @Exposed.expose and it will then be later
returned by getExposedMethods(), a la:

class Exposed:
  @staticmethod
  def expose( f ):
...

  def getExposedMethods( self ):
...

class Person( Exposed ):
  @Exposed.expose
  def talk( self, ... ):
...

I'm trying to implement the decorator by having it populate a static
member list of whatever class it's in with a reference to the method.
getExposedMethods() would then return the contents of each of those
lists from itself back to Exposed in the class hierarchy.  The first
problem was that having a reference to the method (i.e. talk()) does
not allow you to get a reference to the enclosing class (I had hoped
im_class would lead me there).  The real hiccup was that explicitly
passing the class as an argument to the decorator generates a undefined
global name error, presumably because at that point of execution the
class object hasn't been fully created/initialised.

So how can this be done?  It doesn't seem like it's possible to pass a
reference to the enclosing class into the decorator, which in turn
means that static tracking of the list of exposed methods is impossible
(at least, if I want to use decorators).

Any ideas that will enable my initial design, or suggestions for an
elegant, workable alternative would be much appreciated.

Cheers,
Glen

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detect TKinter window being closed?

2005-12-02 Thread Glen
Thanks Fredrik and Adonis that's just what I needed, plus a bit more to
learn about.

-- 
http://mail.python.org/mailman/listinfo/python-list


Detect TKinter window being closed?

2005-12-02 Thread Glen
Is it possible to to detect a Tkinter top-level window being closed with the
close icon/button (top right), for example to call a function before the
window actually closes?

Python 2.4 / Linux (2.6 kernel) if that makes any difference.
Any info would be greatly appreciated.
Thanks
Glen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to stop a linux process

2005-11-28 Thread Glen
Simon Brunning wrote:

> The subprocess module might be worth a look.

That looks about right for what I need (once I understand it!).
Thanks very much.

-- 
http://mail.python.org/mailman/listinfo/python-list


How to stop a linux process

2005-11-28 Thread Glen
When I used the following line to play a midi file in linux,

return_value = os.system('timidity test.mid')

I have encountered two problems.
1. The python script halts until timidity has finished.
2. If I had control of the script, I can't think how I would stop timidity.

Any advice on the 'area' of python I should be looking at would be greatly
appreciated.

Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newb: Telnet 'cooked data','EOF' queries

2005-08-01 Thread glen
> > Could someone explain what "cooked data" is.
> discussed in the telnet RFC, which is in RFC854 telnetlib docstring.
> "Cooked" data is data after these special sequences are removed.
>
>>'when' is an EOF received.
> the only EOF in telnet is when the other side closes the socket.

Thanks, thats got me started.
-- 
http://mail.python.org/mailman/listinfo/python-list


Newb: Telnet 'cooked data','EOF' queries.

2005-07-31 Thread glen
While experimenting with telnetlib, Ive come across a couple of 
'features' that confuse me a little (lot!).
Could someone explain what "cooked data" is.
Also when trying read_all() the program seems to lock up, which I assume 
is because it is waiting for an EOF, but 'when' is an EOF received.
Glen
-- 
http://mail.python.org/mailman/listinfo/python-list


Begniner Question

2005-03-21 Thread Glen
#!/usr/local/bin/python

import sys

print "1.\tDo Something"
print "2.\tDo Something"
print "3.\tDo Something"
print "4.\tDo Something"
print "5.\tDo Something"
print "6.\tExit"

choice=raw_input("Please Enter Choice: ")

if int(choice)==1:
   print "Here"
else:
   pass

if int(choice)==2:
else:
   pass

if int(choice)==3:
else:
   pass

if int(choice)==4:
else:
   pass

if int(choice)==5:
else:
   pass

if int(choice)==6:
   sys.exit(0)
else:
   pass

File "./Code.py", line 20
   else:
  ^
IndentationError: expeted an indented block

What am I doing wrong?

Thank-you


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused updating 2.3 to 2.4 on Linux

2004-12-17 Thread Glen
> > Being a new'ish user to both Linux and Python, I've been 'happily'
> > learning Python (2.3) with Idle and Tkinter as installed with Mandrake
> > 10.
> > All seemed to work without any errors, but starting Python from Idle
> > or a console displays the same statup text,
> >
> > Python 2.3.3 (#2, Feb 17 2004, 11:45:40)
> > [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2
> >
> > 'which python' shows /usr/bin/python, and this file has not been updated
> >
> > Is there something else I should do?
> 
> The default install location for python is /usr/local, not /usr. You
> can change your PATH so that /usr/local/bin precedes /usr/bin, and
> then you'll get the new Python.
> 
> BTW, installing a new python doesn't "completely replace" the old
> python on Unix systems. Python installs everything but one file in
> directories that include the version number, so that people (mostly
> developers) can keep multiple versions around with no problem. The one
> exception is bin/python, which is a hard link to the last python you
> installed.
> 
> If you look, you'll find /usr/lib/python2.3, /usr/include/python2.3,
> /usr/local/lib/python2.4, /usr/local/include/python2.4,
> /usr/bin/python2.3, /usr/local/bin/python2.3, /usr/bin/python (the
> same as /usr/bin/python2.3) and /usr/local/bin/python (which is the
> same as /usr/local/bin/python2.4).
> 
> If you want, you can rebuild python with:
> 
>./configure --prefix=/usr
>make install
> 
> and it will put the directories in parallel with the old ones, instead
> of putting them in /usr/local.
> 
>http://mail.python.org/mailman/listinfo/python-list


Confused updating 2.3 to 2.4 on Linux

2004-12-17 Thread Glen
Being a new'ish user to both Linux and Python, I've been 'happily'
learning Python (2.3) with Idle and Tkinter as installed with Mandrake
10.
Thought I would try installing Python 2.4 (to completely replace 2.3)
(first time I've tried installing anything from source)

Followed the readme file (all done from my 'home' directory),

tar -zxvf Python-2.4.tgz
./configure
make
make test (2 skips unexpected on linux2:test_bz2 test_gdbm)
make install

Although I wasn't sure about some of the directory references, 
'type "./configure" in the current directory'
'type "make" in the toplevel directory'.

All seemed to work without any errors, but starting Python from Idle
or a console displays the same statup text,

Python 2.3.3 (#2, Feb 17 2004, 11:45:40)
[GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2

'which python' shows /usr/bin/python, and this file has not been updated

Is there something else I should do?
Also 'IF' I get 2.4 working, will Tkinter/Idle need any additional
installation work, or is it all done through the Python 2.4 installation

-- 
http://mail.python.org/mailman/listinfo/python-list