Re: win32 shell extension (virtual drive)
Tiziano Bettio <[EMAIL PROTECTED]> wrote: > >I'm looking for a simple solution of a win32 shell extension (virtual >drive). > >It should make available a new drive with letter, which will be >read-only. Instead of a network drive or similar it then should query a >server application for directory/file listing. Creating a new virtual folder with a shell extension is easy. Creating a new drive letter requires that you write a file system driver, something that (A) must be written in C, (B) requires the expensive "installable file system kit" from Microsoft, and (C) no human being really wants to do. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: will it cause any problems to open a read-only file & not close it?
Sara Khalatbari <[EMAIL PROTECTED]> wrote: >Dear friends >In a code, I'm opening a file to read. Like : >lines = open(filename).readlines() >& I'm never closing it. >I'm not writing in that file, I just read it. > >Will it cause any problems if you open a file to read >& never close it? A file is closed when the last reference to it is deleted. Since you never save a reference to this file, the last reference is deleted as soon as the readlines() call finishes. So, the file will be closed when you move to the next statement. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why tuple with one item is no tuple
Gregor Horvath wrote: thanks are given to all "problem" solved... Personally I add a , after every list/tuple item. Also the last. It also makes copy/pasting code easier. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: SAX parsing problem
anon <[EMAIL PROTECTED]> writes: > So I've encountered a strange behavior that I'm hoping someone can fill > me in on. i've written a simple handler that works with one small > exception, when the parser encounters a line with '&' in it, it > only returns the portion that follows the occurence. > > For example, parsing a file with the line : > mykeysome%20&%20value > > results in getting "%20value" back from the characters method, rather > than "some%20&%20value". > > After looking into this a bit, I found that SAX supports entities and > that it is probably believing the & to be an entity and processing > it in some way that i'm unware of. I'm using the default > EntityResolver. Are you sure you're not actually getting three chunks: "some%20", "&", and "%20value"? The xml.sax.handler.ContentHandler.characters method (which I presume you're using for SAX, as you don't mention!) is not guaranteed to get all contiguous character data in one call. Also check if .skippedEntity() methods are firing. -- |>|\/|< /--\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca -- http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
Jacob Lee wrote: On Tue, 15 Mar 2005 21:38:48 -0800, Michael Spencer wrote: string.translate is a good idea. Note you can handle upper-casing and translation in one operation by adding a mapping from lower case to the complement i.e., table = string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDM\nKNSYAAWBRTGVHCDMKNSYAAWBR') Good call. This looks unwieldy - especially writing to sys.stdout oe character at a time. I may not have understood the spec exactly, but isn't this the same as: for line in sys.stdin: if line and (line[0] == ">" or line[0] == ";"): print line else: print line.translate(table) That's the immediately obvious solution, but it doesn't actually fulfill the problem requirements. What if your last line is less than 60 characters long? You no longer will be displaying the input in reverse order. Otherwise you'd be right - my solution would be unnecessarily unwieldy (and the problem would be much simpler...) . yes it would be, wouldn't it ;-) How about this then: basetable = string.maketrans('ACBDGHKMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR') from collections import deque from itertools import islice def output(seq, linelength = 60): if seq: iterseq = iter(seq) while iterseq: print "".join(islice(iterseq,linelength)) def revcomp(input = sys.stdin): seqlines = deque() for line in input: if line[0] in ">;": output(seqlines) print line, seqlines.clear() else: seqlines.extendleft(line.translate(basetable, "\n\r")) output(seqlines) It would be nice to inline the output function, and re-arrange the iteration so that EOF triggers the same suite as line[0] in ">;" Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
On Tue, 15 Mar 2005 03:21:48 -0800, Paul Boddie wrote: > Well, I've been using Python for almost ten years, and I've managed to > deliberately ignore descriptors and metaclasses quite successfully. I get > the impression that descriptors in particular are a detail of the > low-level implementation that get a disproportionate level of coverage > because of the "hack value" they can provide (albeit with seemingly > inappropriate application to certain problem areas). I kept playing with descriptors, and tearing them out of production code, but I finally figured out how to "think" of them, I think. You want to create a descriptor for a type of "property()" that you keep using over and over again. If it's a one-off, use a property and be done with it. If you find yourself writing the same property over and over again, having access to the descriptor itself lets you factor it out so you can write it Once and Only Once (IMHO the highest of all programming laws^H^H^H^H^H rules of thumb). I went a long time before I came up with a use case for that, but now I have one where I want an attribute to fire an event in a particular manner every time it is changed. Rather than write a read function and a write function for each attribute (or try to hack it with closures or other arcane enchantments), it was easy to pack it up as a descriptor. It's a little too large to just copy and paste, but the upshot is that I can use it just like this: class Whatever(object): name = EmitOnChange("nameChange", "_name") and that will fire a "nameChange" event into my event system every time someone modifies "name", and the "real" value is stored in _name. (Obviously, I use it more than this once in the real code.) This may not be the best way to look at it from the C point of view, but I think it's a good way to look at it from the Python point of view. It probably is pretty rare that you need this, but it's there. -- http://mail.python.org/mailman/listinfo/python-list
Re: Jython Phone Interview Advice
On Tue, 15 Mar 2005 03:21:19 -0800, George Jempty wrote: > I'm noticing that Javascript's array/"hash" literal syntax is EXACTLY the > same as that for Python lists/dictionaries. No it isn't, quite. Two differences of note, one literally syntax and one technically not but you probably still want to know about it. First, Javascript objects can only use strings for keys, anything used as a key will be converted to a string. Try this in your browser and you'll see what I mean... the "instance" of the "class" I define (let's not get into prototyping issues here :-) ) has its string value used as the key, not the object: javascript:function a(){}; a.prototype.toString = function () {return 'q';}; b = new a(); c = {}; c[b] = 1; alert(c['q']) (All one line, if your browser objects to the newline.) The other is the syntax point: The strings you use in {} expressions to denote keys are used literally, they are not resolved. Thus, in the above I *had* to write c = {}; c[b] = 1; Because had I written c = {b: 1} I would have ended up with an object where c['b'] == 1; Javascript does not resolve the "expression", 'cause it isn't one. (That said, certain reserved words like "class" and such do have to be quoted, which means the safe bet is to quote them all, which leads to Javascript objects that look identical to Python dicts. But {1+2: "moo"} will end up different in each language.} Danger danger danger! -- http://mail.python.org/mailman/listinfo/python-list
Re: __getitem__ method on (meta)classes
In article <[EMAIL PROTECTED]>, Steven Bethard <[EMAIL PROTECTED]> wrote: > > Yeah, except I actually left out one thing: I also want type(v)==e1. > > Why? In Python usually you rely on duck-typing and not explicit type > checks. What is it that you're trying to gain by asserting type(v) == e1? Clarity. I want to be able to distinguish a member of an enumeration from a string or an integer for the same reason one would want to distinguish 123 from "123". rg -- http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
Jacob Lee wrote: So here's a tentative contest version of the code: import sys import string def show(seq, table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDM\nKNSYAAWBRTGVHCDMKNSYAAWBR')): seq = seq.translate(table)[::-1] for i in range(0, len(seq), 60): print seq[i:i+60] def main(): seq = [] for line in sys.stdin: if line[0] in ';>': show(''.join(seq)) print line, del seq[:] else: seq.append(line[:-1]) show(''.join(seq)) main() Looks pretty good. (And yes, I definitely prefer the unaliased ''.join and seq.append for readability's sake. Glad to know they try to grade on that too.) =) Only one other suggestion: "range" in the show function should probably be "xrange". "range" is going to create an actual list of however many integers, while "xrange" will just create the integers as needed. "xrange" thus will be more memory friendly. (It's also occasionally faster, though this depends a lot on the rest of the code). STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: error sending path to Win OS
Earl Eiland <[EMAIL PROTECTED]> wrote: > >A couple of you commented that I should be using os.path.join. >Accordingly, I rewrote my code. Unfortunately, I still have the same >problem. the following code snippet > >Results.SetOriginal(os.path.getsize(os.path.join(InputDirectory , x))) >y = str(x.split('.')[0]) + '.rk' >print InputDirectory, y >raw_input() >Results.SetArchive(os.path.getsize(os.path.join(InputDirectory, y))) > >is executed from the command line with >C:\Documents and Settings\eeiland\Desktop> ..\Thesis\Plan2\Compressor.py >Test_Data\ Test_Output\Results >Test_Data\ Book1.rk, where InputDirectory (in the above snippet) = >'Test_Data\' (I've also tried 'Test_Data', with the same results). > >x (in the above snippet) is an element of the list generated by >os.listdir(InputDirectory). > >Output upon execution is as follows: >Test_Data\ Book1.rk > >Traceback (most recent call last): > File "C:\Documents and Settings\eeiland\Thesis\Plan2\Compressor.py", >line 60, >in ? >Results.SetArchive(os.path.getsize(os.path.join(InputDirectory, y))) > File "C:\Python24\lib\ntpath.py", line 229, in getsize >return os.stat(filename).st_size >OSError: [Errno 2] No such file or directory: 'Test_Data\\Book1.rk' > >What am I doing wrong? My guess would be that Test_Data\Book1.rk does not exist from the point of view of the directory where the script is running this. You might do this: print os.getcwd() os.system('dir ' + InputDirectory) just to prove that you are where you think you are. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
On Tue, 15 Mar 2005 22:45:48 -0700, Steven Bethard wrote: > # table as default argument value so you don't have to do > # a global lookup each time it's used > > def show(seq, table=string.maketrans('ACBDGHK\nMNSRUTWVY', > 'TGVHCDM\nKNSYAAWBR') > seq = seq.upper().translate(table)[::-1] > # print string in slices of length 60 > for i in range(0, len(seq), 60): > print seq[i:i+60] > > def main(): > seq = [] > # alias methods to avoid repeated lookup > join = ''.join > append = seq.append > for line in sys.stdin: > # note only one "line[0]" by using "in" test > if line[0] in ';>': > # note no need to check if seq is empty; show now prints > # nothing for an empty string > show(join(seq)) > print line, > del seq[:] > else: > append(line[:-1]) > Wow - that ran about 10 times faster on a 10MB input file. The significant change was the for loop inside the show function: your method avoids the increment and if statement and of course has 60x fewer iterations total. > reversed() won't save you any memory -- you're already loading the > entire string into memory anyway. > > > Interesting tidbit: > del seq[:] > tests faster than > seq = [] > > $ python -m timeit -s "lst = range(1000)" "lst = []" > 1000 loops, best of 3: 0.159 usec per loop > > $ python -m timeit -s "lst = range(1000)" "del lst[:]" > 1000 loops, best of 3: 0.134 usec per loop > > It's probably the right way to go in this case anyway -- no need to > create a new empty list each time. Fascinating - I hadn't thought about that. Besides redoing that loop, the remaining optimizations produce less than a 10% speed-up; in particular, adding the function aliases increases the number of lines of code (another benchmark in the shootout), and I would imagine that the organizers don't really want that type of special optimization (no developer is going to write that in their programs unless they have really time-critical code, so this is the sort of hit that Python really should take in the contest as penalty for being so dynamically nifty ;)). So here's a tentative contest version of the code: import sys import string def show(seq, table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDM\nKNSYAAWBRTGVHCDMKNSYAAWBR')): seq = seq.translate(table)[::-1] for i in range(0, len(seq), 60): print seq[i:i+60] def main(): seq = [] for line in sys.stdin: if line[0] in ';>': show(''.join(seq)) print line, del seq[:] else: seq.append(line[:-1]) show(''.join(seq)) main() -- Jacob Lee [EMAIL PROTECTED] | www.nearestneighbor.net -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
jrlen balane <[EMAIL PROTECTED]> wrote: >why is it that here: > >1)rx_data = ser.read(10) >(rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, >pyra2, voltage, current, rx_checksum) = unpack('10B', rx_data) >print rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, >pyra2, voltage, current, rx_checksum > type (rx_command) > > >but here: > >2)rx_data_command = ser.read() >(rx_command) = unpack('1B', rx_data_command) > type (rx_command) > > >how can i make rx_command of type 'int' if i am to use 2)? Did you get an answer to this? I couldn't see any responses. The answer is either: rx_command = unpack('1B', rx_data_command)[0] or (rx_command,) = unpack('1B', rx_data_command) -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
On Tue, 15 Mar 2005 21:38:48 -0800, Michael Spencer wrote: > string.translate is a good idea. Note you can handle upper-casing and > translation in one operation by adding a mapping from lower case to the > complement i.e., > > table = string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', > 'TGVHCDM\nKNSYAAWBRTGVHCDMKNSYAAWBR') > Good call. > This looks unwieldy - especially writing to sys.stdout oe character at a > time. I may not have understood the spec exactly, but isn't this the > same as: > > for line in sys.stdin: > if line and (line[0] == ">" or line[0] == ";"): > print line > else: > print line.translate(table) > > That's the immediately obvious solution, but it doesn't actually fulfill the problem requirements. What if your last line is less than 60 characters long? You no longer will be displaying the input in reverse order. Otherwise you'd be right - my solution would be unnecessarily unwieldy (and the problem would be much simpler...) . -- Jacob Lee [EMAIL PROTECTED] | www.nearestneighbor.net -- http://mail.python.org/mailman/listinfo/python-list
Re: how to read a tab delimited file
> Peter Hansen wrote: > >>jrlen balane wrote: >> >>>how would i read a tab delimited file? at the same time put what i >>>read in an array, say for example that i know that the file is an >>>array with column= 5 and row=unknown. >> >>Use the "csv" module. Although that stands for "comma >>separated values", it readily supports alternative >>delimiters such as TAB. jrlen balane top-posted: if i am going to do this, how should i continue: how would i know the end of file? Look at the examples in the docs: http://docs.python.org/lib/node617.html STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: how to read a tab delimited file
if i am going to do this, how should i continue: how would i know the end of file? table_data = open(filename, 'r') table_data.readlines() On Tue, 15 Mar 2005 23:37:50 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote: > jrlen balane wrote: > > how would i read a tab delimited file? at the same time put what i > > read in an array, say for example that i know that the file is an > > array with column= 5 and row=unknown. > > Use the "csv" module. Although that stands for "comma > separated values", it readily supports alternative > delimiters such as TAB. > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
Jacob Lee wrote: There are a bunch of new tests up at shootout.alioth.debian.org for which Python does not yet have code. I've taken a crack at one of them, a task to print the reverse complement of a gene transcription. Since there are a lot of minds on this newsgroup that are much better at optimization than I, I'm posting the code I came up with to see if anyone sees any opportunities for substantial improvement. Without further ado: table = string.maketrans('ACBDGHK\nMNSRUTWVY', 'TGVHCDM\nKNSYAAWBR') def show(s): i = 0 for char in s.upper().translate(table)[::-1]: if i == 60: print i = 0 sys.stdout.write(char) i += 1 print def main(): seq = '' for line in sys.stdin: if line[0] == '>' or line[0] == ';': if seq != '': show(seq) seq = '' print line, else: seq += line[:-1] show(seq) main() Don't know if this is faster for your data, but I think you could also write this as (untested): # table as default argument value so you don't have to do # a global lookup each time it's used def show(seq, table=string.maketrans('ACBDGHK\nMNSRUTWVY', 'TGVHCDM\nKNSYAAWBR') seq = seq.upper().translate(table)[::-1] # print string in slices of length 60 for i in range(0, len(seq), 60): print seq[i:i+60] def main(): seq = [] # alias methods to avoid repeated lookup join = ''.join append = seq.append for line in sys.stdin: # note only one "line[0]" by using "in" test if line[0] in ';>': # note no need to check if seq is empty; show now prints # nothing for an empty string show(join(seq)) print line, del seq[:] else: append(line[:-1]) Making seq into a list instead of a string (and using .extend instead of the + operator) didn't give any speed improvements. Neither did using a dictionary instead of the translate function, or using reversed() instead of s[::-1]. The latter surprised me, since I would have guessed using an iterator to be more efficient. Since the shootout also tests memory usage, should I be using reversed for that reason? reversed() won't save you any memory -- you're already loading the entire string into memory anyway. Interesting tidbit: del seq[:] tests faster than seq = [] $ python -m timeit -s "lst = range(1000)" "lst = []" 1000 loops, best of 3: 0.159 usec per loop $ python -m timeit -s "lst = range(1000)" "del lst[:]" 1000 loops, best of 3: 0.134 usec per loop It's probably the right way to go in this case anyway -- no need to create a new empty list each time. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
Here's my solution to the problem[1]: [1] http://shootout.alioth.debian.org/benchmark.php?test=revcomp import sys import string basetable = string.maketrans('ACBDGHKMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR') def revcomp(seqlines, linelength=60, basetable=basetable): seq = ''.join(seqlines) complement = seq.translate(basetable) revcomplement = complement[::-1] for i in xrange(0, len(revcomplement), linelength): print revcomplement[i:i+linelength] def main(): seqlines = [] for line in sys.stdin: if line.startswith('>') or line.startswith(';'): if seqlines: revcomp(seqlines) sys.stdout.write(line) seqlines = [] else: seqlines.append(line.strip()) revcomp(seqlines) if __name__ == '__main__': main() -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
Jacob Lee wrote: There are a bunch of new tests up at shootout.alioth.debian.org for which Python does not yet have code. I've taken a crack at one of them, a task to print the reverse complement of a gene transcription. Since there are a lot of minds on this newsgroup that are much better at optimization than I, I'm posting the code I came up with to see if anyone sees any opportunities for substantial improvement. Without further ado: table = string.maketrans('ACBDGHK\nMNSRUTWVY', 'TGVHCDM\nKNSYAAWBR') string.translate is a good idea. Note you can handle upper-casing and translation in one operation by adding a mapping from lower case to the complement i.e., table = string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDM\nKNSYAAWBRTGVHCDMKNSYAAWBR') def show(s): i = 0 for char in s.upper().translate(table)[::-1]: if i == 60: print i = 0 sys.stdout.write(char) i += 1 print def main(): seq = '' for line in sys.stdin: if line[0] == '>' or line[0] == ';': if seq != '': show(seq) seq = '' print line, else: seq += line[:-1] show(seq) main() This looks unwieldy - especially writing to sys.stdout oe character at a time. I may not have understood the spec exactly, but isn't this the same as: for line in sys.stdin: if line and (line[0] == ">" or line[0] == ";"): print line else: print line.translate(table) HTH Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Thomas Bellman wrote: Torsten Bronger <[EMAIL PROTECTED]> wrote: Just to amplify Thomas' statements... ... And inflexibility will always make some situations horribly daunting to get out of. Powerful constructs like these can, in some cases, enable a skilled package writer to design an API that reduces the amount of boiler plate code needed for using the package. ... The following is from the (draft of) my paper for my pycon presentation (upcoming). We see similar patterns throughout the class-type redesign, the introduction of the __new__ method which allowed for “hooking” the creation (as distinct from initialization) of an object, the __getattribute__ method for hooking all attribute access. In each case, the operations were previously “part of the interpreter” and unavailable for customization by the Python programmer, the protocols generalized the behavior, making objects themselves responsible for what was previously implemented by the interpreter, and thus was always exactly the same. That sameness was arguably a strong advantage for Python in the early days of its life-cycle. When you were handed an object (particularly, any object defined by a class), it had simple, predictable behavior. The (one) class implementation was straightforward enough that most new users didn't particularly get lost in it. Of course, the flip side was the presence of “types”, which could behave very differently, and the need for people who wanted to customize the core behavior of an object (for instance to change how attribute traversal was handled) to write C extensions. And then there was the strange exception for attribute access for functions, but that was so natural and practical it seldom bit anyone who wasn't doing meta-programming. Effectively, there were a few bits of “magic” that the Python programmer needed to understand, but the variety and complexity of the magical patterns was limited. The magic incantations could be learned readily by the acolyte, but there was a hard cap on what could be done without becoming a “wizard” and programming in C. The limits on functionality made Python a smaller and less complex language, but it also tended to frustrate the “wizards”, who, after all, might know C, but would rather either program in Python (or spend more of their time looking at really deep C, rather than creating yet another customization to support something just beyond the reach of the acolytes). So, with Python 2.2, the wizards of Python made it possible to override and customize the behavior of objects in ways that were previously impossible. They brought things that were previously “magic” (for example, the order of attribute lookup that somehow created bound instance methods) into the realm of the understandable by rationalizing the process. metaclasses and descriptors are primarily of interest to metaprogrammers, people whose target audience is other programmers. Most programmers can get along perfectly fine ignoring them save for knowing what the particular ones they *use* do. Metaprogramming is not *necessarily* a *dark* art, but it can certainly lead the way to darkness if done improperly or wantonly. When done properly, you can build systems that seem to perfectly map a problem domain into the familiar embrace of everyday Python with just the right "lived in" touches to make it seem as though the language was designed from the start to support that domain [leaving aside any questions of syntactic variants, which is its own involved debate]. When you have metaprogramming to do, it is *such* a relief when you can get it done in Python without resorting to C. Have fun all, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com PyCon is coming... -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Debug logging
gf gf wrote: Is there a simple way to log to a debug console in Python? Don't know exactly what you want, but you should check out the logging module: http://docs.python.org/lib/minimal-example.html STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Turning String into Numerical Equation
Giovanni Bajo wrote: When __builtin__ is not the standard __builtin__, Python is in restricted execution mode. Do you know where this is documented? I looked around, but couldn't find anything. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
Jacob Lee wrote: By the way - is there a good way to find out the maximum memory a program used (in the manner of the "time" command)? Other than downloading and running the shootout benchmark scripts, of course. Inserting appropriate pauses with raw_input() and recording the memory usage using top(1) is a quick and dirty way. -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Turning String into Numerical Equation
Giovanni Bajo wrote: Steven Bethard wrote: I use something along these lines: def safe_eval(expr, symbols={}): return eval(expr, dict(__builtins__=None, True=True, False=False), symbols) import math def calc(expr): return safe_eval(expr, vars(math)) That offers only notional security: >>> calc("acos.__class__.__bases__[0]") Yeah, I was concerned about the same thing, but I realized that I can't actually access any of the func_globals attributes: Interesting, of course I had never actually tried it When __builtin__ is not the standard __builtin__, Python is in restricted execution mode. After a little experimenting, it appears to be a bit stronger than that. Once a frame is set for restricted execution (f_restricted == 1), then even if you set f_globals['__builtin__'] = __builtins__, you are still left in resticted execution mode. In fact, I believe my solution to be totally safe, That's a bold claim! I'll readily concede that I can't access func_globals from restricted mode eval (others may know better). But your interpreter is still be vulnerable to DOS-style attack from rogue calculations or quasi-infinite loops. > otherwise would love to be proved wrong. Michael -- http://mail.python.org/mailman/listinfo/python-list
code for Computer Language Shootout
There are a bunch of new tests up at shootout.alioth.debian.org for which Python does not yet have code. I've taken a crack at one of them, a task to print the reverse complement of a gene transcription. Since there are a lot of minds on this newsgroup that are much better at optimization than I, I'm posting the code I came up with to see if anyone sees any opportunities for substantial improvement. Without further ado: table = string.maketrans('ACBDGHK\nMNSRUTWVY', 'TGVHCDM\nKNSYAAWBR') def show(s): i = 0 for char in s.upper().translate(table)[::-1]: if i == 60: print i = 0 sys.stdout.write(char) i += 1 print def main(): seq = '' for line in sys.stdin: if line[0] == '>' or line[0] == ';': if seq != '': show(seq) seq = '' print line, else: seq += line[:-1] show(seq) main() Making seq into a list instead of a string (and using .extend instead of the + operator) didn't give any speed improvements. Neither did using a dictionary instead of the translate function, or using reversed() instead of s[::-1]. The latter surprised me, since I would have guessed using an iterator to be more efficient. Since the shootout also tests memory usage, should I be using reversed for that reason? Does anyone have any other ideas to optimize this code? By the way - is there a good way to find out the maximum memory a program used (in the manner of the "time" command)? Other than downloading and running the shootout benchmark scripts, of course. -- Jacob Lee [EMAIL PROTECTED] | www.nearestneighbor.net -- http://mail.python.org/mailman/listinfo/python-list
Re: RotatingFileHandler and logging config file
Rob Cranfill wrote: Kent Johnson wrote: It is in the latest docs. No, it isn't. (But thanks for replying anyway!) Can you prove it isn't? ;-) http://docs.python.org/lib/logging-config-fileformat.html has all the others (OK, maybe not all, I haven't thoroughly checked, but it's got nine of 'em) but nothing for RFH. Or is that not "the latest docs"? Sure, but it's not the only place to look in the current docs. Try here instead: http://docs.python.org/lib/node332.html The missing piece of the puzzle might be the connection between the 'args' in the config file and the arguments passed to the __init__ method of the class -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: how to read a tab delimited file
jrlen balane wrote: how would i read a tab delimited file? at the same time put what i read in an array, say for example that i know that the file is an array with column= 5 and row=unknown. Use the "csv" module. Although that stands for "comma separated values", it readily supports alternative delimiters such as TAB. -Peter -- http://mail.python.org/mailman/listinfo/python-list
SAX parsing problem
So I've encountered a strange behavior that I'm hoping someone can fill me in on. i've written a simple handler that works with one small exception, when the parser encounters a line with '&' in it, it only returns the portion that follows the occurence. For example, parsing a file with the line : mykeysome%20&%20value results in getting "%20value" back from the characters method, rather than "some%20&%20value". After looking into this a bit, I found that SAX supports entities and that it is probably believing the & to be an entity and processing it in some way that i'm unware of. I'm using the default EntityResolver. Any help/info would be much appreciated. gh -- http://mail.python.org/mailman/listinfo/python-list
how to read a tab delimited file
how would i read a tab delimited file? at the same time put what i read in an array, say for example that i know that the file is an array with column= 5 and row=unknown. -- http://mail.python.org/mailman/listinfo/python-list
Re: RotatingFileHandler and logging config file
Kent Johnson wrote: It is in the latest docs. Kent No, it isn't. (But thanks for replying anyway!) http://docs.python.org/lib/logging-config-fileformat.html has all the others (OK, maybe not all, I haven't thoroughly checked, but it's got nine of 'em) but nothing for RFH. Or is that not "the latest docs"? - rob -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode converting
Maxim Kasimov wrote: Diez B. Roggisch wrote: Maxim Kasimov wrote: there are a few questions i can find answer in manual: 1. how to define which is internal encoding of python unicode strings (UTF-8, UTF-16 ...) It shouldn't be your concern - but you can specify it using " ./configure --enable-unicode=ucs2" or --enable-unicode=ucs4. You can't set it to utf-8 or utf-16. is that means that python internal unicode format is ucs2 or ucs4? i'm concerning with the qustion because i need to send data to external application in ucs2 encoding The internal format Python stores Unicode strings in is an implementation detail; it has nothing to do with how you send data. To do that, you encode your string into a suitable encoding: >>> s = u"Some Unicode text." >>> s u'Some Unicode text.' >>> s.encode('utf-16') '\xff\xfeS\x00o\x00m\x00e\x00 \x00U\x00n\x00i\x00c\x00o\x00d\x00e\x00 \x00t\x00e\x00x\x00t\x00.\x00' -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Torsten Bronger wrote: HallÃchen! [EMAIL PROTECTED] (Paul Boddie) writes: Torsten Bronger <[EMAIL PROTECTED]> wrote: At first, I was very pleased by Python's syntax (and still I am). Then, after two weeks, I learned about descriptors and metaclasses and such and understood nothing (for the first time in syntax I felt totally lost). Well, I've been using Python for almost ten years, and I've managed to deliberately ignore descriptors and metaclasses quite successfully. I get the impression that descriptors in particular are a detail of the low-level implementation that get a disproportionate level of coverage because of the "hack value" they can provide (albeit with seemingly inappropriate application to certain problem areas). I have exactly the same impression, but for me it's the reason why I feel uncomfortable with them. For example, I fear that a skilled package writer could create a module with surprising behaviour by using the magic of these constructs. I don't know Python well enough to get more specific, but flexibility almost always make confusing situations for non-hackers possible. In that case I wouldn't worry about the magic which can be done in python but the magic which can be done in C (which many modules are written in). Sometimes I think people complain just to complain. I know that such magic is inavoidable with dynamic languages, but There's always a but. descriptors will be used almost exclusively for properties, and therefore I think it would have been better to hard-wire properties in the interpreter rather than pollute the language with this sort of proto-properties (aka descriptors). Have you heard of java ? maybe you'll like groovy. TeX is extremely dynamic. It can modify its own scanner in order to become an XML parser or AFM (Adobe font metrics) reader. This is highly confusing for all but those five or six people on this planet who speak TeX fluently. Since I saw raw TeX, I dislike "proto-syntaxes" (or meta-syntaxes if you wish). Now you're talking about extremes Huy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Debug logging
gf gf wrote: Is there a simple way to log to a debug console in Python? In .NET, you can Debug.Write(str), which does nothing if there is no debug console open, but, if there is, debugs the message. Is there something similar? Alternatively, is there a very simple log4j type setup? I emphasize very simple, since, for me, having to go through all the log4j xml configuration defeats the purpose of coding quickly in python anyway... I'm looking for something along the lines of log4p(DEBUG, str) and then just a one line config somewhere log4p.DEBUG=stderr or =/dev/null Anything like this? Try googling for "python logging". YOu can try search this newsgroup as well. It's the least you can do before posting. Huy -- http://mail.python.org/mailman/listinfo/python-list
Python Debug logging
Is there a simple way to log to a debug console in Python? In .NET, you can Debug.Write(str), which does nothing if there is no debug console open, but, if there is, debugs the message. Is there something similar? Alternatively, is there a very simple log4j type setup? I emphasize very simple, since, for me, having to go through all the log4j xml configuration defeats the purpose of coding quickly in python anyway... I'm looking for something along the lines of log4p(DEBUG, str) and then just a one line config somewhere log4p.DEBUG=stderr or =/dev/null Anything like this? Thanks PS Please cc me on all responses, muchos gracias __ Do you Yahoo!? Make Yahoo! your home page http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumping an instance
gf gf wrote: If I want to dump (for debugging) an instance and all of it's member attributes, what's the simplest way? print myInstance just gives a pointer to its location in memory Roughly speaking, as a starting point: from pprint import pformat def dump(obj): print repr(obj) for name in obj.__dict__: val = getattr(obj, name) print name, '=', pformat(val) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass structures using a C extension?
Jaime Wyant wrote: > You need to check out swig. It is the *only* way to setup a `c' > library for use with python. It's not. Regards, Yevgen -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumping an instance
In article <[EMAIL PROTECTED]>, gf gf <[EMAIL PROTECTED]> wrote: > If I want to dump (for debugging) an instance and all > of it's member attributes, what's the simplest way? > > print myInstance > > just gives a pointer to its location in memory You need to write a str() method for the class. Alternatively, take a look at the pprint module. -- http://mail.python.org/mailman/listinfo/python-list
Dumping an instance
If I want to dump (for debugging) an instance and all of it's member attributes, what's the simplest way? print myInstance just gives a pointer to its location in memory Thanks! __ Do you Yahoo!? Yahoo! Mail - 250MB free storage. Do more. Manage less. http://info.mail.yahoo.com/mail_250 -- http://mail.python.org/mailman/listinfo/python-list
Re: Minidom empty script element bug
Martin v. Löwis wrote: > Derek Basch wrote: > > XHTML 1.0 specs, Appendix C > > [EMAIL PROTECTED] > > C.3 Element Minimization and Empty Element Content > > > > Given an empty instance of an element whose content model is not EMPTY (for > > example, an empty title or paragraph) do not use the minimized form (e.g. > > use and not ) > > [EMAIL PROTECTED] > > I'd like to point out that this is *not* a minidom bug. minidom cannot > possibly know that the document type is XHTML, and that strange, non-XML > rules apply to XHTML (i.e. rules which are not present in XML itself). > > I'd also like to point out that XHTML Appendix C is informative (i.e. > non-normative), meaning that failure to comply to it does not imply > non-compliance with XHTML. An XML file which uses the minimized form > for the script element is still proper, well-formed, valid XHTML. > > > How do I get minidom to NOT render an empty script element? Should I submit a > > bug report? > > That said, I think there is a simple solution: add an empty Text node > to the script element: > > script_node_0.appendChild(doc.createText(u"")) > > [Disclaimer: this is untested; from reading the source, I think it > should work] > > Regards, > Martin Thanks Martin. That fixed it. I had to change your code a bit to this: script_node_0.appendChild(self.doc.createTextNode("")) maybe you meant createTextNode? I started digging through the dom modules on this path: XHTMLPrettyPrint -> XHTMLPrinter -> Printer and found this comment: try: #The following stanza courtesy Martin von Loewis import codecs # Python 1.6+ only from types import UnicodeType So I guess you are pretty qualified to answer my question! You are correct that this is not a minidom bug now that I think about it. However, it seems proper that XHTMLPrinter (or some other module) should allow the developer to use either normative or non-normative XHTML design guidlines to achieve some sane degree of HTML user agent compatablilty. Maybe something like this in Printer.py: def visitElement(self, node): ... if len(node.childNodes): self._write('>') self._depth = self._depth + 1 self.visitNodeList(node.childNodes) self._depth = self._depth - 1 if not self._html or (node.tagName not in HTML_FORBIDDEN_END): not (self._inText and inline) and self._tryIndent() self._write('' % node.tagName) elif not self._html and node.tagName not in XHTML_NON_NORMATIVES: self._write('/>') elif node.tagName not in HTML_FORBIDDEN_END: self._write('>' % node.tagName) else: self._write('>') of course this would only take care of the "C.3. Element Minimization and Empty Element Content" guideline but you get the general idea. Anyways, thanks for the help again and feel free to shoot down my suggestions :) Derek Basch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Bruno Desthuilliers wrote: Valentino Volonghi aka Dialtone a écrit : Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: It is actually. Ruby's syntax is mostly consistent and coherent, and there is much less special cases than in Python. I'd be glad to know which special cases are you referring to. A few examples: - A statement is different from an expression (2 special cases instead of one general case). You do know that Ruby may well get this special case as well. At least they know a good thing when they see it. I'm not sure why this is a problem in any case. Huy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Bruno Desthuilliers wrote: news.sydney.pipenetworks.com a Ãcrit : I looked for a new language for my hobby programming. I used to use Turbo Pascal for 10 years and then C++ for 6 years. A couple of weeks ago, I narrowed my decision to C#, Ruby, and Python. At the moment, I want to go with Python, but you can definitely see that it's the oldest one: Many parts of its syntax are awkward and look like patchwork. You mean you think Ruby syntax is less awkward then Python ? It is actually. Ruby's syntax is mostly consistent and coherent, and there is much less special cases than in Python. Really, well I must be wrong. Each to his own opinion then. Now it's also much more difficult to grasp Ruby for programmers coming from procedural languages, but that's another story. So being more consistent and coherent means being more complex ? I'm glad python worried about the complex part before the consistent and conherent part. Maybe you should add Perl to your list of languages to learn especially after your complaints about the decorator syntax. I guess you stopped your exploration of Ruby at the first sign of 'special chars' syntax. well not really. I stopped when it started to look to much like perl. I hate too much punctuation in syntax. I quite like the @ in ruby better then the self in python though, but at the end of the day, i don't really care that much whether it's an @ or a self. I don't like Perl, I still prefer to use Python (over Ruby) for a number of good and less good reasons, but I somewhat share Fernando's (and some other's people here) concerns about the future of MyFavoriteLanguage. Fair enough. It seems many people want to trade places with the BDFL. I don't. May his god bless him ;-) Huy -- http://mail.python.org/mailman/listinfo/python-list
Re: Turning String into Numerical Equation
Steven Bethard wrote: >>> I use something along these lines: >>> >>> def safe_eval(expr, symbols={}): >>> return eval(expr, dict(__builtins__=None, True=True, >>> False=False), symbols) >>> >>> import math >>> def calc(expr): >>> return safe_eval(expr, vars(math)) >>> >> That offers only notional security: >> >> >>> calc("acos.__class__.__bases__[0]") >> > > Yeah, I was concerned about the same thing, but I realized that I > can't actually access any of the func_globals attributes: When __builtin__ is not the standard __builtin__, Python is in restricted execution mode. In fact, I believe my solution to be totally safe, and I otherwise would love to be proved wrong. -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
jrlen balane wrote: [from further down in the message] > could somebody out there help me. You could try helping yourself. Insert some print statements at salient points. [see examples below; you'll need to get the indentation correct, of course] Try to understand what is happening. > ok heres the code, i'm trying on IDLE: > > import sys > import serial > import sys, os > import serial > import string > import time > from struct import * > > data_file = open('C:/Documents and Settings/nyer/Desktop/IRRADIANCE.txt', 'r') > data = data_file.readlines() > > def process(list_of_lines): > data_points = [] > for line in list_of_lines: > data_points.append(int(line)) > return data_points > > irradiance = process(data) > > ser = serial.Serial() > ser.baudrate = 9600 > ser.port = 0 > ser I'll ask, for the 3rd time, what the @#$% is the above line meant to achieve? > > ser.open() > tx_command = 67 > tx_no_databyte = 2 > tx_message_no = 1 > tx_len = len (irradiance) > > for j in range (tx_len) : > start_time = time.time() > > temp1 = [] > temp2 = [] > pyra1 = [] > pyra2 = [] > voltage = [] > current = [] > > current_time = time.time() print 'before while stmt', j, start_time, current time > > while( current_time >= start_time + 300): > print 'inside while stmt', j, start_time, current time > data_hi, data_lo = divmod(irradiance[j], 0x100) > tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no > + tx_no_databyte) & 0xff > ser.write(pack('6B', tx_command, tx_message_no, > tx_no_databyte, data_lo, data_hi, tx_checksum)) > > rx_data = ser.read(19) > rx_len = len(rx_data) > byte = [ord(x) for x in rx_data] > > if rx_len < 10: > #print 'it is not pumping data out as fast as we assumed' > sys.exit(1) > > for k in range (rx_len-9): > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) > & 0xff == 0: > #print byte[k:k+10] > > temp1.append(byte[k+3]) > temp2.append(byte[k+4]) > pyra1.append(byte[k+5]) > pyra2.append(byte[k+6]) > voltage.append(byte[k+7]) > current.append(byte[k+8]) > print temp1, temp2, pyra1, pyra2, voltage, current > > current_time = time.time() print 'after while stmt', j, start_time, current time > > while theres no error in the output, there is also no response from > the hardware or maybe communication is off. > -- http://mail.python.org/mailman/listinfo/python-list
Re: compiled open source Windows lisp
Christopher C. Stacy wrote: > > All this information has been available in FAQs and > on many web pages since forever. When I Google for "comp.lang.lisp FAQ," I get a document that was last updated in 1997. Consequently I do not pay attention to it. I do peruse newsgroup archives, and I did make a thorough search of "Lisp stuff" 2 years ago. It is possible, however, that my criteria was somewhat more restrictive back then. As for "websites," well, there's a sea of them. I ask human beings for pointers because it saves time. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Kent Johnson wrote: Steven Bethard wrote: Bruno Desthuilliers wrote: class CommandMenuSelectionCallback: def __init__(self, key): self.key = key def __call__(self): print self.key Looks like Java. When was the last time you used Java? It has no support for using classes as callable objects. __call__ would have to be invoked manually; you definitely couldn't have a CommandMenuSelectionCallback instance masquerading as a function as this code (basically) does. It's like Java in that it uses a short helper class to define an event callback. In the case of Java it would be an anonymous inner class programming to an interface. It's like Java in that it uses five lines of code to do what Python can do in one. Well the second is definitely true. ;) Do you really prefer this verbosity to a lambda expression? Depends on the situtation. I do like that the signature of CommandMenuSelectionCallback is correct (that is, no arguments), where lambda cmd=cmdkey: CommandMenuSelection(cmd) has an optional argument when one is not asked for. OTOH, in this particular case, the real problem is that the API has made a poor choice for callbacks. The signature of UI.CmdBtn.menu.add_command should be add_command(label, command, *args, **kwargs) instead of add_command(label, command) Of course API's won't always do things the way you want them to, so I can see that in working around API deficiences, lambda can occasionally seem useful. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
On Wed, 16 Mar 2005 00:36:40 +0100, Marcin 'Qrczak' Kowalczyk <[EMAIL PROTECTED]> wrote: >[EMAIL PROTECTED] (Thomas A. Russ) writes: > >>> >(defun addn (n) >>> > #'(lambda (x) >>> > (+ x n))) >>> >>> The same as >>> def addn(n): >>> def fn(x): >>> return n + x >>> return fn >> >> Is this really equivalent? >> >> What happens if you call addn more than once with different >> parameters. Will you get different functions that you can >> use simultaneously? > >Yes. > >It also behaves correctly when a variable it refers to is later >mutated. > > >BTW, the fact that a closure refers to a variable itself rather to its >current value can be used to check the true attitude of languages with >respect to functional programming, by observing how they understand >their basic loops :-) > >Python loses: > closures = [] for i in range(10): >...def add(x): >... return x + i >...closures.append(add) >... closures[5](1000) >1009 Fire the coach -- the team can do it ;-) One way is with the help of a byte-code-hacking decorator: >>> from ut.presets import presets >>> closures = [] >>> for i in range(10): ... @presets(i=i) ... def add(x): ... return x + i ... closures.append(add) ... >>> closures[5](1000) 1005 >>> import dis >>> dis.dis(closures[5]) 2 0 LOAD_CONST 1 (5) 3 STORE_FAST 1 (i) 4 6 LOAD_FAST0 (x) 9 LOAD_FAST1 (i) 12 BINARY_ADD 13 RETURN_VALUE >>> dis.dis(closures[3]) 2 0 LOAD_CONST 1 (3) 3 STORE_FAST 1 (i) 4 6 LOAD_FAST0 (x) 9 LOAD_FAST1 (i) 12 BINARY_ADD 13 RETURN_VALUE Of course, if you want to do it without byte code hacking, you can: >>> closures2 = list((lambda i: lambda x: x + i)(i) for i in xrange(10)) >>> closures2[5](1000) 1005 >>> dis.dis(closures2[5]) 1 0 LOAD_FAST0 (x) 3 LOAD_DEREF 0 (i) 6 BINARY_ADD 7 RETURN_VALUE >>> closures2[3](1000) 1003 Or same thing without lambda: >>> def mkadd(i): ... def add(x): return x + i ... return add ... >>> closures3 = [mkadd(i) for i in xrange(10)] >>> closures3[5](1000) 1005 >>> closures3[3](1000) 1003 >>> dis.dis(closures3[5]) 2 0 LOAD_FAST0 (x) 3 LOAD_DEREF 0 (i) 6 BINARY_ADD 7 RETURN_VALUE > >as does Ruby: > >$ ruby -e ' > closures = [] > for i in 0..9 do > closures.push(proc {|x| x + i}) > end > puts closures[5][1000]' >1009 > >but Lisp loses too: > >> (let ((closures (make-array 10))) >(do ((i 0 (+ i 1))) >((= i 10)) >(setf (svref closures i) #'(lambda (x) (+ x i >(funcall (svref closures 5) 1000)) >1010 > > >Scheme wins: > >> (let ((closures (make-vector 10))) >(do ((i 0 (+ i 1))) >((= i 10)) >(vector-set! closures i (lambda (x) (+ x i >((vector-ref closures 5) 1000)) >1005 > >and what is perhaps surprising, Perl wins: > >$ perl -e ' > foreach my $i (0..9) { > push @closures, sub {$_[0] + $i} > } > print $closures[5](1000), "\n"' >1005 > > >If you think it's unlikely that one would want to keep a closure >referring to a loop control variable longer than the loop iteration >which has created it, think about the loop body spawning a thread. > Just do what you need to do. Python usually provides a way ;-) Or do you just want what you want using your idea of the right spelling? ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
Marcin 'Qrczak' Kowalczyk wrote: > [EMAIL PROTECTED] (Thomas A. Russ) writes: > > >> >(defun addn (n) > >> >#'(lambda (x) > >> >(+ x n))) > >> > >> The same as > >> def addn(n): > >>def fn(x): > >>return n + x > >>return fn > > > > Is this really equivalent? > > > > What happens if you call addn more than once with different > > parameters. Will you get different functions that you can > > use simultaneously? > > Yes. > > It also behaves correctly when a variable it refers to is later > mutated. > > > BTW, the fact that a closure refers to a variable itself rather to its > current value can be used to check the true attitude of languages with > respect to functional programming, by observing how they understand > their basic loops :-) > > Python loses: > > >>> closures = [] > >>> for i in range(10): > ...def add(x): > ... return x + i > ...closures.append(add) > ... > >>> closures[5](1000) > 1009 I had a minor discussion on this a couple weeks ago, wherein I suggested that Python does it that way because nested scopes weren't specifically done to enhance functional programming. (It's not a secret that Python is moving away from abstract functional support.) For example, Python might lose when it comes to functional programming, but it wins when it comes to nested functions like this (where a,b,c,d are in the enclosing scope and presumably changing): def print_variables(): print a,b,c,d If Python did it the way Scheme did, this would be pretty useless. IMO, this sort of usage is FAR more common than the functional usage as a closure inside a loop. Closing on a value rather than a variable would have been a lot easier to implement. I'm sure there was talk about which way to do it in the discussions about adding nested scopes to the language, and if the Python gods felt closing on a variable wasn't significantly more useful than closing on a value, I doubt they would have done that. > If you think it's unlikely that one would want to keep a closure > referring to a loop control variable longer than the loop iteration > which has created it, think about the loop body spawning a thread. Yes, it does happen here and there. I've needed to do that in GUI programming. But I would say it's not remotely as common as it other uses, and is easy to work around: > >>> closures = [] > >>> for i in range(10): > ...def defineadder(y): > ... def add(x): > ... return x + y > ... return add > ...closures.append(defineadder(i)) > ... > >>> closures[5](1000) > 1005 -- CARL BANKS -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
please post your suggestions? please ... On Wed, 16 Mar 2005 08:33:23 +0800, jrlen balane <[EMAIL PROTECTED]> wrote: > ok heres the code, i'm trying on IDLE: > > import sys > import serial > import sys, os > import serial > import string > import time > from struct import * > > data_file = open('C:/Documents and Settings/nyer/Desktop/IRRADIANCE.txt', 'r') > data = data_file.readlines() > > def process(list_of_lines): > data_points = [] > for line in list_of_lines: > data_points.append(int(line)) > return data_points > > irradiance = process(data) > > ser = serial.Serial() > ser.baudrate = 9600 > ser.port = 0 > ser > > ser.open() > tx_command = 67 > tx_no_databyte = 2 > tx_message_no = 1 > tx_len = len (irradiance) > > for j in range (tx_len) : > start_time = time.time() > > temp1 = [] > temp2 = [] > pyra1 = [] > pyra2 = [] > voltage = [] > current = [] > > current_time = time.time() > > while( current_time >= start_time + 300): > > data_hi, data_lo = divmod(irradiance[j], 0x100) > tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no > + tx_no_databyte) & 0xff > ser.write(pack('6B', tx_command, tx_message_no, > tx_no_databyte, data_lo, data_hi, tx_checksum)) > > rx_data = ser.read(19) > rx_len = len(rx_data) > byte = [ord(x) for x in rx_data] > > if rx_len < 10: > #print 'it is not pumping data out as fast as we assumed' > sys.exit(1) > > for k in range (rx_len-9): > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) > & 0xff == 0: > #print byte[k:k+10] > > temp1.append(byte[k+3]) > temp2.append(byte[k+4]) > pyra1.append(byte[k+5]) > pyra2.append(byte[k+6]) > voltage.append(byte[k+7]) > current.append(byte[k+8]) > print temp1, temp2, pyra1, pyra2, voltage, current > > current_time = time.time() > > while theres no error in the output, there is also no response from > the hardware or maybe communication is off. > > could somebody out there help me. > > by the way, here is a working code: though here the data to be > transmitted is just incrementing and not read from a text file: > > import serial > import string > import time > from struct import * > import os > > ser = serial.Serial() > > ser.baudrate = 9600 > ser.port = 0 > ser.timeout = 1 > ser > > ser.open() > tx_command = 67 > tx_message_no = 1 > tx_no_databyte = 2 > item=1 > for item in range(1, 30001, 10): > > data_hi, data_lo = divmod(item, 0x100) > tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no + > tx_no_databyte) & 0xff > ser.write(pack('6B', tx_command, tx_message_no, tx_no_databyte, > data_lo, data_hi, tx_checksum)) > #print tx_command, tx_message_no, tx_total_data, data_lo, data_hi, > tx_checksum > > > rx_data = ser.read(19) > rx_len = len(rx_data) > #print 'rx_len', rx_len > byte = [ord(x) for x in rx_data] > #print 'received', byte > > if rx_len < 10: > print 'it is not pumping data out as fast as we assumed' > sys.exit(1) > > for k in range (rx_len-9): > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & 0xff == > 0: > print byte[k:k+10] > === > outputs: > [70, 2, 6, 54, 197, 253, 230, 231, 211, 26] > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] > ... > ... > > On Wed, 16 Mar 2005 07:34:44 +0800, jrlen balane <[EMAIL PROTECTED]> wrote: > > will this be correct??? > > what i want to happen is saved every received data (6 data bytes) to > > an array for each one. > > > > for k in range (rx_len-9): > > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & 0xff == 0: > > #print byte[k:k+10] > > > >temp1.append(byte[k+3]) > >temp2.append(byte[k+4]) > >pyra1.append(byte[k+5]) > >pyra2.append(byte[k+6]) > >voltage.append(byte[k+7]) > >current.append(byte[k+8]) > > > >if time.sleep(300) == True: > > temp1 = [] > > temp2 = [] > > pyra1 = [] > > pyra2 = [] > > voltage = [] > > current = [] > > > > and after x minutes of of receiving data, the arrays will be emptied > > of its contents. > > > > thanks again for the help. > > On 15 Mar 2005 02:13:40 -0800, John Machin <[EMAIL PROTECTED]> wrote: > > >
Re: python reading excel thru ADO ?
> "tc" == tc <[EMAIL PROTECTED]> writes: tc> I always used win32com.client to access excel files and parse tc> them, save them as website, csv and so on. tc> why exactly is it that u use ado for solving this? tc> TC The value of ADO would be to throw some Stupid Question Language at an .xls. One thing to keep an eye on is text-heavy fields; I've seen >255 char strings truncated, in which chase instantiating excel.exe is all you can do. R, C -- http://mail.python.org/mailman/listinfo/python-list
Problem with _imaging.pyd in windows
Hello, I install the follow packages python-2.4 for windows PIL-1.1.5c1.win32-py2.4 numarray-1.2.3.win32-py2.4 but when I run some code and this error appear AppName: pythonw.exe AppVer: 0.0.0.0 ModName: _imaging.pyd ModVer: 0.0.0.0 Offset: 373a Exit code: -1073741819 and I don´t know where is tthe problem! I tried install older versions but I have the same error VP -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Bruno Desthuilliers wrote: A few examples: [...] - to get the length of a sequence, you use len(seq) instead of seq.len() - to call objects attributes by name, you use [get|set]attr(obj, name [,value]) instead of obj.[get|set]attr(name [,value]) These are both very consistent applications of a more functional style of programming, rather than the pure object-oriented style you seem to desire. It's not that Python is inconsistent; it's that Python is consistently blending multiple paradigms in a way that uses the best features of each and (mostly) avoids the worst pitfalls of each. - if x is a class attribute of class A and a is an instance of A, a.x=anyvalue create a new instance attribute x instead of modifying A.x This is very consistent with the way that binding a name in any scope will shadow any bindings of that name in "higher" scopes. It is the same principle by which one is able to use the same name for a function-local variable that is used for a global variable, without destroying that global variable. Doing as you suggest would be far *less* consistent, and would create a special case for class/instance lookups where there is none now. - sequence methods that modify the sequence in place return None instead of returning self - ok, I know the rational for this one, but I still dont like it, and still count it as a special case since when using a 'destructive' sequence method I can't chain it with non-destructive method calls. This is not a special case. It is a deliberate and consistent design decision, and it is implemented uniformly through the standard library. Note that if your preference was the standard, one could *still* use the same logic to call it a special case -- that in some cases a method call returns a new object leaving the original unmodified, and in other cases it modifies the original object and returns a reference to it. The current implementation has the advantage of being much less likely to lead to hard-to-detect bugs than your preference would. Also, Python enforce some coding style (indentation) but not some others (capitalization for example). So you always have to check, on a lib by lib base, what style has been used (I personnaly don't give a damn whether I use underscore_all_lower or mixedCaps, but consistency is useful, even more when there's such a huge stdlib). Worst, the base class for new style classes is all lower ('object') when the usual convention is to use CamelCase for classes. Um... does Lisp enforce capitalization? No. Does C? I didn't think so. Keep in mind that Python uses indentation not as a coding style, but as an inherent part of the syntax in the same way that C uses {} (but that indentation is much easier for humans to keep straight). Do you complain that C enforces brace-usage but not capitalization styles? What you have here is a listing of things about Python that you don't like. They are not actually special cases, except in the sense of "things that Bruno especially dislikes". Now, you're welcome to dislike them if you want, but be aware that some of the things that you're looking at as weaknesses, others of us see as positive and beneficial things, and in many cases there's real evidence to support the contention that Python's design choices will decrease the frequency of bugs. Perhaps Python *is* becoming less Lisp-like... but I've never been convinced that Lisp is the best of all possible programming languages, so maybe being less Lisp-like and more Python-like is a good thing. Jeff Shannon -- http://mail.python.org/mailman/listinfo/python-list
Re: why this error?
spencer wrote: Hi, I'm not sure why I can't concatenate dirname() with basename(). Of course you *can* concatenate them, but you're not getting that far. The piece os.path.dirname(os.getcwd) should be os.path.dirname(os.getcwd()) Then it will work without raising an exception, but I'm not sure the result makes sense. Traceback (most recent call last): File "showDir.py", line 50, in ? print 'somthing new...', os.path.join(os.path.dirname(os.getcwd)) + os.path.basename(os.getcwd()) File "/usr/lib/python2.3/posixpath.py", line 119, in dirname return split(p)[0] File "/usr/lib/python2.3/posixpath.py", line 77, in split i = p.rfind('/') + 1 AttributeError: 'builtin_function_or_method' object has no attribute 'rfind' Thanks, Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing the contents of a 'cell' object from Python
Here's an old thread I contributed to which had a similar function (called 'cell_get' in this case) http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/baba3b943524a92c/71b57a32b311ffc8?q=func_closure#71b57a32b311ffc8 http://groups-beta.google.com/group/comp.lang.python/msg/71b57a32b311ffc8?dmode=source Jeff pgpXLMoKMtyfX.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Steven Bethard wrote: Bruno Desthuilliers wrote: class CommandMenuSelectionCallback: def __init__(self, key): self.key = key def __call__(self): print self.key Looks like Java. When was the last time you used Java? It has no support for using classes as callable objects. __call__ would have to be invoked manually; you definitely couldn't have a CommandMenuSelectionCallback instance masquerading as a function as this code (basically) does. It's like Java in that it uses a short helper class to define an event callback. In the case of Java it would be an anonymous inner class programming to an interface. It's like Java in that it uses five lines of code to do what Python can do in one. Do you really prefer this verbosity to a lambda expression? Yikes! Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Martin Franklin wrote: Tim Daneliuk wrote: Except that in this case, removal will also complicate code in some cases. Consider this fragment of Tkinter logic: UI.CmdBtn.menu.add_command(label="MyLabel", command=lambda cmd=cmdkey: CommandMenuSelection(cmd)) In this case you perhaps should try using a class like so:- UI.CmdBtn.menu.add_command(label="MyLabel", command=CommandMenuSelectionCallback(cmdkey)) Where CommandMenuSelectionCallback is a class like so: class CommandMenuSelectionCallback: def __init__(self, key): self.key = key def __call__(self): print self.key One could equivalently define CommandMenuSelectionCallback as a function which creates and returns closures -- def CommandMenuSelectionCallback(key): def func(): CommandMenuSelection(key) return func This should have the same practical value as the callable class; in both cases you have a callable taking a single argument, which produces a callable taking no arguments. Whether one prefers that the resulting callable object be a class instance or a closure (function) seems to me to be largely a matter of taste. Also, once Python 2.5 is realeased, one should be able to use the partial() function (see http://www.python.org/peps/pep-0309.html) to accomplish much the same thing in a more general fashion. ISTM that partial() will cover somewhere between 50% and 95% of the current (reasonable) uses of lambda -- my guess being that it's towards the hight end of that range. Jeff Shannon -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 18, Issue 208
Jeff Shannon <[EMAIL PROTECTED]> wrote: > >> I'd be in favor of that, unless someone can come up with a compelling > >> current use-case for octal literals. I grew up talking octal, and while I'm still more comfortable in octal than hex (newline to me is always going to be 012, not 0xA), even a luddite like myself recognizes that hex just makes more sense in a 8/16/32/64-bit world. -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
ok heres the code, i'm trying on IDLE: import sys import serial import sys, os import serial import string import time from struct import * data_file = open('C:/Documents and Settings/nyer/Desktop/IRRADIANCE.txt', 'r') data = data_file.readlines() def process(list_of_lines): data_points = [] for line in list_of_lines: data_points.append(int(line)) return data_points irradiance = process(data) ser = serial.Serial() ser.baudrate = 9600 ser.port = 0 ser ser.open() tx_command = 67 tx_no_databyte = 2 tx_message_no = 1 tx_len = len (irradiance) for j in range (tx_len) : start_time = time.time() temp1 = [] temp2 = [] pyra1 = [] pyra2 = [] voltage = [] current = [] current_time = time.time() while( current_time >= start_time + 300): data_hi, data_lo = divmod(irradiance[j], 0x100) tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no + tx_no_databyte) & 0xff ser.write(pack('6B', tx_command, tx_message_no, tx_no_databyte, data_lo, data_hi, tx_checksum)) rx_data = ser.read(19) rx_len = len(rx_data) byte = [ord(x) for x in rx_data] if rx_len < 10: #print 'it is not pumping data out as fast as we assumed' sys.exit(1) for k in range (rx_len-9): if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & 0xff == 0: #print byte[k:k+10] temp1.append(byte[k+3]) temp2.append(byte[k+4]) pyra1.append(byte[k+5]) pyra2.append(byte[k+6]) voltage.append(byte[k+7]) current.append(byte[k+8]) print temp1, temp2, pyra1, pyra2, voltage, current current_time = time.time() while theres no error in the output, there is also no response from the hardware or maybe communication is off. could somebody out there help me. by the way, here is a working code: though here the data to be transmitted is just incrementing and not read from a text file: import serial import string import time from struct import * import os ser = serial.Serial() ser.baudrate = 9600 ser.port = 0 ser.timeout = 1 ser ser.open() tx_command = 67 tx_message_no = 1 tx_no_databyte = 2 item=1 for item in range(1, 30001, 10): data_hi, data_lo = divmod(item, 0x100) tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no + tx_no_databyte) & 0xff ser.write(pack('6B', tx_command, tx_message_no, tx_no_databyte, data_lo, data_hi, tx_checksum)) #print tx_command, tx_message_no, tx_total_data, data_lo, data_hi, tx_checksum rx_data = ser.read(19) rx_len = len(rx_data) #print 'rx_len', rx_len byte = [ord(x) for x in rx_data] #print 'received', byte if rx_len < 10: print 'it is not pumping data out as fast as we assumed' sys.exit(1) for k in range (rx_len-9): if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & 0xff == 0: print byte[k:k+10] === outputs: [70, 2, 6, 54, 197, 253, 230, 231, 211, 26] [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] ... ... On Wed, 16 Mar 2005 07:34:44 +0800, jrlen balane <[EMAIL PROTECTED]> wrote: > will this be correct??? > what i want to happen is saved every received data (6 data bytes) to > an array for each one. > > for k in range (rx_len-9): > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & 0xff == 0: > #print byte[k:k+10] > >temp1.append(byte[k+3]) >temp2.append(byte[k+4]) >pyra1.append(byte[k+5]) >pyra2.append(byte[k+6]) >voltage.append(byte[k+7]) >current.append(byte[k+8]) > >if time.sleep(300) == True: > temp1 = [] > temp2 = [] > pyra1 = [] > pyra2 = [] > voltage = [] > current = [] > > and after x minutes of of receiving data, the arrays will be emptied > of its contents. > > thanks again for the help. > On 15 Mar 2005 02:13:40 -0800, John Machin <[EMAIL PROTECTED]> wrote: > > > > jrlen balane wrote: > > > did some editing: > > > > > > > The error means that you received less than 19 bytes of data. > > > > > rx_data = ser.read(19) > > !rx_len = len(rx_data) > > !print 'rx_len', rx_len > > > byte[0:18] = unpack('19B', rx_data) > > !# trash the above, do this > > !byte = [ord(x) for x in rx_data] > > !print 'received', byte
Re: Lisp-likeness
Marcin 'Qrczak' Kowalczyk <[EMAIL PROTECTED]> writes: > BTW, the fact that a closure refers to a variable itself rather to its > current value can be used to check the true attitude of languages with > respect to functional programming, by observing how they understand > their basic loops :-) The thread "Midfunction Recursion"¹ from October 2002 sounds relevant here, exploring options for bindings in iteration. Footnotes: ¹ http://groups-beta.google.com/group/comp.lang.lisp/browse_frm/thread/46bb18e56cad/0590de10f975a059 -- Steven E. Harris -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 18, Issue 208
Martin v. Löwis wrote: Jeff Shannon wrote: I'd be in favor of that, unless someone can come up with a compelling current use-case for octal literals. Existing code. It may use octal numbers, and it would break if they suddenly changed to decimal. Right, which was my original point -- it was only in the context of Python 3.0 / 3K, when backwards compatibility is *already* being deliberately discarded, that getting rid of octal constants would be worth considering. (I had specified *current* use-case to specifically indicate "other than backwards-compatibility and historical reasons" -- I know those are overriding until Py3K, but if the whole point of Py3K is to ditch all the "features" that exist only for backwards-compatibility and historical reasons, then...) Jeff Shannon -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing the contents of a 'cell' object from Python
On Tue, Mar 15, 2005 at 03:08:19PM -0700, paul cannon wrote: > Having poked around a little bit, I found there doesn't appear to be any > way to get at the contents of a cell object from Python. It's not the > sort of thing that one needs to be doing very frequently, but I've run > into a few situations recently where it would be really useful from a > debugging standpoint. Okay, I did come up with one solution- create a new function that just returns a value from its own closure, and manufacture its closure from the cell you already have. So.. import new def get_cell_value(cell): return new.function( (lambda x: lambda: x)(0).func_code, {}, None, None, (cell,) )() It could be optimized a bit by precalculating the code object. I do still think the earlier solution (giving the cell objects a method) is cleaner and better long-term, but this will do. -- paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 18, Issue 208
Jeff Shannon wrote: I'd be in favor of that, unless someone can come up with a compelling current use-case for octal literals. Existing code. It may use octal numbers, and it would break if they suddenly changed to decimal. Not only that - breakage would be *silent*, i.e. the computations would just use incorrect numbers. You could make breakage explicit, by disallowing leading zeroes in integer literals - but still, programs would break. As for functional use-cases: os.chmod is the typical example: os.chmod("/tmp/bla", 0660) gives rw-rw access to /tmp/bla. Unix permission line up nicely with octal numbers. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils setup ignoring scripts
"Jack Orenstein" wrote: > Quoting [i]: > > as you use Python22 on RH9, maybe: > > python setup.py bdist_rpm --install-script foobar > > Is install-script really needed? I would have thought that specifying > setup( ... scripts = [...] ...) would suffice, based on the python > docs. > i think you need to precise it, and even with some other rpm specific options like: --use-rpm-opt-flags but ... i'm not sure that those options are already implemented with Python22. if not you may have to upgrade! -- nirinA -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create stuffit files on Linux?
Stuffit Expander can handle zip, rar, tar, gz, etc, etc, etc. Don't worry. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Torsten Bronger <[EMAIL PROTECTED]> wrote: > I have exactly the same impression, but for me it's the reason why I > feel uncomfortable with them. For example, I fear that a skilled > package writer could create a module with surprising behaviour by > using the magic of these constructs. If the behaviour is surprising, then the package writer wasn't very skilled... A very large part of the skill needed to write a module, is knowing how to design its interface so it becomes easy to use, intuitive, and non-surprising. > I don't know Python well > enough to get more specific, but flexibility almost always make > confusing situations for non-hackers possible. On the other hand, *in*flexibility doesn't give any guarantee against confusing situations. At least not as long as there is enough flexibility in the language to actually allow you to do anything more advanced than "Hello World". And inflexibility will always make some situations horribly daunting to get out of. Powerful constructs like these can, in some cases, enable a skilled package writer to design an API that reduces the amount of boiler plate code needed for using the package. If some authors write bad books, do you blame the English language for allowing them to write such books, or do you blame the writers for using English in a bad way? -- Thomas Bellman, Lysator Computer Club, Linköping University, Sweden "We don't understand the software, and! bellman @ lysator.liu.se sometimes we don't understand the hardware, ! but we can *see* the blinking lights!" ! Make Love -- Nicht Wahr! -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
Marcin 'Qrczak' Kowalczyk wrote: [EMAIL PROTECTED] (Thomas A. Russ) writes: (defun addn (n) #'(lambda (x) (+ x n))) The same as def addn(n): def fn(x): return n + x return fn Is this really equivalent? What happens if you call addn more than once with different parameters. Will you get different functions that you can use simultaneously? Yes. It also behaves correctly when a variable it refers to is later mutated. BTW, the fact that a closure refers to a variable itself rather to its current value can be used to check the true attitude of languages with respect to functional programming, by observing how they understand their basic loops :-) None of the examples you show close over values. The difference is in whether the loop constructs use one binding for their control variable or create new bindings in each iteration: (loop for i below 10 collect (lambda (x) (setq i x)) into setters collect (lambda () i) into getters finally (print (funcall (elt getters 0))) (funcall (elt setters 4) 42) (print (funcall (elt getters 9 => 10 => 42 If this difference matters to you, just be more explicit. Pascal -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Bruno Desthuilliers wrote: class CommandMenuSelectionCallback: def __init__(self, key): self.key = key def __call__(self): print self.key Looks like Java. When was the last time you used Java? It has no support for using classes as callable objects. __call__ would have to be invoked manually; you definitely couldn't have a CommandMenuSelectionCallback instance masquerading as a function as this code (basically) does. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 18, Issue 208
Reinhold Birkenfeld wrote: So what's the current state of the "universal-base-prefix" syntax? Something like 10x10, 16xA and 8x12? An interesting thought -- I like the consistency. On the other hand, I have a hard time imagining that this is such a common need that it requires syntactic support. The int type should cover most use cases: py> int("10", 10) 10 py> int("A", 16) 10 py> int("12", 8) 10 STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
[EMAIL PROTECTED] (Thomas A. Russ) writes: >> >(defun addn (n) >> > #'(lambda (x) >> > (+ x n))) >> >> The same as >> def addn(n): >> def fn(x): >> return n + x >> return fn > > Is this really equivalent? > > What happens if you call addn more than once with different > parameters. Will you get different functions that you can > use simultaneously? Yes. It also behaves correctly when a variable it refers to is later mutated. BTW, the fact that a closure refers to a variable itself rather to its current value can be used to check the true attitude of languages with respect to functional programming, by observing how they understand their basic loops :-) Python loses: >>> closures = [] >>> for i in range(10): ...def add(x): ... return x + i ...closures.append(add) ... >>> closures[5](1000) 1009 as does Ruby: $ ruby -e ' closures = [] for i in 0..9 do closures.push(proc {|x| x + i}) end puts closures[5][1000]' 1009 but Lisp loses too: > (let ((closures (make-array 10))) (do ((i 0 (+ i 1))) ((= i 10)) (setf (svref closures i) #'(lambda (x) (+ x i (funcall (svref closures 5) 1000)) 1010 Scheme wins: > (let ((closures (make-vector 10))) (do ((i 0 (+ i 1))) ((= i 10)) (vector-set! closures i (lambda (x) (+ x i ((vector-ref closures 5) 1000)) 1005 and what is perhaps surprising, Perl wins: $ perl -e ' foreach my $i (0..9) { push @closures, sub {$_[0] + $i} } print $closures[5](1000), "\n"' 1005 If you think it's unlikely that one would want to keep a closure referring to a loop control variable longer than the loop iteration which has created it, think about the loop body spawning a thread. -- __("< Marcin Kowalczyk \__/ [EMAIL PROTECTED] ^^ http://qrnik.knm.org.pl/~qrczak/ -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a problem on this simple code
will this be correct??? what i want to happen is saved every received data (6 data bytes) to an array for each one. for k in range (rx_len-9): if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & 0xff == 0: #print byte[k:k+10] temp1.append(byte[k+3]) temp2.append(byte[k+4]) pyra1.append(byte[k+5]) pyra2.append(byte[k+6]) voltage.append(byte[k+7]) current.append(byte[k+8]) if time.sleep(300) == True: temp1 = [] temp2 = [] pyra1 = [] pyra2 = [] voltage = [] current = [] and after x minutes of of receiving data, the arrays will be emptied of its contents. thanks again for the help. On 15 Mar 2005 02:13:40 -0800, John Machin <[EMAIL PROTECTED]> wrote: > > jrlen balane wrote: > > did some editing: > > > > The error means that you received less than 19 bytes of data. > > > rx_data = ser.read(19) > !rx_len = len(rx_data) > !print 'rx_len', rx_len > > byte[0:18] = unpack('19B', rx_data) > !# trash the above, do this > !byte = [ord(x) for x in rx_data] > !print 'received', byte > !if rx_len < 10: > ! print 'it is not pumping data out as fast as we assumed!' > ! sys.exit(1) > > > !for k in range(rx_len - 9): > >if byte[k] == 70: > >if byte[k+2] == 6: > >if byte[k+9] == > > > -(byte[k]+byte[k+1]+byte[k+2]+byte[k+3]+byte[k+4]+byte[k+5]+byte[k+6]+byte[k+7]+byte[k+8]) > > & 0xff: > > Yuk! > > (1) use 'and' > (2) when you find yourself typing repetitive crap like that, your brain > should be shrieking "There must be a better way!!" > > if byte[k] == 70 \ > and byte[k+2] == 6 \ > and sum(byte[k:k+10]) & 0xff == 0: > > >print byte[k:k+9] <<=== you probably mean 10, > not nine > > > > heres the error: > > Traceback (most recent call last): > > File "C:\Python23\practices\serialnewesttest2.py", line 28, in > -toplevel- > > byte[0:18] = unpack('19B', rx_data) > > error: unpack str size does not match format > > > > what i am doing here is creating an array from based on the unpacked > data > > then i am searching for the array member that is equal to "70" since > > it is going to be my reference. once i find it, i'll based my > received > > data from that point. then if the succeding tests are confirmed, i > can > > get my data. > > > > please help(again) :( > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: compiled open source Windows lisp (was Re: Python becoming less Lisp-like)
James Graves wrote: > > But coverage in this area (compiled CL) is a bit thin, I'll admit. > But who really cares? After all, there are the mature commercial proprietary lisp compilers for those people who insist on using closedware OSes, and they've already proven they're willing to use closedware. This, I fear, is similar to Brandon's demands for a microcrap visual-studio compatible yet open source gaming framework. or silly expectations of microsoft suite support for various open-source language implementations (just google search on groups for his name...): Might happen (has happened, to an extent), but where's the developer motivation? It's not like it's hard to install linux these days. Most open source developers would be indifferent at best to a windows port, it's not like it's even a fun challenge like a port to an obscure platform like AROS would be, you just end up with creeping hungarian notation ugliness in your code, and lots of #defines. Most people writing open source and for the fun of it just aren't going to go massively out of the way to support windows, and even if they do, they're just giving the slaves another excuse not to throw off their chains. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
Thomas A. Russ wrote: > Fernando <[EMAIL PROTECTED]> writes: > > >>On 15 Mar 2005 00:43:49 -0800, "Kay Schluehr" <[EMAIL PROTECTED]> >>wrote: >> >> >>>Maybe You can answer my question what this simple LISP function does ? >>> >>>(defun addn (n) >>> #'(lambda (x) >>> (+ x n))) >> >>The same as >>def addn(n): >> def fn(x): >> return n + x >> return fn > > > Is this really equivalent? AFAIK, yes. I admit that I know almost nothing about Lisp though. And I'm not a Python guru either. > What happens if you call addn more than once with different > parameters. Will you get different functions that you can > use simultaneously? Yes. Using the addn function defined above, you can do for example: >>> add4 = addn(4) >>> add10 = addn(10) >>> add4(5) 9 >>> add10(7) 17 >>> add4(add10(28)) 42 And so on. At least, I think that's what you mean. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Minidom empty script element bug
Derek Basch wrote: XHTML 1.0 specs, Appendix C [EMAIL PROTECTED] C.3 Element Minimization and Empty Element Content Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use and not ) [EMAIL PROTECTED] I'd like to point out that this is *not* a minidom bug. minidom cannot possibly know that the document type is XHTML, and that strange, non-XML rules apply to XHTML (i.e. rules which are not present in XML itself). I'd also like to point out that XHTML Appendix C is informative (i.e. non-normative), meaning that failure to comply to it does not imply non-compliance with XHTML. An XML file which uses the minimized form for the script element is still proper, well-formed, valid XHTML. How do I get minidom to NOT render an empty script element? Should I submit a bug report? That said, I think there is a simple solution: add an empty Text node to the script element: script_node_0.appendChild(doc.createText(u"")) [Disclaimer: this is untested; from reading the source, I think it should work] Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: why this error?
spencer wrote: > Hi, > I'm not sure why I can't concatenate dirname() with basename(). > > Traceback (most recent call last): > File "showDir.py", line 50, in ? > print 'somthing new...', os.path.join(os.path.dirname(os.getcwd)) + > os.path.basename(os.getcwd()) > File "/usr/lib/python2.3/posixpath.py", line 119, in dirname > return split(p)[0] > File "/usr/lib/python2.3/posixpath.py", line 77, in split > i = p.rfind('/') + 1 Several errors: - os.getcwd is the _function_, you need to call them os.getcwd(), as you do in the second call to it. - the join is supposed to work on a list of arguments, like this: os.path.join("a", "b", "c") will yield a/b/c But you concatenate two strings using +, and thus have only one argument at all, which can't be joined as it is only one... -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: why this error?
Le Wed, 16 Mar 2005 17:53:57 -0500, spencer a écrit : > Hi, > I'm not sure why I can't concatenate dirname() with basename(). > > Traceback (most recent call last): > File "showDir.py", line 50, in ? > print 'somthing new...', os.path.join(os.path.dirname(os.getcwd)) + > os.path.basename(os.getcwd()) The problem is here : os.path.join() take at least one parameter, but it is silly to use it with only one. Replace the « + » by a comma. > File "/usr/lib/python2.3/posixpath.py", line 119, in dirname > return split(p)[0] > File "/usr/lib/python2.3/posixpath.py", line 77, in split > i = p.rfind('/') + 1 > AttributeError: 'builtin_function_or_method' object has no attribute > 'rfind' > Thanks, > Wayne > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't seem to insert rows into a MySQL table
Anthra Norell wrote: > Very true! > I could verify that cursor.execute () seems to understand "... %s ...", > ..."string"... where print () doesn't.. I didn't know that. > I could also verify that gumfish's ineffective insertion command works fine > for me. (Python 2.4, mysql-3.23.38). So it looks like the problem is with > MySQL (e.g. table name, column names, ...) I'm not sure if this is what you are referring to, but here's the definitive answer: MySQLdb uses %s as a parameter placeholder. When you pass the parameters in a tuple as the second argument (as PEP-249 and the API documentation tells you to), MySQLdb escapes any special characters that may be present, and adds quotation marks as required. However, the only parameters you can pass in that way are SQL literal values, i.e. 15, 'string literal', '2005-03-15', etc. You can NOT pass in things like names (column, table, database) or other pieces of arbitrary SQL; these would be treated as strings, and thus be quoted. Anything other than literal values has to be added some other way, either by use of format strings and % or string concatenation, or whatnot. You can double the % (i.e. %%s) so that if you also have parameters to pass, their placeholder will be preserved. You need to be very careful about what you allow to be inserted into your SQL query when not using the quoting/escaping of execute(). > > In <[EMAIL PROTECTED]>, Anthra Norell > > wrote: > > > > > Try to use % instead of a comma (a Python quirk) and quotes around your > > > strings (a MySQL quirk): > > > > > >cursor.execute("INSERT INTO edict (kanji, kana, meaning) VALUES ('%s', > > > '%s', '%s')" % ("a", "b", "c") ) Don't do this. -- http://mail.python.org/mailman/listinfo/python-list
How to create stuffit files on Linux?
I need to create Stuffit (.sit) files on Linux. Does anyone have any ideas for how to do this? I checked the Python docs and on SourceForge, but I didn't see any open source stuffit compatible libraries. Are my Mac users out of luck? Yours, Noah -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
[EMAIL PROTECTED] (Thomas A. Russ) writes: >> >(defun addn (n) >> > #'(lambda (x) >> > (+ x n))) >> >> The same as >> def addn(n): >> def fn(x): >> return n + x >> return fn > > Is this really equivalent? > > What happens if you call addn more than once with different > parameters. Will you get different functions that you can > use simultaneously? Yes. It also behaves correctly when a variable it refers to is later mutated. -- __("< Marcin Kowalczyk \__/ [EMAIL PROTECTED] ^^ http://qrnik.knm.org.pl/~qrczak/ -- http://mail.python.org/mailman/listinfo/python-list
RE: How to create stuffit files on Linux?
noah, i'm fairly certain that stuffit will accommodate a number of formats, including zip. if you look around, you probably have open source that will create zip, which can then be read by stuffit... stuffit also provides an sdk that can probably be used to create what you need. check their site, or use google to get a better feel for what it provdes.. -bruce -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Noah Sent: Tuesday, March 15, 2005 2:03 PM To: python-list@python.org Subject: How to create stuffit files on Linux? I need to create Stuffit (.sit) files on Linux. Does anyone have any ideas for how to do this? I checked the Python docs and on SourceForge, but I didn't see any open source stuffit compatible libraries. Are my Mac users out of luck? Yours, Noah -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib (and urllib2) read all data from page on open()?
[EMAIL PROTECTED] (Bengt Richter) writes: > ISTM reading top-posts is only easier when the top-post is a single global > comment on the quoted text following. And that stops being true as soon as someone wants to comment on that comment. You either wind up with: Last comment > First comment >> Original text. or > First comment Last comment. >> Original text. Both of which are a PITA to deal with. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Minidom empty script element bug
Hello All, I ran into a problem while dynamically constructing XHTML documents using minidom. If you create a script tag such as: script_node_0 = self.doc.createElement("script") script_node_0.setAttribute("type", "text/javascript") script_node_0.setAttribute("src", "../test.js") minidom renders it as: Which is incorrect because: XHTML 1.0 specs, Appendix C [EMAIL PROTECTED] C.3 Element Minimization and Empty Element Content Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use and not ) [EMAIL PROTECTED] reference for further explanation: http://lists.evolt.org/archive/Week-of-Mon-20020304/105951.html So, the rendered page completely fails on IE6 because it actually handles the empty script element correctly. Mozilla handles the element incorrectly and instantiates the javascript. How do I get minidom to NOT render an empty script element? Should I submit a bug report? Thanks for the help, Derek Basch __ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ -- http://mail.python.org/mailman/listinfo/python-list
why this error?
Hi, I'm not sure why I can't concatenate dirname() with basename(). Traceback (most recent call last): File "showDir.py", line 50, in ? print 'somthing new...', os.path.join(os.path.dirname(os.getcwd)) + os.path.basename(os.getcwd()) File "/usr/lib/python2.3/posixpath.py", line 119, in dirname return split(p)[0] File "/usr/lib/python2.3/posixpath.py", line 77, in split i = p.rfind('/') + 1 AttributeError: 'builtin_function_or_method' object has no attribute 'rfind' Thanks, Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI toolkit question
If you may need to port to another language, you'll probably want to use a toolkit that helps you store the interface description seperately from the code. The example I'm most familiar with is libglade for GTK, although I believe Qt and wx have analagous facilities. I don't do 3D stuff myself, but I'd guess that your best bet for that will be OpenGL. wxwidgets 2.1.14 and higher has an OpenGL canvas included with the stock distribution. OpenGL widgets also exist for GTK, and the Trolltech website says that OpenGL functionality is included with QT/X11, though I have no experience with this. Others can offer more informed advice than I can, but I'd probably reccommend Qt. Very good documentation, Qt designer rocks, and I'd trust their OpenGl stuff more than the others. Greg Steffensen -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
Thomas A. Russ <[EMAIL PROTECTED]> wrote: > > >(defun addn (n) > > > #'(lambda (x) > > > (+ x n))) > > > > The same as > > def addn(n): > > def fn(x): > > return n + x > > return fn > > Is this really equivalent? yes > What happens if you call addn more than once with different > parameters. Will you get different functions that you can > use simultaneously? yes > The lisp snippet creates new functions each time the addn function is > called, so one can interleave calls to the individual functions. In [21]: a = addn(4) In [22]: b = addn(5) In [23]: c = addn(25) In [24]: a(1) Out[24]: 5 In [25]: b(1) Out[25]: 6 In [26]: c(1) Out[26]: 26 -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.3.8 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de -- http://mail.python.org/mailman/listinfo/python-list
ElementTree/DTD question
I'm trying to convert from minidom to ElementTree for handling XML, and am having trouble with entities in DTDs. My Python script looks like this: -- #!/usr/bin/env python import sys, os from elementtree import ElementTree for filename in sys.argv[1:]: ElementTree.parse(filename) -- My first attempt was this XML file: -- ]> Write an introduction&ldots; -- Running "python validate.py first.xml" produces: -- Traceback (most recent call last): File "validate.py", line 7, in ? ElementTree.parse(filename) File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py", line 865, in parse tree.parse(source, parser) File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py", line 589, in parse parser.feed(data) File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py", line 1160, in feed self._parser.Parse(data, 0) File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py", line 1113, in _default raise expat.error( xml.parsers.expat.ExpatError: undefined entity &ldots;: line 9, column 27 -- All right, pull the DTD out, and use this XML file: -- Write an introduction&ldots; -- with this minimalist DTD (saved as "swc.dtd" in the same directory as both the XML file and the script): -- -- Same error; only the line number changed. Anyone know what I'm doing wrong? (Note: minidom loads it just fine...) Thanks, Greg Wilson [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
On Tue, 15 Mar 2005 14:16:09 -0800, Thomas A. Russ wrote: > The lisp snippet creates new functions each time the addn function is > called, so one can interleave calls to the individual functions. Yes, I believe them to be equivalent. Each call to addn creates an activation record which is closed over by fn. foo = addn(5) bar = addn(6) foo(4) => 9 bar(4) => 10 Matt -- "You do not really understand something unless you can explain it to your grandmother." â Albert Einstein. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp-likeness
Fernando <[EMAIL PROTECTED]> writes: > > On 15 Mar 2005 00:43:49 -0800, "Kay Schluehr" <[EMAIL PROTECTED]> > wrote: > > >Maybe You can answer my question what this simple LISP function does ? > > > >(defun addn (n) > > #'(lambda (x) > > (+ x n))) > > The same as > def addn(n): > def fn(x): > return n + x > return fn Is this really equivalent? What happens if you call addn more than once with different parameters. Will you get different functions that you can use simultaneously? The lisp snippet creates new functions each time the addn function is called, so one can interleave calls to the individual functions. -- Thomas A. Russ, USC/Information Sciences Institute -- http://mail.python.org/mailman/listinfo/python-list
Re: readonly class attribute ?
Bengt Richter a écrit : On Tue, 15 Mar 2005 20:21:19 +0100, bruno modulix <[EMAIL PROTECTED]> wrote: Hi How can I make a *class* attribute read-only ? (snip) Does this help, or did I misunderstand? >>> class Base(object): ... class __metaclass__(type): ... def __setattr__(cls, name, value): ... raise AttributeError, 'setting %r to %r not allowed' %(name, value) Pretty obvious, indeed ! Bengt, if we meet one day, remind me to pay you a couple of your favorite drink !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: readonly class attribute ?
Simon Percivall a écrit : Start the attribute name with "_" and don't document it. If clients mess with it, they're to blame. The problem is that client code must *define* this attribute when subclassing BaseClass - and that's (well, in most case that should be) the only place where they have to deal with it (unless they want to do mumbo-jumbo thangs, in which case that's not my problem anymore !-). What I want is to prevent client code to accidentally mess with it, and have strange bugs that they may have hard time to fix. At the same time, I want to have the cleanest syntax for the subclass declaration. In fact, in most cases, the client code should not have much more to do than defining a handfull of class attributes to end up with a taylor-made fully functional subclass. Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > A few examples: > - A statement is different from an expression (2 special cases instead > of one general case). > - You can't use statements in a lambda Good reason to remove lambda, let's do this asap. > - to get the length of a sequence, you use len(seq) instead of seq.len() I can see nothing wrong with this. seq.__len__() works equally well. > - to call objects attributes by name, you use [get|set]attr(obj, name > [,value]) instead of obj.[get|set]attr(name [,value]) this is the same as above. And I can see nothing wrong with this. This is not a special case but syntax sugar. If you feel more comfortable use the following: seq.__getattribute__('append') > - if x is a class attribute of class A and a is an instance of A, > a.x=anyvalue create a new instance attribute x instead of modifying A.x How is this a wart? Do you understand mutable and immutable objects? In [7]: class A(object): ...: a = {} ...: b = 5 ...: In [8]: a = A() In [9]: b = A() # Modifying an immutable object yields a new object, thus a new binding In [10]: a.b = 3 In [11]: b.b Out[11]: 5 # Modyfing a mutable object doesn't change the original binding: In [12]: a.a['a'] = 4 In [13]: b.a Out[13]: {'a': 4} It would be a wart if it was like you thought it should be because the behaviour of objects changed depending on where they happend to be. > - sequence methods that modify the sequence in place return None instead > of returning self - ok, I know the rational for this one, but I still > dont like it, and still count it as a special case since when using a > 'destructive' sequence method I can't chain it with non-destructive > method calls. This has nothing to do with special cases... Your countless special cases are coming out to be things you didn't really understand about python. > - object.__getattr__ (if it exists...) is called only when attribute > name is not found. object.__setattr__ (if it exists...) is always called. This is because of the new object model. Agree here, there should be only one: __getattr__ or __getattribute__. > - functions are not methods functions are functions and methods are functions that take the instance of the object as their first argument. Anyway discussion is ongoing to remove the bound/unbound difference. Though you can actually do this: In [14]: class A(object): : def foo(self, a): : print "hello world" : In [15]: a = A() In [16]: a.foo(1) hello world In [17]: def baz(): : KeyboardInterrupt In [17]: def baz(self): : print "hello world" : In [18]: a.foo = baz.__get__(a) In [19]: a.foo() hello world > - old-style classes vs new-style classes Agreed. Backwards compatibility wins here. Again Python 3k will remove this. Of all your points I agreed on only 3 or 4. This strikes me as a very well thought out language that in 15 years managed to only get 3 or 4 special cases. > Also, Python enforce some coding style (indentation) but not some others > (capitalization for example). So you always have to check, on a lib by you are mixing oranges and apples here. > lib base, what style has been used (I personnaly don't give a damn > whether I use underscore_all_lower or mixedCaps, but consistency is > useful, even more when there's such a huge stdlib). Worst, the base > class for new style classes is all lower ('object') when the usual > convention is to use CamelCase for classes. Python standard library is consistent with this style. The only library I am aware of that doesn't follow this style is wxPython with wax, and I always discurage every python developer to use this library for this very reason. I can agree with you here, but this is not a special case. > I'm not able to count them all, since a good part of them are not carved > in my poor little brain - I just deal with them day after day. I love You are not able to count them all since there are almost not special cases. But many things that could be done in a better way (this is for sure, python is far from perfect, but it 'sucks' a lot less then everything else). -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.3.8 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de -- http://mail.python.org/mailman/listinfo/python-list
Accessing the contents of a 'cell' object from Python
Having poked around a little bit, I found there doesn't appear to be any way to get at the contents of a cell object from Python. It's not the sort of thing that one needs to be doing very frequently, but I've run into a few situations recently where it would be really useful from a debugging standpoint. You can get at a cell object containing a given value by making a quick closure and looking at the func_closure attribute: (lambda x: lambda: x)(some_value).func_closure[0] but there's not anything we can easily do with that object to find out what it's pointing at. The str() representation helpfully tells us the id of the contained value, but I'm not aware of a way to get at an object given its id [1]. So I thought it might be useful to add such a method to the cell object type. Attached is a sample patch that does so (against python2.4). Does this look like the sort of thing that would be useful to anyone else? How does one go about getting small changes like this into Python anyway? -- paul [1] Yes, the id is the object's pointer in cPython, but even I don't think it would be a good idea to allow accessing an object via the id, even if it's possible. :) diff -Naur python2.4-2.4dfsg/Objects/cellobject.c python2.4-2.4dfsg-pik2/Objects/cellobject.c --- python2.4-2.4dfsg/Objects/cellobject.c 2001-08-29 17:51:00.0 -0600 +++ python2.4-2.4dfsg-pik2/Objects/cellobject.c 2005-03-15 14:21:02.389725784 -0700 @@ -86,6 +86,13 @@ return 0; } +static PyMethodDef cell_methods[] = { + {"value", (PyCFunction)PyCell_Get, METH_NOARGS, + "Return the value stored by the cell" + }, + {NULL} /* sentinel */ +}; + PyTypeObject PyCell_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, @@ -111,4 +118,9 @@ 0, /* tp_doc */ (traverseproc)cell_traverse,/* tp_traverse */ (inquiry)cell_clear,/* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + cell_methods, /* tp_methods */ }; -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Martin Franklin a écrit : Tim Daneliuk wrote: In-Reply-To: <[EMAIL PROTECTED]> (snip) Of course we users will complain about removals, but we'll knuckle down and take our medicine eventually ;-) Except that in this case, removal will also complicate code in some cases. Consider this fragment of Tkinter logic: UI.CmdBtn.menu.add_command(label="MyLabel", command=lambda cmd=cmdkey: CommandMenuSelection(cmd)) In this case you perhaps should try using a class like so:- UI.CmdBtn.menu.add_command(label="MyLabel", command=CommandMenuSelectionCallback(cmdkey)) Where CommandMenuSelectionCallback is a class like so: class CommandMenuSelectionCallback: def __init__(self, key): self.key = key def __call__(self): print self.key Looks like Java. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python becoming less Lisp-like
Valentino Volonghi aka Dialtone a écrit : Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: It is actually. Ruby's syntax is mostly consistent and coherent, and there is much less special cases than in Python. I'd be glad to know which special cases are you referring to. A few examples: - A statement is different from an expression (2 special cases instead of one general case). - You can't use statements in a lambda - to get the length of a sequence, you use len(seq) instead of seq.len() - to call objects attributes by name, you use [get|set]attr(obj, name [,value]) instead of obj.[get|set]attr(name [,value]) - if x is a class attribute of class A and a is an instance of A, a.x=anyvalue create a new instance attribute x instead of modifying A.x - sequence methods that modify the sequence in place return None instead of returning self - ok, I know the rational for this one, but I still dont like it, and still count it as a special case since when using a 'destructive' sequence method I can't chain it with non-destructive method calls. - object.__getattr__ (if it exists...) is called only when attribute name is not found. object.__setattr__ (if it exists...) is always called. - functions are not methods - old-style classes vs new-style classes Also, Python enforce some coding style (indentation) but not some others (capitalization for example). So you always have to check, on a lib by lib base, what style has been used (I personnaly don't give a damn whether I use underscore_all_lower or mixedCaps, but consistency is useful, even more when there's such a huge stdlib). Worst, the base class for new style classes is all lower ('object') when the usual convention is to use CamelCase for classes. Please note that you wrote "much less" which means there are probably so many that you weren't able to count them. I'm not able to count them all, since a good part of them are not carved in my poor little brain - I just deal with them day after day. I love Python and find it one of the best languages around, but the truth is that it has warts - like any other language - and no one can honnestly deny it. Some are on the way to disappear (the type unification is a good thing in intself, even if it actually leads to having 2 more or less compatible object models...) Regards, Bruno -- http://mail.python.org/mailman/listinfo/python-list
Re: compiled open source Windows lisp (was Re: Python becoming less Lisp-like)
"Brandon J. Van Every" <[EMAIL PROTECTED]> writes: > Last I looked, 2 years ago?, there were no compiled, open source > lisps that ran on Windows. Has this changed? GCL (formerly known as KCL and ACL) has been around since 1984, and has been available on Windows since 2000. ECL (another KCL derivative) has been available since about 1990. Corman Common Lisp only runs on Windows, and has been available since 1998. There might be others; those are off the top of my head. I am also not counting here any Lisp implementations that ran on Windows under the Cygwin support; just native ones. Historically, compiled open-souce Lisp implementations have been available since the 1960s. All this information has been available in FAQs and on many web pages since forever. -- http://mail.python.org/mailman/listinfo/python-list
GUI toolkit question
I'm building an app that operates on tuples (typically pairs) of hierarchical structures, and i'd like to add a GUI to display my internal representation of them, and simplify manipulations/operations on them. My requirements are: 1) Draw a single 3D representation of the hierarchies, and the connections between them. 2) All objects must be interactive. That is, they should have left/middle/rightClick behavior; they must be draggable (with rubber band behavior of their conncections); the user should be able to highlight a set of them, associate them as a group, then execute some group operation. 3) I don't need very fancy stuff from the normal widgets. Just menus, a few buttons, dialog boxes, etc. 4) Don't need complex 3D behavior. 5) Don't need to ever run on Windows, just *nix. 6) May eventually need to either compile the Python, or port part/all of it to C++. I started looking into Qt, Wx, Blender, etc, but don't even know if i have the right questions in mind. Any thoughts, considerations, recommendations would be much appreciated. thanks in advance, Eric -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils setup ignoring scripts
Quoting Raseliarison nirinA <[EMAIL PROTECTED]>: > Jack wrote: > > No, I'm referring to bin/foobar, as specified > > in "scripts = ['bin/foobar']". > > yes i'm deadly wrong and should refuse the > temptation to guess! > and ougth to read clearly the post. > so, you want the script foobar included in your package? > what command are you issueing? The tool I'm developing has two python packages (root and 'foobar' in my earlier email), and one script. I want to package up the packages and the script so that when an installer installs, he gets the two packages and the script. I created the package as "python ./setup.py sdist". > > does this include the file? > python setup.py sdist No, that's what I tried. > as you use Python22 on RH9, maybe: > python setup.py bdist_rpm --install-script foobar Is install-script really needed? I would have thought that specifying setup( ... scripts = [...] ...) would suffice, based on the python docs. Jack This message was sent using IMP, the Internet Messaging Program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Boo who? (was Re: newbie question)
Grant Edwards wrote: That seems to imply that you think market sucess == technical merits. Unless you mean that Prothon was a technical failure rather than a market-share failure... As Prothon never got as far as an alpha stage product, I don't think you could call it a technical success. It may well not have been a technical failure, as it didn't get far enough to become one, but it certainly was NOT a technical success. -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert python to exe
exemaker and bdist, too: http://effbot.org/downloads/index.cgi/exemaker-1.2-20041012.zip/README http://www.python.org/doc/2.2.3/dist/creating-wininst.html RM wrote: > Does cx_Freeze pack all dependencies? Would te resulting files(s) be > able to run on a Linux machine that does not have Python installed? If > not, what alternatives are there to accomplish that? Is the McMillan > installer still being maintained? Does it work for GUI applications? > > -Ruben > > Stephen Thorne wrote: > > On 13 Mar 2005 14:31:53 -0800, [EMAIL PROTECTED] > > <[EMAIL PROTECTED]> wrote: > > > Hi > > > > > > I have a python script under linux, I wonder if I can be converted > to > > > an executable or not? > > > > Yes, you can use cx_Freeze. > > > > Regards, > > Stephen Thorne -- http://mail.python.org/mailman/listinfo/python-list
Re: Boo who? (was Re: newbie question)
Terry Reedy wrote: "Luis M. Gonzalez" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] ... It is as important and "python related" as other projects such as PyPy, Stackless, but I think this is silly. PyPy is an alternate implementation of Python, not a different language. Stackless is a compiled extension, like many others, that works with the standard implementation or maybe still a minor modification thereof. Where would you classify Pyrex? Language boundaries are somewhat artificial, but Pyrex clearly doesn't intend to be as similar to Python as PyPy does. Still, it's close enough to almost be considered a language extension. If one wanted to bother, one could probably construct a language slightly more similar to Python than Pyrex, and another slightly less similar. This couldn't continue forever, as the domain is discrete. But it could go a long!! way. One could probably arrive at a graded series of languages between Python and C (probably along several different transformation vectors). And slightly off to the side would be Python 2.5 and C2006 (or whatever year the next version is defined). But some of the languages in the series would be more similar to current Python than is Python 2.5. So. A language is a series of specifications made at differnt times, and has a fuzzy surround of implementations which nearly meet the specifications. And this is true even where one of the implementations itself is designated as the primary specification (because people will argue that this feature or that is wrongly implemented). Still, even given all that, Boo is clearly outside the area that is Python. (One could have a "minimal acceptable distance" which could be thought of as running correctly most of the programs that the core language would run correctly.) -- http://mail.python.org/mailman/listinfo/python-list
Re: compiled open source Windows lisp (was Re: Python becoming less Lisp-like)
Brandon J. Van Every <[EMAIL PROTECTED]> wrote: >James Graves wrote: >> >> If you want to do application development, Common Lisp is where it's >> at, no doubt about it. There are more and better libraries for CL >> these days, and they are easier to install and manage with tools like >> ASDF. Multiple open-source implementations, covering the most popular >> platforms (Windows, Linux, Mac). > >Last I looked, 2 years ago?, there were no compiled, open source lisps that >ran on Windows. Has this changed? Yes. GCL compiles to C first. And it has been ported to Windows. It isn't fully ANSI compliant yet, though they are working on that. I haven't had to try that yet. There's talk about a port of SBCL to Windows. But I don't know what progress has been made on that front. But coverage in this area (compiled CL) is a bit thin, I'll admit. James Graves -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert python to exe
Does cx_Freeze pack all dependencies? Would te resulting files(s) be able to run on a Linux machine that does not have Python installed? If not, what alternatives are there to accomplish that? Is the McMillan installer still being maintained? Does it work for GUI applications? -Ruben Stephen Thorne wrote: > On 13 Mar 2005 14:31:53 -0800, [EMAIL PROTECTED] > <[EMAIL PROTECTED]> wrote: > > Hi > > > > I have a python script under linux, I wonder if I can be converted to > > an executable or not? > > Yes, you can use cx_Freeze. > > Regards, > Stephen Thorne -- http://mail.python.org/mailman/listinfo/python-list
Re: compiled open source Windows lisp
On Tue, 15 Mar 2005 23:29:04 +0100, Fraca7 <[EMAIL PROTECTED]> wrote: > I don't think so. I recently (about 2 months ago) started to want to > learn Lisp (didn't go far for now) and wanted to find a Windows > impl, to evaluate "cross-platformability". The only open source/free > software Lisp interpreter Compiler, not interpreter. All available Common Lisp implementations are compilers - one (CLISP) compiles to bytecode while all others compile to machine code. > I found was Common Lisp under Cygwin. "Common Lisp" is not an implementation but a language (defined by an ANSI standard). You're probably talking about CLISP (which is an implementation of the language Common Lisp) which runs on Cygwin. > Not exactly win32 native. But good enough, I think. Native Win32 versions of CLISP are available. And there's also ECL. Also, if you're just learning CL it's perfectly fine to use the trial versions of AllegroCL or LispWorks. Why do you need an open source implementation to learn a language? Cheers, Edi. -- Lisp is not dead, it just smells funny. Real email: (replace (subseq "[EMAIL PROTECTED]" 5) "edi") -- http://mail.python.org/mailman/listinfo/python-list