ANN: Pygments 0.8 released
I'm happy to announce the release of version 0.8 of the Pygments syntax highlighter. Download it from http://cheeseshop.python.org/pypi/Pygments, or look at the demonstration at http://pygments.org/demo. The new features changelog for 0.8 is: * Lexers added: o Haskell, thanks to Adam Blinkinsop o Redcode, thanks to Adam Blinkinsop o D, thanks to Kirk McDonald o MuPad, thanks to Christopher Creutzig o MiniD, thanks to Jarrett Billingsley o Vim Script, by Tim Hatch * The CSharpLexer now is Unicode-aware, which means that it has an option that can be set so that it correctly lexes Unicode identifiers allowed by the C# specs. * Added a RaiseOnErrorTokenFilter that raises an exception when the lexer generates an error token, and a VisibleWhitespaceFilter that converts whitespace (spaces, tabs, newlines) into visible characters. * The ReST lexer now automatically highlights source code blocks in .. sourcecode:: language and .. code:: language directive blocks. * Improved the default style (thanks to Tiberius Teng). The old default is still available as the emacs style (which was an alias before). * The get_style_defs method of HTML formatters now uses the cssclass option as the default selector if it was given. The updated documentation and the full changelog can be found, as always, at http://pygments.org/docs. Happy highlighting, Georg -- Pt! Schon vom neuen GMX MultiMessenger gehört? Der kanns mit allen: http://www.gmx.net/de/go/multimessenger -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Usage of the __and__ method
On May 30, 10:11 pm, theju [EMAIL PROTECTED] wrote: Hello all, I've two objects (both instances of a class called Person) and I want to use the __and__ method and print the combined attributes of the two instances. To be precise, here is my code class Person: def __init__(self,name): self.name = name def print_name(self): print self.name def __and__(self,other): self.name = '%s AND %s' %(self.name,other.name) return self.name p = Person(John) q = Person(George) r = p and q print r.print_name() Try: class Person(object): def __init__(self, name): self.name = name def __and__(self, other): return '%s AND %s' % (self.name, other.name) p = Person(John) q = Person(George) r = p q print r (1) A getter method (like your print_name method) is usually not needed, just access the attribute of the instance. Like, print p.name (2) I doubt that you want the __and__ special method to alter the name attribute of an instance. (3) You want to use the '' operator to dispatch to the __and__ method; __and__ is typically used for Numeric objects. (4) You misunderstood how the 'and' operator is used. The expression 'p and q' causes p to be evaluated; if p is false, its value is returned; otherwise q is evaluated and its value is returned. -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
Oops! guess I should have tested my rather hasty complaint about executable containers. This is nice: def a(): return 'b' def b(): print 'polly! wakey wakey' c = {} c['a'] = b c[a()]() #works! c[a()]() is a switch statement with an amorphous selector- very handy in its own right. But, using a() as a generator would be more expressive. This seems to work: c = [a,a] [d() for d in c] But that still isn't as simple or as direct as: c[:]() Which would you rather explain to a 12-year-old writing code for the first time? I still want my executable container though. Would love to so this h[search('a//f')]() # where a//f is like an Xpath // search for leaves -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
Warren Stringer wrote: c[:]() # i wanna TypeError: 'tupple' object is not callable c[:] equals c (in expressions), so c[:]() is equivalent to c() c[:][0] # huh? a c[:][0] is c[0] is a [i() for i in c] # too long and ...huh? a b [None,None] #-- [None, None] is the result of the operation. for i in c: i() If that is too long, reconsider what you are doing. -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Listbox - Different Text colors in one listbox
[EMAIL PROTECTED] wrote: On May 29, 2:02 pm, [EMAIL PROTECTED] wrote: Hi, Is it possible to havedifferentitems in alistboxindifferentcolors? Or is it justonecolor for all items in alistbox? Thanks Rahul from Tkinter import * root = Tk() l = Listbox(root) l.pack() for x in range(10): l.insert(END, x) l.itemconfig(2, bg='red', fg='white') l.itemconfig(4, bg='green', fg='white') l.itemconfig(5, bg='cyan', fg='white') root.mainloop() You can _only_ configurate 'background', 'foreground', 'selectbackground', 'selectforegroud', not font :( Live and learn, - was not aware you could do this - thanks, nice one. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
projecktzero [EMAIL PROTECTED] wrote: On May 30, 12:36 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote: Maric Michaud [EMAIL PROTECTED] wrote: Typist is fine, although MCP that I am, I tend to think of typist as female... - Hendrik What does being a Microsoft Certified Professional(MCP) have to do with thinking of a typist as female? =) Yikes! - Male Chauvinist Pig... ;-) - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a standard way to install egg-files under windows ?
John Nagle wrote: Diez B. Roggisch wrote: Stef Mientki schrieb: hello, after 4 months playing around with Python, and I still have troubles with egg files. Sometimes it works, sometimes it doesn't. If I google on python egg, I get lost of links, which contains huge pages of information, and I'm totally scared off. .egg files are actually .zip files. So you can rename them to .zip and unpack them where they need to go. This is usually easier than debugging easy_install. John Nagle thanks guys, I'm slowly getting the picture. Now knowing it's a zip file, and trying several egg-files through easy_install, I noticed different things, - sometimes the egg is unzipped and placed in the site-package directory - sometimes it's just copied (unzipped) to the site-package directory. My first conclusion that egg-installation didn't work sometimes, has probably to do with version conflicts between the already installed libs and the new to install libs, but I guess that's the benefit of open source ;-) So if that's all, the renaming to .zip might be a less obscure way of working. cheers, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
[EMAIL PROTECTED] wrote: On May 31, 12:31 am, Warren Stringer [EMAIL PROTECTED] wrote: This is inconsistent: why does c[:][0]() work but c[:]() does not? Why does c[0]() has exactly the same results as c[:][0]() ? Moreover, c[:][0]() implies that a slice was invoked It's not inconsistent, but [:] probably does something different than you think it does. All it does is create a copy (not in general, but at least if c is a list or a tuple). Since in your example c is a tuple and tuples are immutable, making a copy of it is essentially useless. Why not just use the original? I.e. instead of c[:] you could just write c. That's why c[:][0]() has exactly the same effect as c[0] (), although the former is likely to be slightly slower. An extremely minor point (and implementation specific), but while [:] will copy a list it won't copy a tuple. Likewise 'list(aList)' will always copy a list, 'tuple(aTuple)' won't copy a tuple. So in this particular example the slice is completely redundant. c is c[:] is c[:][:][:][:] is tuple(c) True -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble with wxPython intro
On May 30, 11:41 pm, Anthony Irwin [EMAIL PROTECTED] wrote: Daniel Gee wrote: I'm trying to learn WxPython with the tutorial: http://wiki.wxpython.org/Getting_Started I'm a wxPython beginner too, but instead of Anthony Irwin's suggestions, I think you should delete these two lines: ID_ABOUT=101 ID_EXIT=110 and use: wx.ID_ABOUT wx.ID_EXIT throughout the body of your program. As far as I can tell, there is no reason for you to be manually setting your own id's (is there ever?). Instead, you can use the ids in the wx module. In addition, I suggest you never use wx.PySimpleApp(). If you create your own app class, you can send the error messages to the console. Instead of always seeing a window that flashes at you briefly and being left with no clue what went wrong, you can at least see an error message and a line number in the console. Here's how you would do that: - import wx class MyFrame(wx.Frame): def __init__(self, mytitle): wx.Frame.__init__(self, None, title= mytitle) class MyApp(wx.App): def __init__(self): wx.App.__init__(self, redirect=False) app = MyApp() window = MyFrame(Testing) window.Show() app.MainLoop() -- By setting redirect=False in wx.App.__init__(), the errors will be sent to the console. -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble with wxPython intro
That's so simple I'm embarrassed. I should have noticed the change from the example before to this one. It works now, thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On Wed, 30 May 2007 23:23:22, Warren Stringer [EMAIL PROTECTED] wrote def a(): return 'b' def b(): print 'polly! wakey wakey' c = {} c['a'] = b c[a()]() #works! (typo correction for other easily-confused newbies like myself) I think you mean , | c['a']() #works! ` -- Doug Woodrow -- http://mail.python.org/mailman/listinfo/python-list
Researcher/Lecturer Position at MODUL University Vienna
I would like to draw your attention to the following open position at the Department of New Media Technology of MODUL University Vienna (under accreditation): * Geospatial, Semantic and Web 2.0 Technologies http://www.ecoresearch.net/download/nmt-tech.pdf MODUL University Vienna is a recently founded private university on top of Kahlenberg, a scenic hill overlooking Vienna. The university combines a strong academic foundation with state-of-the-art curricula and a commitment to innovation and sustainability as key drivers of success in a dynamic and knowledge-based society. Appointees are expected to make significant contributions to the university's teaching and research activities. I would be very grateful if you could forward this information to potential candidates who might be interested in this offer. - Prof. Arno Scharl Know-Center Graz University of Technology Inffeldgasse 21a, A-8010 Graz (t) +43-316-8739257 (e) [EMAIL PROTECTED] - Sent by: Johanna Ostertag Institute for Tourism and Leisure Studies Vienna Unversity of Economics and Business Administration -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble with wxPython intro
On May 31, 1:56 am, 7stud [EMAIL PROTECTED] wrote: By setting redirect=False in wx.App.__init__(), the errors will be sent to the console. Hmmm...I just read a note I scribbled in the margin of my book that says setting redirect=False sends the error messages to the console on Mac and Windows. Are you using one of those operating systems? If not, what os are you using, and do you get errors messages in the console when using wx.PySimpleApp()? Thanks -- http://mail.python.org/mailman/listinfo/python-list
qt doevent
Hello at all I try to use qt , but i have problem, i don't find the command like wx.Yield() in wx or doevent in vb. Can you tell me the same command in qt Regards Luca -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On Thu, 31 May 2007 08:57:56, Douglas Woodrow [EMAIL PROTECTED] wrote On Wed, 30 May 2007 23:23:22, Warren Stringer [EMAIL PROTECTED] wrote def a(): return 'b' def b(): print 'polly! wakey wakey' c = {} c['a'] = b c[a()]() #works! (typo correction for other easily-confused newbies like myself) I think you mean , | c['a']() #works! ` Oh no, I get it, you meant... , | c['b'] = b | c[a()]() #works! ` ...or was it?:- , | def a(): return 'a' ` -- Doug Woodrow -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
In [EMAIL PROTECTED], Warren Stringer wrote: Oops! guess I should have tested my rather hasty complaint about executable containers. This is nice: def a(): return 'b' def b(): print 'polly! wakey wakey' c = {} c['a'] = b c[a()]() #works! c[a()]() is a switch statement with an amorphous selector- very handy in its own right. But, using a() as a generator would be more expressive. This seems to work: c = [a,a] [d() for d in c] If you are using the list comprehension just for the side effect of calling `d` then consider this bad style. You are building a list of `None` objects just to have a cool one liner then. But that still isn't as simple or as direct as: c[:]() Which would you rather explain to a 12-year-old writing code for the first time? for func in funcs: func() Because it is explicit and readable and matches the english description for every function in functions: call that function very closely while a list comprehension or your perlish line noise is much more magic to explain and harder to remember. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: qt doevent
On Thursday 31 May 2007 9:04 am, luca72 wrote: Hello at all I try to use qt , but i have problem, i don't find the command like wx.Yield() in wx or doevent in vb. Can you tell me the same command in qt QApplication.processEvents() Phil -- http://mail.python.org/mailman/listinfo/python-list
Embedding objects( txt, doc) into excel using python
Hi, I want to embed a txt document into an excel using python. Here is my code, but i get an error message === Traceback (most recent call last): File C:\Documents and Settings\kusumap\Desktop\Girish.py, line 7, in ? worksheet.OLEObjects.Add(Filename=C:\Documents and Settings \kusumap\My Documents\desktop.ini, Link=False,DisplayAsIcon=True, IconFileName=packager.exe, IconIndex=0, IconLabel=C:\Documents and Settings\kusumap\My Documents\desktop.ini).Select AttributeError: 'function' object has no attribute 'Add' === import win32com.client ExcelApp = win32com.client.Dispatch(Excel.Application) ExcelApp.visible = 1 workbook = ExcelApp.Workbooks.open(C:\Software\New Microsoft Excel Worksheet.xls) worksheet = workbook.Activesheet #worksheet.OLEObjects.Add(Filename=C:\Documents and Settings\p\My Documents\desk.txt, Link=False,DisplayAsIcon=True, IconFileName=packager.exe, IconIndex=0, IconLabel=C:\Documents and Settings\p\My Documents\desk.txt).Select Can anyone please whtz the problem with the code and how to overcome the same. Thanks Girish S -- http://mail.python.org/mailman/listinfo/python-list
Re: Usage of the __and__ method
Thank you folks for reminding me that the logical AND cannot be over- ridden and that the __and__ method represents the bit-wise AND operation. Thank You Thejaswi Puthraya http://thejuhyd.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Good Python style?
Hi, I found the following quite cryptic code, which basically reads the first column of some_file into a set. In Python I am used to seeing much more verbose/explicit code. However, the example below _may_ actually be faster than the usual for line in ... Do you consider this code good Python style? Or would you recommend to refrain from such complex single-line code?? Thanks! Andreas inp = resource(some_file) # read first entries of all non-empty lines into a set some_set = frozenset([line.split()[0] for line in \ filter(None, [ln.strip() for ln in inp])]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Python style?
What if I want to process lines.In this case I would have to iterate over the set and do the processing On 5/31/07, Andreas Beyer [EMAIL PROTECTED] wrote: Hi, I found the following quite cryptic code, which basically reads the first column of some_file into a set. In Python I am used to seeing much more verbose/explicit code. However, the example below _may_ actually be faster than the usual for line in ... Do you consider this code good Python style? Or would you recommend to refrain from such complex single-line code?? Thanks! Andreas inp = resource(some_file) # read first entries of all non-empty lines into a set some_set = frozenset([line.split()[0] for line in \ filter(None, [ln.strip() for ln in inp])]) -- http://mail.python.org/mailman/listinfo/python-list -- Regards-- Rishi Pathak -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding objects( txt, doc) into excel using python
Girish wrote: I want to embed a txt document into an excel using python. I didn't know people still did that! Still, each to his own ;) Here is my code, but i get an error message === Traceback (most recent call last): File C:\Documents and Settings\kusumap\Desktop\Girish.py, line 7, in ? worksheet.OLEObjects.Add(Filename=C:\Documents and Settings \kusumap\My Documents\desktop.ini, Link=False,DisplayAsIcon=True, IconFileName=packager.exe, IconIndex=0, IconLabel=C:\Documents and Settings\kusumap\My Documents\desktop.ini).Select AttributeError: 'function' object has no attribute 'Add' === Well done for providing reproducible code, by the way. It's amazing how many people expect us to deduce code from tracebacks! Two things: 1) You need to use raw strings for your path names or to double-up the slashes. By good fortune, you don't seem to be using any actual special characters (\n, \r, \t etc.) but you won't always be so lucky! 2) As the error suggests, OLEObjects is in fact a method, not an container. Slightly more concise screen dump: dump Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import win32com.client xl = win32com.client.Dispatch (Excel.Application) ws = xl.Workbooks.Add ().ActiveSheet print repr (ws.OLEObjects) bound method _Worksheet.OLEObjects of win32com.gen_py.Microsoft Excel 11.0 Object Library._Worksheet instance at 0x24646440 o = ws.OLEObjects () o win32com.gen_py.Microsoft Excel 11.0 Object Library.OLEObjects instance at 0x24648240 o.Add bound method OLEObjects.Add of win32com.gen_py.Microsoft Excel 11.0 Object Library.OLEObjects instance at 0x24648240 /dump As you can see, the ws.OLEObjects is a bound method, ie a function within the _Worksheet class. It seems to return a value which is an OLEObjects instance, which itself seems to have an .Add method. Although I could forage in the docs, I just tried it out at the interpreter. You can do the same if you want! TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Python style?
On May 31, 2007, at 2:59 AM, Andreas Beyer wrote: Hi, I found the following quite cryptic code, which basically reads the first column of some_file into a set. In Python I am used to seeing much more verbose/explicit code. However, the example below _may_ actually be faster than the usual for line in ... Do you consider this code good Python style? Or would you recommend to refrain from such complex single-line code?? Thanks! Andreas inp = resource(some_file) # read first entries of all non-empty lines into a set some_set = frozenset([line.split()[0] for line in \ filter(None, [ln.strip() for ln in inp])]) I don't know about style, but I find it much harder to read than this: some_set = frozenset(line.split()[0] for line in inp if len(line.strip())) ...which I *think* is equivalent, but less complicated. regards, Michael --- (do (or (do (not '(there is no try))) ())) -- http://mail.python.org/mailman/listinfo/python-list
Re: Anyone else has seen forrtl: error (200) ...
Jason schrieb: Forrtl indicates that your script is running a Fortran library or program. Remember that Python exceptions only apply during Python. If a Fortran DLL performs a divide-by-zero error, or accesses invalid memory, it will kill the interpreter instead of throwing a Python exception. With Compaq Visual Fortran, the Fortran library calls can kill your entire program if a function receives an invalid value. (Try raising a negative real number to a fractional exponent, for example.) I'd guess that the Fortran code is intercepting the CTRL-C signal and killing the running script. Without knowing anything about your script and the library calls it makes, I can't give you much advice. There may be little that you can do, especially if you don't have the Fortran source code in question and/or can't recompile it. Maybe someone with some Fortran/Python experience can assist you. --Jason Thanks for that hint. Indeed a extension I'm using in my script uses matlab, and matlab uses (I'm quite sure) fortran. But does that mean, if a fortran dll is loaded, a underlying software layer passes Ctrl+C to the fortran dll instead to python? (I can reproduce that in doing a ctrl+c while my script is currently at time.sleep(10) Thanks, Alexander -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
Warren Stringer wrote: I want to call every object in a tupple, like so: [snip examples] Why? Because I want to make Python calls from a cell phone. Every keystroke is precious; even list comprehension is too much. If you are going to do this just a few times in your program, I cannot help. But: If you want to do it several times, perhaps you have space for an initial class definition, like so: class CallableList(list): def __call__(self,*args,**kwargs): return [f(*args,**kwargs) for f in self] def a(): return 'a called' def b(): return 'b called' c = CallableList([a,b])() You might want to trim the class to fit your needs, perhaps use a shorter name, and perhaps you don't need to handle arguments. Can the class be placed in a module, so that it only needs to be typed once in your application? /MiO -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Joe Riopel [EMAIL PROTECTED] writes: Using camel case instead of the under_score means less typing. I am lazy. fooBar foo_bar Each requires exactly the same number of key strokes when I do the math. (Too lazy to explain further...) -- http://mail.python.org/mailman/listinfo/python-list
Re: file / module / package - import problem
aspineux wrote: import os.path file=open(os.path.join(os.path.dirname(__file__), 'hauteur.yaml')) Thanks that worked ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
Il Wed, 30 May 2007 11:48:47 -0700, Warren Stringer ha scritto: [cut] c[:] is c True BTW, I couldn't understand your concern. Are you sure you really need many functions, and not just one function with different parametrs? In such a case you could just use the builtin func map() to achieve the very same result. Or you could define a function of your own like: def call_elems(iterable): for elem in iterable: elem() and just do call_elems(c) when needed. -- Alan Franzoni [EMAIL PROTECTED] - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Python style?
On Thu, 31 May 2007 09:59:07 +0200, Andreas Beyer wrote: Hi, I found the following quite cryptic code, which basically reads the first column of some_file into a set. In Python I am used to seeing much more verbose/explicit code. However, the example below _may_ actually be faster than the usual for line in ... Do you consider this code good Python style? Or would you recommend to refrain from such complex single-line code?? Thanks! Andreas inp = resource(some_file) # read first entries of all non-empty lines into a set some_set = frozenset([line.split()[0] for line in \ filter(None, [ln.strip() for ln in inp])]) It's a little complex, but not excessively so. Any more, and it would probably be too complex. It would probably be easier to read with more readable names and a few comments: some_set = frozenset( # ... from a list comp of the first word in each line [line.split()[0] for line in # ... each line has leading and trailing white space # filtered out, and blanks are skipped filter(None, # strip whitespace and filter out blank lines [line.strip() for line in input_lines] )]) Splitting it into multiple lines is self-documenting: blankless_lines = filter(None, [line.strip() for line in input_lines]) first_words = [line.split()[0] for line in blankless_words] some_set = frozenset(first_words) As for which is faster, I doubt that there will be much difference, but I expect the first version will be a smidgen fastest. However, I'm too lazy to time it myself, so I'll just point you at the timeit module. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
non standard path characters
A kind user reports having problems running the reportlab tests because his path has non-ascii characters in it eg .\Mes documents\Mes Téléchargements\Firefox\... somewhere in the tests we look at the path and then try and convert to utf8 for display in pdf. Is there a standard way to do these path string conversions? Paths appear to come from all sorts of places and given the increasing use of zip file packaging it doesn't seem appropriate to rely on the current platform as a single choice for the default encoding. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Python style?
On May 31, 3:59 am, Andreas Beyer [EMAIL PROTECTED] wrote: Hi, I found the following quite cryptic code, which basically reads the first column of some_file into a set. In Python I am used to seeing much more verbose/explicit code. However, the example below _may_ actually be faster than the usual for line in ... Do you consider this code good Python style? Or would you recommend to refrain from such complex single-line code?? Thanks! Andreas inp = resource(some_file) # read first entries of all non-empty lines into a set some_set = frozenset([line.split()[0] for line in \ filter(None, [ln.strip() for ln in inp])]) I think it would be more readable if you would take the filter out of the list comprehension, and the list comprehension out of the set. inp = resource(some_file) stripped_lines = (ln.strip() for ln in inp) splitted_lines = (line.split()[0] for line in stripped_lines if line) some_set = frozenset(splitted_lines) -- http://mail.python.org/mailman/listinfo/python-list
Re: speeding things up with C++
Thanks this is good news. I think my C/C++ background is sufficient to manage to figure things out if I RTFM carefully. Basically I want to pass in a Python list of integer tuples, create an STL container full of equivalent tuples, apply some processor- intensive algorithm to said list of tuples, and finally poke the results back into another Python list of integer tuples and return it to the calling Python environment. Data structures are well-defind and simple, and the most complex case would be 3-deep nested list, so I will seriously consider figuring out how to do it manually as you suggest. On May 31, 3:04 am, Jorgen Grahn [EMAIL PROTECTED] wrote: On 26 May 2007 02:19:39 -0700, bullockbefriending bard [EMAIL PROTECTED] wrote: ... Essentially, I need to pass a list of 6-tuples containing only integers to my new sadly necessary super-fast compiled language function which i am not looking forward to writing: input: [(1,2,3,4,5,6), (7,8,9,10,11,12),...] and after much thrashing of processor resources, return data which looks like this to the Python calling environment: output: [( (1, 2), (1,), (12,), (13), (1, 7, 11), (9,) ), ( another nested tuple like preceding one ), ] ... However, I hope someone reading this will be able to tell me that I'm being a total pessimist and that in fact it isn't very difficult to do what I want to do using SWIG. You're talking about the actual conversion between Python data structures and C or C++ data structures? That is easy to do even manually, IMHO -- provided a decent C background. Have a look in the Python/C API Reference Manual, and the mapping becomes clear. The PyListObject stuff for example, where there's a C function for every basic operation on lists, and where the elements have the C type PyObject. And so on. Mapping to C is just a matter of walking a nested data structure, where you have a good idea what it is supposed to look like (a list of six-tuples of some kind of numbers). /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Python style?
Steven D'Aprano wrote: It would probably be easier to read with more readable names and a few comments: [...] Splitting it into multiple lines is self-documenting: blankless_lines = filter(None, [line.strip() for line in input_lines]) first_words = [line.split()[0] for line in blankless_words] some_set = frozenset(first_words) Re-writing code so that it is self-documenting is almost always a better approach. Premature optimization is the root of all evil. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: replace the base class
Larry: Using as, I cannot use both Circle and ColorCircle or more like 3DCircle ... at the same time, only one of them. But this is a easy solution in some cases. On 31 mai, 00:25, Matimus [EMAIL PROTECTED] wrote: Hi Martimus, your idea was a good one, I used it to meet my _particular_ needs. I was expecting something more complicate with metaclass, object introspection I used an interface (like in Java, a class with just method that must work in // with anoter class). Finally the replacement of the base class in done with a simple : class ColorCircle(ColorGraphInterface, Circle): graph_base_class=Circle Here is my full working test code class Graph: def plot(self): print 'Graph.plot' class Circle(Graph): def draw(self): print 'Circle.draw' self.plot() class Square(Graph): def draw(self): print 'Square.draw' self.plot() class ColorGraphInterface: graph_base_class=None def plot(self): print 'ColorGraphInterface.plot' self.graph_base_class.plot(self) def draw(self): print 'ColorGraphInterface.draw' self.graph_base_class.draw(self) class ColorCircle(ColorGraphInterface, Circle): graph_base_class=Circle class ColorCircle(ColorGraphInterface, Square): graph_base_class=Square cc=ColorCircle() cc.draw() This is a rather simplistic example, but you may be able to use a mixin class to achieve what you need. The idea is that you write a class that overrides only what is needed to add the new functionality. For you it would be Color. [code] class Graph(object): def _foo(self): print Graph._foo class Color(object): def _foo(self): print Color._foo class Circle(Graph): def bar(self): self._foo() class ColorCircle(Color,Circle): # the order of parent classes is important pass if __name__ == __main__: c1 = Circle() c2 = ColorCircle() c1.bar() #prints: Graph._foo c2.bar() #pritns: Color._foo [/code] You might not have to do anything already. Try this and see if it works: [code] ColorCircle(ColorGraph,Circle): pass [/code] Note that you will probably have to create an __init__ method, and explicitly call the __init__ methods for the base classes. If the __init__ for Circle ends up calling the __init__ method from Graph, you may have issues. That is why the Color mixin that I created inherited from object not Graph. It helps to avoid clashing __init__ methods. Yes I know, super() do a great job for that :-) Matt -- http://mail.python.org/mailman/listinfo/python-list
Python memory handling
Greets, I've some troubles getting my memory freed by python, how can I force it to release the memory ? I've tried del and gc.collect() with no success. Here is a code sample, parsing an XML file under linux python 2.4 (same problem with windows 2.5, tried with the first example) : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared #Using http://www.pixelbeat.org/scripts/ps_mem.py to get memory information import cElementTree as ElementTree #meminfo: 2.3 Mb private, 1.6 Mb shared import gc #no memory change et=ElementTree.parse('primary.xml') #meminfo: 34.6 Mb private, 1.6 Mb shared del et #no memory change gc.collect() #no memory change So how can I free the 32.3 Mb taken by ElementTree ?? The same problem here with a simple file.readlines() #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared del data #meminfo: 11.5 Mb private, 1.4 Mb shared gc.collect() # no memory change But works great with file.read() : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared del data #meminfo: 1.1 Mb private, 1.4 Mb shared gc.collect() # no memory change So as I can see, python maintain a memory pool for lists. In my first example, if I reparse the xml file, the memory doesn't grow very much (0.1 Mb precisely) So I think I'm right with the memory pool. But is there a way to force python to release this memory ?! Regards, FP -- http://mail.python.org/mailman/listinfo/python-list
Re: non standard path characters
I thing you should change the code page before to run the test, doing something like : c:\ chcp 850 c:\ \python.exe ..\test.py look for the good code page for you, maybe 850, 437 or 1230 or 1250 should work Regards On 31 mai, 12:17, Robin Becker [EMAIL PROTECTED] wrote: A kind user reports having problems running the reportlab tests because his path has non-ascii characters in it eg .\Mes documents\Mes Téléchargements\Firefox\... somewhere in the tests we look at the path and then try and convert to utf8 for display in pdf. Is there a standard way to do these path string conversions? Paths appear to come from all sorts of places and given the increasing use of zip file packaging it doesn't seem appropriate to rely on the current platform as a single choice for the default encoding. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
TR: embeded python progam into visual C++ application crash
-Message d'origine- De : fabien.lyon [mailto:[EMAIL PROTECTED] Envoyé : mercredi 30 mai 2007 20:16 À : 'python-list@python.org' Objet : RE: embeded python progam into visual C++ application crash hello, The C++ application uses a python module which wraps commands set for CVS management: checkout, checkin and tag. We used python2.5.1 and Visual C++ 6.0 2.5.1 is compiled with Visual Studio 2005 - I hope you had no problems with VC++ 6.0? The problem we get is: After a good import and definition of python functions we have a random unhandled exception (from python25.dll) when calling python interface function several times. All the python module has been tested using the python IDLE. This the C++ sequence code we used: Py_initialize() Py_Import(moduleName) cvs_init() // cvs view initialisation handled by python script init() cvs_set_tag()// cvs commit and tag handled by python script settag() // the exception occured here Neither Py_initialize nor Py_Import functions exist - so please post actual code. -- Gabriel Genellina Ho sorry you are right (this pb disturbs me too much). Investigation and efforts has been helpfull, so we have found the problem. This is the following description : void InterfaceTestConfigPython_C::InitCVS(CString path_vue_bench_p, CString path_vue_test_p) { PyObject *pArgs= NULL, *pValue= NULL; PyObject *pPathVueBench= NULL, *pPathVueTest= NULL ; //python objects for each python function argument pPathVueBench = PyString_FromString((LPCTSTR)path_vue_bench_p); pPathVueTest = PyString_FromString((LPCTSTR)path_vue_test_p); //python object to collect all arguments pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, pPathVueBench); PyTuple_SetItem(pArgs, 1, pPathVueTest); // python function call pValue = PyObject_CallObject(pFuncInit_m, pArgs); // clean up memory Py_DECREF(pArgs); // process return value if (pValue != NULL) { // clean up memory Py_DECREF(pValue); } // clean up memory Py_DECREF(pPathVueBench ); Py_DECREF(pPathVueTest); } The problem we get come from a wrong code. The last two lines, calling Py_DECREF, are not mandatory and make the python interpreter in a bad day. When the InitCVS() function call Py_DECREF(pArgs) the memory allocated for pPathVueBench and pPathVueTest is free (i guess) because the PyTuple_SetItem(pArgs, 0, pPathVueBench) steals the reference of the python object you add into the tuple pArgs like the python documentation tells. So we have suppressed the last clean up memory in the InitCVS() function and now the program is running as expected. I join the C++ object code if this can help someone. InterfaceTestConfigPython_C.cpp Description: Binary data -- http://mail.python.org/mailman/listinfo/python-list
PEP 8 style enforcing program
Some recent posts about Python programming style got me thinking. Since we have the PEP 8 which gives some guidelines about the style to be used, do we have any program that can check for violations of these guidelines within the source code? I understand that there are a lot of code beautifiers out there, but i haven't seen one specially tailored for Python... Is there even a desire in Python community for a program like this (by Python community I mean the people in this group:) ) ? I think it would be a nice little project for practice and I'd like to do it, but if there is already something like this then I can probably spend my time on something more productive. So, I'd like to hear your opinion on this... There is one thing that I don't understand about PEP 8 - why is using spaces considered more desirable than using tabs for indentation? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
In [EMAIL PROTECTED], frederic.pica wrote: So as I can see, python maintain a memory pool for lists. In my first example, if I reparse the xml file, the memory doesn't grow very much (0.1 Mb precisely) So I think I'm right with the memory pool. But is there a way to force python to release this memory ?! AFAIK not. But why is this important as long as the memory consumption doesn't grow constantly? The virtual memory management of the operating system usually takes care that only actually used memory is in physical RAM. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: ImageMagick Issue
Sick Monkey wrote: When I run the following command: [EMAIL PROTECTED] david.huggins]# identify -format %w '/someDIR/images/david.huggins/100_0264.JPG' From Python interpreter: cmd = identify -format %w test.jpg p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) t = p.stdout.read() p.stdout.close() t '50\n' From command line: [EMAIL PROTECTED]:~$ identify -format %w test.jpg 50 [EMAIL PROTECTED]:~$ Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Each requires exactly the same number of key strokes when I do the math. (Too lazy to explain further...) foo_bar f, o, o, shift + underscore, b, a, r = 8 fooBar f, o, o, shift + b, a, r = 7 -- http://mail.python.org/mailman/listinfo/python-list
file reading by record separator (not line by line)
Dear all, I would like to read a really huge file that looks like this: name1 line_11 line_12 line_13 ... name2 ... line_21 line_22 ... etc where line_ij is just a free form text on that line. how can i read file so that every time i do a read() i get exactly one record up to the next many thanks Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
In [EMAIL PROTECTED], kc wrote: Joe Riopel [EMAIL PROTECTED] writes: Using camel case instead of the under_score means less typing. I am lazy. fooBar foo_bar Each requires exactly the same number of key strokes when I do the math. (Too lazy to explain further...) Let's leave 'foo' and 'ar': 1. B = Shift + B = 2 key strokes. 2. _b = Shift + - and b = 3 key strokes. At least on my keyboard + layout. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
I wanted to also say that this file is really huge, so I cannot just do a read() and then split on to get a record thanks lee On May 31, 1:26 pm, Lee Sander [EMAIL PROTECTED] wrote: Dear all, I would like toreada really hugefilethat looks like this: name1 line_11 line_12 line_13 ...name2 ... line_21 line_22 ... etc where line_ij is just a free form text on that line. how can ireadfileso that every time i do a read() i get exactly onerecord up to the next many thanks Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: non standard path characters
Robin Becker wrote: A kind user reports having problems running the reportlab tests because his path has non-ascii characters in it eg .\Mes documents\Mes Téléchargements\Firefox\... somewhere in the tests we look at the path and then try and convert to utf8 for display in pdf. Is there a standard way to do these path string conversions? Paths appear to come from all sorts of places and given the increasing use of zip file packaging it doesn't seem appropriate to rely on the current platform as a single choice for the default encoding. Zip files contain a bit flag for the character encoding (cp430 or utf-8), see the ZipInfo object in module zipfile and the link (on that page) to the file format description. But I think some zip programs just put the path in the zipfile, encoded in the local code page, in which case you have no way of knowing. -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
pexpect/termios error: Inappropriate ioctl for device
Hi All, I have a python program that downloads database backups from a remote server, and tries to replace the local database with the downloaded backup. The database is a PostgreSQL server and my program calls the pg_restore command with the aid of the wonderful pexpect module. Everything works fine if I start this program from a tty. When I try to start the same program from cron, I get this nasty exception: Traceback (most recent call last): File /root/restore_databases.py, line 82, in ? main() File /root/restore_databases.py, line 79, in main restore_all() File /root/restore_databases.py, line 73, in restore_all do_restore(os.path.join(BACKUPDIR,fname),database) File /root/restore_databases.py, line 56, in do_restore dropdb(database) File /root/restore_databases.py, line 44, in dropdb db.interact() File /usr/local/lib/python2.4/site-packages/pexpect.py, line 1226, in interact mode = tty.tcgetattr(self.STDIN_FILENO) termios.error: (25, 'Inappropriate ioctl for device') What can I do to avoid this? Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: with ctypes, how to parse a multi-string
Eric schrieb: Hi, I am currently dealing with ctypes, interfacing with winscard libbrary (for smart card access). Several APIs (e.g. SCardListReaderGroupsW ) take a pointer to an unicode string as a parameter , which points at function return to a sequence of unicode strings, NULL terminated. The last string is double NULL terminated. (of course buffer length is also returned as another parameter). e.g. it could return something like 'group1\x00group2\x00group3\x00\x00' What should I use as argtypes to my function prototype in order to gain access to the full list? using c_wchar_p works, but it resolves the string until it reaches the first \x00, resulting in having access to the first entry of the list only. A c_wchar_p instance represent a (one!) zero-terminated string, as you already know. A POINTER(c_wchar) instance is more flexible, you should use that instead. It can be indexed/sliced with arbitrary indexes. Here is a simple script to get you started: from ctypes import * # Normally, the function call will fill the buffer: buf = create_unicode_buffer(first\0second\0third\0) # The pointer you will pass to the function call ptr = cast(buf, POINTER(c_wchar)) # function call omitted # Print the raw result print ptr[:len(buf)] # Print a list of strings print ptr[:len(buf)].split(\0) Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
something like name=None lines=[] for line in open('yourfilename.txt'): if line.startwith(''): if name!=None: print 'Here is the record', name print lines print name=line.stripr('\r') lines=[] else: lines.append(line.stripr('\n')) On 31 mai, 14:39, Lee Sander [EMAIL PROTECTED] wrote: I wanted to also say that this file is really huge, so I cannot just do a read() and then split on to get a record thanks lee On May 31, 1:26 pm, Lee Sander [EMAIL PROTECTED] wrote: Dear all, I would like toreada really hugefilethat looks like this: name1 line_11 line_12 line_13 ...name2 ... line_21 line_22 ... etc where line_ij is just a free form text on that line. how can ireadfileso that every time i do a read() i get exactly onerecord up to the next many thanks Lee -- http://mail.python.org/mailman/listinfo/python-list
Re: non standard path characters
Tijs wrote: Robin Becker wrote: ... Zip files contain a bit flag for the character encoding (cp430 or utf-8), see the ZipInfo object in module zipfile and the link (on that page) to the file format description. But I think some zip programs just put the path in the zipfile, encoded in the local code page, in which case you have no way of knowing. thanks for that. I guess the problem is that when a path is obtained from such an object the code that gets the path usually has no way of knowing what the intended use is. That makes storage as simple bytes hard. I guess the correct way is to always convert to a standard (say utf8) and then always know the required encoding when the thing is to be used. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 8 style enforcing program
[EMAIL PROTECTED] schrieb: Some recent posts about Python programming style got me thinking. Since we have the PEP 8 which gives some guidelines about the style to be used, do we have any program that can check for violations of these guidelines within the source code? I understand that there are a lot of code beautifiers out there, but i haven't seen one specially tailored for Python... Is there even a desire in Python community for a program like this (by Python community I mean the people in this group:) ) ? I think it would be a nice little project for practice and I'd like to do it, but if there is already something like this then I can probably spend my time on something more productive. So, I'd like to hear your opinion on this... There is one thing that I don't understand about PEP 8 - why is using spaces considered more desirable than using tabs for indentation? Pylint is one of them (http://www.logilab.org/857) With spaces you get always the same len of the line, where tabs can use 2,4,8 spaces, dependingt on the settings of the IDE Alexander -- http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
On 31 mai, 14:16, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: In [EMAIL PROTECTED], frederic.pica wrote: So as I can see, python maintain a memory pool for lists. In my first example, if I reparse the xml file, the memory doesn't grow very much (0.1 Mb precisely) So I think I'm right with the memory pool. But is there a way to force python to release this memory ?! AFAIK not. But why is this important as long as the memory consumption doesn't grow constantly? The virtual memory management of the operating system usually takes care that only actually used memory is in physical RAM. Ciao, Marc 'BlackJack' Rintsch Because I'm an adept of small is beautiful, of course the OS will swap the unused memory if needed. If I daemonize this application I will have a constant 40 Mb used, not yet free for others applications. If another application need this memory, the OS will have to swap and loose time for the other application... And I'm not sure that the system will swap first this unused memory, it could also swap first another application... AFAIK. And these 40 Mb are only for a 7 Mb xml file, what about parsing a big one, like 50 Mb ? I would have preferred to have the choice of manually freeing this unused memory or setting manually the size of the memory pool Regards, FP -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
aspineux wrote: something like name=None lines=[] for line in open('yourfilename.txt'): if line.startwith(''): if name!=None: print 'Here is the record', name print lines print name=line.stripr('\r') lines=[] else: lines.append(line.stripr('\n')) That would miss the last chunk. -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython demo error on debian etch
On May 31, 12:21 am, BartlebyScrivener [EMAIL PROTECTED] wrote: On May 29, 1:09 pm, [EMAIL PROTECTED] wrote: The newer versions of wxPython won't make your Debian crash or anything. We run Debian at work and I've upgraded the Python to 2.4 and the wxPython to its newest version. This has not affected the server's stability in any way. Install like this? Debian stable is way behind the times, so you may find something appropriate in testing. Alternatively, the instructions below should work. apt-get install alien apt-get install libgtk2.0-dev freeglut3-dev python2.3-dev wgethttp://easynews.dl.sourceforge.net/wxpython/wxPython2.8-2.8.3.0-1.src... rpmbuild --rebuild --define 'pyver 2.3' wxPython2.8-2.8.3.0-1.src.rpm cd rpmdir alien packagenames.rpm dpkg -i whatever alien called them This link explains the process the Debian team takes to implement new versions of packages (like wxPython):http://en.wikipedia.org/wiki/Debian Basically, they test it for months before finally putting it in to the stable category. However, since they have to do this for lots of packages, one by one the packages get marked stable. So you could have something like wxPython marked stable in March and 6 months later, the rest of the packages are done so they're marked stable. And then after additional testing, they release the new version. Hopefully that wasn't too confusing. Mike I would assume that would work. If you run into any problems, it would be a good idea to post them to the wxPython user's group. They know a LOT more about that sort of stuff if things go wrong. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
Lee Sander wrote: I wanted to also say that this file is really huge, so I cannot just do a read() and then split on to get a record thanks lee Below is the easy solution. To get even better performance, or if '' is not always at the start of the line, you would have to implement the buffering that is done by readline() yourself (see _fileobject in socket.py in the standard lib for example). def chunkreader(f): name = None lines = [] while True: line = f.readline() if not line: break if line[0] == '': if name is not None: yield name, lines name = line[1:].rstrip() lines = [] else: lines.append(line) if name is not None: yield name, lines if __name__ == '__main__': from StringIO import StringIO s = \ name1 line1 line2 line3 name2 line 4 line 5 line 6 f = StringIO(s) for name, lines in chunkreader(f): print '***', name print ''.join(lines) $ python test.py *** name1 line1 line2 line3 *** name2 line 4 line 5 line 6 -- Regards, Tijs -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Joe Riopel a écrit : Each requires exactly the same number of key strokes when I do the math. (Too lazy to explain further...) foo_bar f, o, o, shift + underscore, b, a, r = 8 fooBar f, o, o, shift + b, a, r = 7 f, o, o, _, b, a, r = 7 f, o, o, shift + b, a, r = 8 Also the shift+b is much more work than 2 keypresses IMHO. On the other hand, the underscore is done by pressing the 8 key without any other modifier which is very easy and accessible. Yeap, french layout rules for that naming convention :) -- http://mail.python.org/mailman/listinfo/python-list
WEATHER PROGRAMMING IN PYTHON
how to diplay the weather condiction on my webpage suppose i want to read weather from www.bbc.co.uk/weather.html how i can read it usin program -- http://mail.python.org/mailman/listinfo/python-list
Re: Examples of high-quality python code?
kaens wrote: Hey everyone, I'm relatively new to python - I actually picked it up to see how quickly I could start building non-trivial apps with it. Needless to say, I was quite pleased. Anyhow, I'm looking to expand my understanding of python, and I feel that one of the best ways to do that is looking at other peoples code. Unfortunately, I don't feel like I grok the python mindset quite well enough to fully distinguish between awesome, average, and not-pythony code, so I was hoping some of the more experienced python people could point me to some (preferably FOSS) non-trivial apps written in python that are examples of great python code. I realize this may be a bit ambiguous - basically I don't want to go randomly downloading other people's source and end up assimilating techniques that aren't . . . well . . . pythonistic. So, who wants to hook me up? You should consider picking up a copy of Python Cookbook. Alex and others have reviewed the code it contains and IMHO it is well written. I've also learned quite a lot from: Python on Win32 (book by Mark Hammond/Andy Robinson) Reading source code to standard library Reading ReportLab source (www.reportlab.org) Reading PIL source (www.effbot.org) Reading wxPython source (www.wxpython.org) Monitoring this list on a daily basis -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: file reading by record separator (not line by line)
In [EMAIL PROTECTED], Lee Sander wrote: Dear all, I would like to read a really huge file that looks like this: name1 line_11 line_12 line_13 ... name2 ... line_21 line_22 ... etc where line_ij is just a free form text on that line. how can i read file so that every time i do a read() i get exactly one record up to the next There was just recently a thread with a `itertools.groupby()` solution. Something like this: from itertools import count, groupby, imap from operator import itemgetter def mark_records(lines): counter = 0 for line in lines: if line.startswith(''): counter += 1 yield (counter, line) def iter_records(lines): fst = itemgetter(0) snd = itemgetter(1) for dummy, record_lines in groupby(mark_records(lines), fst): yield imap(snd, record_lines) def main(): source = \ name1 line_11 line_12 line_13 ... name2 ... line_21 line_22 splitlines() for record in iter_records(source): print 'Start of record...' for line in record: print ':', line Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: WEATHER PROGRAMMING IN PYTHON
In [EMAIL PROTECTED], sandeep patil wrote: how to diplay the weather condiction on my webpage suppose i want to read weather from www.bbc.co.uk/weather.html how i can read it usin program It's hard to scrape information about weather from an 404 error page. ;-) Find some page with actual weather reports or forecasts and use the BeautifulSoup module to scrape the information you need. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Form/Page and Navigation with multiple buttons
How can I identify which button has been pressed. Do I need a separate form for each button and hide all the relevant session fields in each form or is there a way of identifying which button has been pressed on the page. Hi, Richard, Just give each button (or input) tag a distinct name attribute and a value attribute. Also make sure the button is inside the form. When the button is used to submit the form, FieldStorage will return the name:value pair. -Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing Rdf (Rewrite)
On 5/31/07, Brandon McGinty [EMAIL PROTECTED] wrote: I would think that I could do: etexts=tree.findall('pgterms:etext') (or something like that), Which would pull out each etext record in the file. I could then do: for book in etexts: print book.get('id') This isn't yielding anything for me, no matter how I write it. Any thoughts on this? I know very little about ElementTree, but a bit of experimentation shows that the following seems to work: import xml.etree.cElementTree as et tree = et.parse(C:/temp/catalog.rdf) root = tree.getroot() etexts = tree.findall({http://www.gutenberg.org/rdfterms/}etext;) for book in etexts: print book.get({http://www.w3.org/1999/02/22-rdf-syntax-ns#}ID;) I see some comments on namespace issues here: http://effbot.org/zone/element.htm#xml-namespaces if that helps. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
HTML Form/Page and Navigation with multiple buttons
I am struggling to find a python example of the scenario - I have. I have a python script, which generates a page with a search button (actually an input field). The data from the above submissions is interrogated and the same script produces a new search option and the a page of results from the previous search request. - as done by Google's Main search page. The user then has the option of a new search or navigating to a different page of results with the usual Start, Previous, Next and Last Buttons. How can I identify which button has been pressed. Do I need a separate form for each button and hide all the relevant session fields in each form or is there a way of identifying which button has been pressed on the page. I only want to use the same python script, which is called each time. No javascript and no cookies. I have a very skimpy knowledge of Forms, Get and Post - so be gentle with me. I have got CGI and FieldStorage to work. Any help or suitable introductory site information appreciated. Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Form/Page and Navigation with multiple buttons
On 31 May, 15:22, mosscliffe [EMAIL PROTECTED] wrote: [Multiple submit buttons in HTML forms] How can I identify which button has been pressed. Do I need a separate form for each button and hide all the relevant session fields in each form or is there a way of identifying which button has been pressed on the page. When you define the buttons like this... input name=new type=submit value=New search / input name=start type=submit value=Start / input name=previous type=submit value=Previous / input name=next type=submit value=Next / input name=last type=submit value=Last / When the user selects one of the buttons, you should get an entry for the field representing the button in the FieldStorage object. So, if the user presses the next button, there should be an entry mapping that name (next) to some value (Next in the above example) in the FieldStorage object. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: WEATHER PROGRAMMING IN PYTHON
On May 31, 8:44 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: In [EMAIL PROTECTED], sandeep patil wrote: how to diplay the weather condiction on my webpage suppose i want to read weather fromwww.bbc.co.uk/weather.html how i can read it usin program It's hard to scrape information about weather from an 404 error page. ;-) Find some page with actual weather reports or forecasts and use the BeautifulSoup module to scrape the information you need. Ciao, Marc 'BlackJack' Rintsch It looks like you might even be able to use the rss module from Python on this sub-page: http://feeds.bbc.co.uk/weather/feeds/rss/5day/world/0008.xml See here for more info on RSS with Python: http://wiki.python.org/moin/RssLibraries Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: with ctypes, how to parse a multi-string
On May 31, 2:52 pm, Thomas Heller [EMAIL PROTECTED] wrote: Eric schrieb: Hi, I am currently dealing with ctypes, interfacing with winscard libbrary (for smart card access). Several APIs (e.g. SCardListReaderGroupsW ) take a pointer to an unicode string as a parameter , which points at function return to a sequence of unicode strings, NULL terminated. The last string is double NULL terminated. (of course buffer length is also returned as another parameter). e.g. it could return something like 'group1\x00group2\x00group3\x00\x00' What should I use as argtypes to my function prototype in order to gain access to the full list? using c_wchar_p works, but it resolves the string until it reaches the first \x00, resulting in having access to the first entry of the list only. A c_wchar_p instance represent a (one!) zero-terminated string, as you already know. A POINTER(c_wchar) instance is more flexible, you should use that instead. It can be indexed/sliced with arbitrary indexes. Here is a simple script to get you started: from ctypes import * # Normally, the function call will fill the buffer: buf = create_unicode_buffer(first\0second\0third\0) # The pointer you will pass to the function call ptr = cast(buf, POINTER(c_wchar)) # function call omitted # Print the raw result print ptr[:len(buf)] # Print a list of strings print ptr[:len(buf)].split(\0) Thomas Thanks Thomas, it works as expected! Regards, Eric -- http://mail.python.org/mailman/listinfo/python-list
Re: Examples of high-quality python code?
On May 31, 8:38 am, Larry Bates [EMAIL PROTECTED] wrote: kaens wrote: Hey everyone, I'm relatively new to python - I actually picked it up to see how quickly I could start building non-trivial apps with it. Needless to say, I was quite pleased. Anyhow, I'm looking to expand my understanding of python, and I feel that one of the best ways to do that is looking at other peoples code. Unfortunately, I don't feel like I grok the python mindset quite well enough to fully distinguish between awesome, average, and not-pythony code, so I was hoping some of the more experienced python people could point me to some (preferably FOSS) non-trivial apps written in python that are examples of great python code. I realize this may be a bit ambiguous - basically I don't want to go randomly downloading other people's source and end up assimilating techniques that aren't . . . well . . . pythonistic. So, who wants to hook me up? You should consider picking up a copy of Python Cookbook. Alex and others have reviewed the code it contains and IMHO it is well written. I've also learned quite a lot from: Python on Win32 (book by Mark Hammond/Andy Robinson) Reading source code to standard library Reading ReportLab source (www.reportlab.org) Reading PIL source (www.effbot.org) Reading wxPython source (www.wxpython.org) Monitoring this list on a daily basis -Larry Also Python Programming by Lutz has some great code to learn from as it also explains most of it. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: RSA SecurID token authentication?
On May 29, 11:22 am, Chris Shenton [EMAIL PROTECTED] wrote: Anyone doing python application authentication using RSASecurID tokens? We have a Pylons app that needs this. I've written code against RSA's API and found the docs terrible and the libraries painful to use. RSA has a RADIUS server fronting their server so I expect I could use that instead, might be easier. This is on Solaris10 x86 which supports PAM but I've never accessed PAM from Python, any pointers? I've done RADIUS before (Cistron, Ascend, FreeRADIUS) but not with Python. Any suggestions? I see a pyrad library, last updated in March I'm guessing it's too late to choose a two-factor solution with an open API and open source python examples? :) Oh well. I recommend going with pyrad and using the Radius interface. This will allow you to use a third party radius server if you want and since all the two-factor vendors support radius, you won't have to re- write the apps if you switch strong authentication vendors. HTH, nick -- Nick Owen WiKID Systems, Inc. 404.962.8983 http://www.wikidsystems.com Commercial/Open Source Two-Factor Authentication irc.freenode.net: #wikid -- http://mail.python.org/mailman/listinfo/python-list
Upgrading a largish group of packages w/ distutils
At work I need to upgrade numpy, scipy, ipython and matplotlib. They need to be done all at once. All have distutils setups but the new versions and the old versions are incompatible with one another as a group because numpy's apis changed. Ideally, I could just do something like cd ~/src cd numpy python setup.py install cd ../scipy python setup.py install cd ../matplotlib python setup.py install cd ../ipython python setup.py install however, even if nothing goes awry it leaves me with a fair chunk of time where the state of the collective system is inconsistent (new numpy, old everything else). I'm wondering... Can I stage the installs to a different directory tree like so: export PYTHONPATH=$HOME/local/lib/python-2.4/site-packages cd ~/src cd numpy python setup.py install --prefix=$PYTHONPATH cd ../scipy python setup.py install --prefix=$PYTHONPATH cd ../matplotlib python setup.py install --prefix=$PYTHONPATH cd ../ipython python setup.py install --prefix=$PYTHONPATH That would get them all built as a cohesive set. Then I'd repeat the installs without PYTHONPATH: unset PYTHONPATH cd ~/src cd numpy python setup.py install cd ../scipy python setup.py install cd ../matplotlib python setup.py install cd ../ipython python setup.py install Presumably the compilation (the time-consuming part) is all location-independent, so the second time the build_ext part should be fast. Can anyone comment on the feasibility of this approach? I guess what I'm wondering is what dependencies there are on the installation directory. Thx, Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: paste text with newlines into raw_input?
Thanks, I think I need a Tkinter text entry widget, but it will take me a week to learn how to set it up. I'll report back. rick -- http://mail.python.org/mailman/listinfo/python-list
How do I Extract Attachment from Newsgroup Message
I'm parsing NNTP messages that have XML file attachments. How can I extract the encoded text back into a file? I looked for a solution with mimetools (the way I'd approach it for email) but found nothing. Here's a long snippet of the message: n.article('116431') ('220 116431 [EMAIL PROTECTED] article', '116431', '[EMAIL PROTECTED]', ['MIME-Version: 1.0', 'Message-ID: [EMAIL PROTECTED]', 'Content-Type: Multipart/Mixed;', ' boundary=Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Date: Thu, 24 May 2007 07:41:34 -0400 (EDT)', 'From: Newsclip [EMAIL PROTECTED]', 'Path: newsclip.ap.org!flounder.ap.org!flounder', 'Newsgroups: ap.spanish.online,ap.spanish.online.business', 'Keywords: MUN ECO PETROLEO PRECIOS', 'Subject: MUN ECO PETROLEO PRECIOS', 'Summary: ', 'Lines: 108', 'Xref: newsclip.ap.org ap.spanish.online:938298 ap.spanish.online.business:116431', '', '', '-- Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Content-Type: Text/Plain', 'Content-Transfer-Encoding: 8bit', 'Content-Description: text, unencoded', '', '(AP) Precios del crudo se mueven sin rumbo claro', 'Por GEORGE JAHN', 'VIENA', 'Los precios ... (truncated for length) ... '', '___', '', 'Editores: Derrick Ho, periodista de la AP en Singapur, contribuy\xf3 con esta informaci\xf3n.', '', '', '-- Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Content-Type: Text/Xml', 'Content- Transfer-Encoding: base64', 'Content-Description: text, base64 encoded', '', 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIG5pdGYgU1lT', 'VEVNICJuaXRmLmR0ZCI+CjxuaXRmPgogPGhlYWQ +CiAgPG1ldGEgbmFtZT0iYXAtdHJhbnNyZWYi', 'IGNvbnRlbnQ9IlNQMTQ3MiIvPgogIDxtZXRhIG5hbWU9ImFwLW9yaWdpbiIgY29udGVudD0ic3Bh', 'bm9sIi8+CiAgPG1ldGEgbmFtZT0iYXAtc2VsZWN0b3IiIGNvbn -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
[EMAIL PROTECTED] wrote: FWIW, even though I think proper-case-with-seperators is greatly preferrable to camelCase, I certainly don't think that speaking the names is a really major point. unless you or someone with working hands helps fix up voicecoder, it is a major point for people like me. http://voicecode.iit.nrc.ca/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I Extract Attachment from Newsgroup Message
On May 31, 8:54 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I'm parsing NNTP messages that have XML file attachments. How can I extract the encoded text back into a file? I looked for a solution with mimetools (the way I'd approach it for email) but found nothing. Here's a long snippet of the message: n.article('116431') ('220 116431 [EMAIL PROTECTED] article', '116431', '[EMAIL PROTECTED]', ['MIME-Version: 1.0', 'Message-ID: [EMAIL PROTECTED]', 'Content-Type: Multipart/Mixed;', ' boundary=Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Date: Thu, 24 May 2007 07:41:34 -0400 (EDT)', 'From: Newsclip [EMAIL PROTECTED]', 'Path: newsclip.ap.org!flounder.ap.org!flounder', 'Newsgroups: ap.spanish.online,ap.spanish.online.business', 'Keywords: MUN ECO PETROLEO PRECIOS', 'Subject: MUN ECO PETROLEO PRECIOS', 'Summary: ', 'Lines: 108', 'Xref: newsclip.ap.org ap.spanish.online:938298 ap.spanish.online.business:116431', '', '', '-- Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Content-Type: Text/Plain', 'Content-Transfer-Encoding: 8bit', 'Content-Description: text, unencoded', '', '(AP) Precios del crudo se mueven sin rumbo claro', 'Por GEORGE JAHN', 'VIENA', 'Los precios ... (truncated for length) ... '', '___', '', 'Editores: Derrick Ho, periodista de la AP en Singapur, contribuy\xf3 con esta informaci\xf3n.', '', '', '-- Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Content-Type: Text/Xml', 'Content- Transfer-Encoding: base64', 'Content-Description: text, base64 encoded', '', 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIG5pdGYgU1lT', 'VEVNICJuaXRmLmR0ZCI+CjxuaXRmPgogPGhlYWQ +CiAgPG1ldGEgbmFtZT0iYXAtdHJhbnNyZWYi', 'IGNvbnRlbnQ9IlNQMTQ3MiIvPgogIDxtZXRhIG5hbWU9ImFwLW9yaWdpbiIgY29udGVudD0ic3Bh', 'bm9sIi8+CiAgPG1ldGEgbmFtZT0iYXAtc2VsZWN0b3IiIGNvbn This looks like what you might be looking for: http://mail.python.org/pipermail/python-list/2004-June/265018.html Not sure if you'll need this or not, but here's some info on encoding/ decoding files: http://www.jorendorff.com/articles/unicode/python.html There are lots of ways to parse xml. I use the minidom module myself. Mike -- http://mail.python.org/mailman/listinfo/python-list
[OT] Re: HTML Form/Page and Navigation with multiple buttons
mosscliffe a écrit : I am struggling to find a python example of the scenario - I have. I have a python script, which generates a page with a search button (actually an input field). The data from the above submissions is interrogated and the same script produces a new search option and the a page of results from the previous search request. - as done by Google's Main search page. The user then has the option of a new search or navigating to a different page of results with the usual Start, Previous, Next and Last Buttons. How can I identify which button has been pressed. Do I need a separate form for each button and hide all the relevant session fields in each form or is there a way of identifying which button has been pressed on the page. This is not really a Python problem - would be the same with any server-side techno... OT You shouldn't use buttons for navigation, but links. The simplest solution is to pass all the relevant data into the query string (the ?key=valkey2=val2etc=etc part of the url). In your case, this would be something like resending all the search params, and adding the current page and the action (ie 'action=next' or 'action=first' etc...) /OT -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
Hey Douglas, Perhaps I was being too abstract? Here goes: ,--- | def selector(): |... |return funcKey #get down get down | | def func(): |... | funcSwitch = {} | funcSwitch[funcKey] = func | ... | funcSwitch[selector()]() even more interesting is a , | def judge(contestants): | for contestant in contestants: | ... | if answersQuestionToSatisfaction: | yield semiFinalist | | beauty[judge(beauty)]() h, I suppost you could just call judge(beauty) and have the judge call the contestant personally. But that may be *too* personal. Moreover, what about the other judges? Wouldn't it be best to simply state: beauty[judges[:](beauty)].thankyouForThisOpportunity() This allows each judge to choose differently while all the contestants behave consistently. It kind of like an off the cuff decorator for generators, where beauty[...].decoration() Maybe there's a better way of doing this? I don't know. def a(): return 'b' def b(): print 'polly! wakey wakey' c = {} c['a'] = b c[a()]() #works! (typo correction for other easily-confused newbies like myself) I think you mean , | c['a']() #works! ` Oh no, I get it, you meant... , | c['b'] = b | c[a()]() #works! ` ...or was it?:- , | def a(): return 'a' ` -- Doug Woodrow -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
Hello, [EMAIL PROTECTED] wrote: I've some troubles getting my memory freed by python, how can I force it to release the memory ? I've tried del and gc.collect() with no success. [...] The same problem here with a simple file.readlines() #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared del data #meminfo: 11.5 Mb private, 1.4 Mb shared gc.collect() # no memory change But works great with file.read() : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared del data #meminfo: 1.1 Mb private, 1.4 Mb shared gc.collect() # no memory change So as I can see, python maintain a memory pool for lists. In my first example, if I reparse the xml file, the memory doesn't grow very much (0.1 Mb precisely) So I think I'm right with the memory pool. But is there a way to force python to release this memory ?! This is from the 2.5 series release notes (http://www.python.org/download/releases/2.5.1/NEWS.txt): [...] - Patch #1123430: Python's small-object allocator now returns an arena to the system ``free()`` when all memory within an arena becomes unused again. Prior to Python 2.5, arenas (256KB chunks of memory) were never freed. Some applications will see a drop in virtual memory size now, especially long-running applications that, from time to time, temporarily use a large number of small objects. Note that when Python returns an arena to the platform C's ``free()``, there's no guarantee that the platform C library will in turn return that memory to the operating system. The effect of the patch is to stop making that impossible, and in tests it appears to be effective at least on Microsoft C and gcc-based systems. Thanks to Evan Jones for hard work and patience. [...] So with 2.4 under linux (as you tested) you will indeed not always get the used memory back, with respect to lots of small objects being collected. The difference therefore (I think) you see between doing an f.read() and an f.readlines() is that the former reads in the whole file as one large string object (i.e. not a small object), while the latter returns a list of lines where each line is a python object. I wonder how 2.5 would work out on linux in this situation for you. Paul -- http://mail.python.org/mailman/listinfo/python-list
How to clean a module?
It assumes that there is a module A which have two global variables X and Y. If I run import A in the IDLE shell, then I can use A.X and A.Y correctly. But if I want to change the module A and then delete the variable Y, I find I can use A.Y just the same as before! In fact, I have tried all the following methods but can't remove the A.Y: execute import A again reload(A) del A; import A Yes, if you use del A.Y, it works. But it is stupid since there are probably many names. In my thought, if no one references objects in A, del A will release all memory about A. But it seems that the fact is not. So I can not refresh the namespace to follow changes of a module easily and I will worry about the memory if I del a module. I want to know if there is a way to clear a module entirely. -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On 2007-05-31, Warren Stringer [EMAIL PROTECTED] wrote: Oops! guess I should have tested my rather hasty complaint about executable containers. This is nice: def a(): return 'b' def b(): print 'polly! wakey wakey' c = {} c['a'] = b c[a()]() #works! c[a()]() is a switch statement with an amorphous selector- very handy in its own right. But, using a() as a generator would be more expressive. This seems to work: c = [a,a] [d() for d in c] But that still isn't as simple or as direct as: c[:]() Why do you always use a _copy_ of c in your examples? As long as you're wishing, why not just c() -- Grant Edwards grante Yow! I'm meditating on at the FORMALDEHYDE and the visi.comASBESTOS leaking into my PERSONAL SPACE!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Upgrading a largish group of packages w/ distutils
export PYTHONPATH=$HOME/local/lib/python-2.4/site-packages cd ~/src cd numpy python setup.py install --prefix=$PYTHONPATH cd ../scipy python setup.py install --prefix=$PYTHONPATH cd ../matplotlib python setup.py install --prefix=$PYTHONPATH cd ../ipython python setup.py install --prefix=$PYTHONPATH Ack! Make that: export PYTHONPATH=$HOME/local/lib/python-2.4/site-packages export PYTHONPFX=$HOME/local cd ~/src cd numpy python setup.py install --prefix=$PYTHONPFX cd ../scipy python setup.py install --prefix=$PYTHONPFX cd ../matplotlib python setup.py install --prefix=$PYTHONPFX cd ../ipython python setup.py install --prefix=$PYTHONPFX Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I Extract Attachment from Newsgroup Message
I looked for a solution with mimetools (the way I'd approach it for email) but found nothing. ... [EMAIL PROTECTED]', 'Content-Type: Multipart/Mixed;', ' boundary=Boundary-00=_A5NJCP3FX6Y5BI3BH890', 'Date: Thu, ... Playing with data = n.article('116431')[3] and email.message_from_string, there seems to be a problem with the content type being split up. I was able to get a multipart message by using msg = email.message_from_string('\n'.join(data).replace(';\n', ';')) (and adding an ending boundary to your sample data). This is a bit hackish and could cause problems if there are semicolons inside the message body (no warranties expressed or implied, etc.) Hope this helps, -Dave -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
Cool! Yes. By the way, I've discovered that [] are quite difficult on cell phones. But periods and parens are easy. So, I'm using your approach for creating a dot operator for {} -Original Message- From: [EMAIL PROTECTED] [mailto:python-list- [EMAIL PROTECTED] On Behalf Of Mikael Olofsson Sent: Thursday, May 31, 2007 1:52 AM To: python-list@python.org Subject: Re: c[:]() Warren Stringer wrote: I want to call every object in a tupple, like so: [snip examples] Why? Because I want to make Python calls from a cell phone. Every keystroke is precious; even list comprehension is too much. If you are going to do this just a few times in your program, I cannot help. But: If you want to do it several times, perhaps you have space for an initial class definition, like so: class CallableList(list): def __call__(self,*args,**kwargs): return [f(*args,**kwargs) for f in self] def a(): return 'a called' def b(): return 'b called' c = CallableList([a,b])() You might want to trim the class to fit your needs, perhaps use a shorter name, and perhaps you don't need to handle arguments. Can the class be placed in a module, so that it only needs to be typed once in your application? /MiO -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
On 31 mai, 16:22, Paul Melis [EMAIL PROTECTED] wrote: Hello, [EMAIL PROTECTED] wrote: I've some troubles getting my memory freed by python, how can I force it to release the memory ? I've tried del and gc.collect() with no success. [...] The same problem here with a simple file.readlines() #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared del data #meminfo: 11.5 Mb private, 1.4 Mb shared gc.collect() # no memory change But works great with file.read() : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared del data #meminfo: 1.1 Mb private, 1.4 Mb shared gc.collect() # no memory change So as I can see, python maintain a memory pool for lists. In my first example, if I reparse the xml file, the memory doesn't grow very much (0.1 Mb precisely) So I think I'm right with the memory pool. But is there a way to force python to release this memory ?! This is from the 2.5 series release notes (http://www.python.org/download/releases/2.5.1/NEWS.txt): [...] - Patch #1123430: Python's small-object allocator now returns an arena to the system ``free()`` when all memory within an arena becomes unused again. Prior to Python 2.5, arenas (256KB chunks of memory) were never freed. Some applications will see a drop in virtual memory size now, especially long-running applications that, from time to time, temporarily use a large number of small objects. Note that when Python returns an arena to the platform C's ``free()``, there's no guarantee that the platform C library will in turn return that memory to the operating system. The effect of the patch is to stop making that impossible, and in tests it appears to be effective at least on Microsoft C and gcc-based systems. Thanks to Evan Jones for hard work and patience. [...] So with 2.4 under linux (as you tested) you will indeed not always get the used memory back, with respect to lots of small objects being collected. The difference therefore (I think) you see between doing an f.read() and an f.readlines() is that the former reads in the whole file as one large string object (i.e. not a small object), while the latter returns a list of lines where each line is a python object. I wonder how 2.5 would work out on linux in this situation for you. Paul Hello, I will try later with python 2.5 under linux, but as far as I can see, it's the same problem under my windows python 2.5 After reading this document : http://evanjones.ca/memoryallocator/python-memory.pdf I think it's because list or dictionnaries are used by the parser, and python use an internal memory pool (not pymalloc) for them... Regards, FP -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Python style?
Andreas Beyer [EMAIL PROTECTED] wrote: Hi, I found the following quite cryptic code, which basically reads the first column of some_file into a set. In Python I am used to seeing much more verbose/explicit code. However, the example below _may_ actually be faster than the usual for line in ... Do you consider this code good Python style? Or would you recommend to refrain from such complex single-line code?? Thanks! Andreas inp = resource(some_file) # read first entries of all non-empty lines into a set some_set = frozenset([line.split()[0] for line in \ filter(None, [ln.strip() for ln in inp])]) Sparse is better than dense, and this code is far from the fastest one could write -- it builds useless lists comprehensions where genexps would do, it splits off all whitespace-separated words (rather than just the first one) then tosses all but the first away, etc. frozenset(first_word_of_line for line in input_file for first_word_of_line in line.split(None, 1)[:1] ) does not sacrifice any speed (on the contrary), yet achieves somewhat better clarity by clearer variable names, reasonable use of whitespace for formatting, and avoidance of redundant processing. If this set didn't have to be frozen, building it in a normal for loop (with a .add call in the nested loop) would no doubt be just as good in terms of both clarity and performance; however, frozen sets (like tuples) don't lend themselves to such incremental building in place (you'd have to build the mutable version, then cast it at the end; the alternative of making a new frozenset each time through the loop is clearly unpleasant), so I can see why one would want to avoid that. A good, readable, and only slightly slower alternative is to write a named generator: def first_words(input_file): for line in input_file: first_word_if_any = line.split(None, 1) if first_word_if_any: yield first_word_if_any[0] ff = frozenset(first_words(input_file)) A full-fledged generator gives you more formatting choices, an extra name to help, and the possibility of naming intermediate variables. Whether it's worth it in this case is moot -- personally I find the slice then for-loop idiom (which I used in the genexp) just as clear as the test then index one (which I used in first_words) to express the underlying notion give me the first item if any, but just proceed without giving anything if the list is empty; but I can imagine somebody else deciding that the test/index idiom is a more direct expression of that notion. You could use it in a genexp, too, of course: frozenset(first_word_if_any[0] for line in input_file for first_word_if_any in [line.split(None, 1)] if first_word_if_any ) but this requires the for x in [y] trick to simulate the x=y assigment of an intermediate variable in a genexp or LC, which is never an elegant approach, so I wouldn't recommend it. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
On Wed, 30 May 2007 20:41:32 -0600, Frank Swarbrick [EMAIL PROTECTED] wrote: Tim Roberts wrote: Frank Swarbrick [EMAIL PROTECTED] wrote: Then you'd really love COBOL! :-) Frank COBOL programmer for 10+ years Hey, did you hear about the object-oriented version of COBOL? They call it ADD ONE TO COBOL. I know you were joking, but the COBOL 2002 standard implements OO. It's OK, but quite obviously bolted on. Exactly the same situation as the OO in C++... -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Form/Page and Navigation with multiple buttons
Excellent - thanks for all your help. I now have a form created by a python script executing an HTML page, doing everything I need, except for Session Data (probably use hidden fields ?? future research) and the actual paging logic !!! If I use a link. I have to add all my hidden fields to the query string, otherwise cgi.FieldStorage(), does not return the hidden fields. This would also mean users see all the hidden field data. Is there another way, other than a cookie ? Why is a link better than a button ? I have been using 'post' for my form, to eliminate the displaying of field values. I accept I am quite niave about FORM/HTML logic. Richard On 31 May, 15:30, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: mosscliffe a écrit : I am struggling to find a python example of the scenario - I have. I have a python script, which generates a page with a search button (actually an input field). The data from the above submissions is interrogated and the same script produces a new search option and the a page of results from the previous search request. - as done by Google's Main search page. The user then has the option of a new search or navigating to a different page of results with the usual Start, Previous, Next and Last Buttons. How can I identify which button has been pressed. Do I need a separate form for each button and hide all the relevant session fields in each form or is there a way of identifying which button has been pressed on the page. This is not really a Python problem - would be the same with any server-side techno... OT You shouldn't use buttons for navigation, but links. The simplest solution is to pass all the relevant data into the query string (the ?key=valkey2=val2etc=etc part of the url). In your case, this would be something like resending all the search params, and adding the current page and the action (ie 'action=next' or 'action=first' etc...) /OT -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
Hey Marc, [d() for d in c] If you are using the list comprehension just for the side effect of calling `d` then consider this bad style. You are building a list of `None` objects just to have a cool one liner then. Yep, you're right for func in funcs: func() Because it is explicit and readable and matches the english description for every function in functions: call that function very closely while a list comprehension or your perlish line noise is much more magic to explain and harder to remember. H... the reason what I use the list comprehension was the description call that thing for every thing in those things The first time I something saw this I though, in my C befuddled head 'huh? that's backwards!' But, then the more I thought about it I recall that this is how some people speak. Still I prefer funcs[:]() Because, I can describe it in English as call everything that funcs has (BTW, I have yet to write my first line of Perl. It that good thing or a bad thing?) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to clean a module?
ai schrieb: It assumes that there is a module A which have two global variables X and Y. If I run import A in the IDLE shell, then I can use A.X and A.Y correctly. But if I want to change the module A and then delete the variable Y, I find I can use A.Y just the same as before! In fact, I have tried all the following methods but can't remove the A.Y: execute import A again reload(A) del A; import A Yes, if you use del A.Y, it works. But it is stupid since there are probably many names. In my thought, if no one references objects in A, del A will release all memory about A. But it seems that the fact is not. So I can not refresh the namespace to follow changes of a module easily and I will worry about the memory if I del a module. I want to know if there is a way to clear a module entirely. There might be other answers - but the easiest and IMHO best is to simply restart the interpreter. Because whatever you type in there, you could or should even (if it reaches some complexity) put in a small test script - and execute that from the interpreter at a shell prompt. The advantage is that you don't suffer from any side-effects e.g. IDLE has (no Tk mainloop for example) and avoid the problems you describe entirely. Together with a bunch of others. If you want/have to, you can drop into interpreter mode after script execution with python -i myscript.py Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
If the memory usage is that important to you, you could break this out into 2 programs, one that starts the jobs when needed, the other that does the processing and then quits. As long as the python startup time isn't an issue for you. On 31 May 2007 04:40:04 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Greets, I've some troubles getting my memory freed by python, how can I force it to release the memory ? I've tried del and gc.collect() with no success. Here is a code sample, parsing an XML file under linux python 2.4 (same problem with windows 2.5, tried with the first example) : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared #Using http://www.pixelbeat.org/scripts/ps_mem.py to get memory information import cElementTree as ElementTree #meminfo: 2.3 Mb private, 1.6 Mb shared import gc #no memory change et=ElementTree.parse('primary.xml') #meminfo: 34.6 Mb private, 1.6 Mb shared del et #no memory change gc.collect() #no memory change So how can I free the 32.3 Mb taken by ElementTree ?? The same problem here with a simple file.readlines() #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared del data #meminfo: 11.5 Mb private, 1.4 Mb shared gc.collect() # no memory change But works great with file.read() : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared del data #meminfo: 1.1 Mb private, 1.4 Mb shared gc.collect() # no memory change So as I can see, python maintain a memory pool for lists. In my first example, if I reparse the xml file, the memory doesn't grow very much (0.1 Mb precisely) So I think I'm right with the memory pool. But is there a way to force python to release this memory ?! Regards, FP -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
But that still isn't as simple or as direct as: c[:]() Why do you always use a _copy_ of c in your examples? As long as you're wishing, why not just c() Oh hey Grant, yes, I misunderstood your question for a bit. I thought you meant the difference between List comprehension [...] and generator expressions (...) where the first returns the whole list and the second iterates the whole list. But, yes, good point if I was only using [:]. For more expressiveness, I could using the alternative, to the example in my reply to Douglas def beauty(judge): ... As an alternative to my reply to Douglas ... and is more cell phone friendly, due to lack of cumbersome [], which I just mentioned to Mikael, who came up with an really cool [] solution ... hmmm ... Translating Mikael's solution to the original c[:]() with some tweaks: class do(list): def __call__(self,*args,**kwargs): return [f(*args,**kwargs) for f in self] def a(): print 'a called' def b(): print 'b called' c = [a,b] do(c[:])() # close but with cell phone gnarly [] do(c)() # woo hoo! In recalling Marc's reply about a cool one liner, such a statement translates in English, as do everything in c insert evil laughter Cheers, \~/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to parse usenet urls?
In article [EMAIL PROTECTED], [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Are you aware of nntplib? http://docs.python.org/lib/module-nntplib.html I am, but I once I got into the article itself, I couldn't figure out how to call a link inside the resulting message text: ... 'Castro: Bush desea mi muerte, pero las ideas no se matan', 'news://newsclip.ap.org/[EMAIL PROTECTED]', ... How can I take the message link 'news://newsclip.ap.org/ [EMAIL PROTECTED]' and follow it? OK, gotcha. I misunderstood your original question. Perhaps this is just a synonym for nntp:;? THis sounds like a dangerous assumption and hopefully someone more knowledgeable will come along and shoot me down. =) But when I fire up Ethereal and paste that news: URL into my browser, Firefox launches my newsreader client and Ethereal reports that my client connects to the remote server at the NNTP port (119), sends an NNTP LIST command and Ethereal identifies the subsequent conversation as NNTP. If I were you I'd try handling news: URLs with nttplib. I bet it will work. Sorry I couldn't provide more than guesses. Good luck! -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On 2007-05-31, Warren Stringer [EMAIL PROTECTED] wrote: But that still isn't as simple or as direct as: c[:]() Why do you always use a _copy_ of c in your examples? As long as you're wishing, why not just c() Oh hey Grant, yes, I misunderstood your question for a bit. I thought you meant the difference between List comprehension [...] and generator expressions (...) where the first returns the whole list and the second iterates the whole list. But, yes, good point if I was only using [:]. For more expressiveness, How is it more expressive? In the context you're concerned with, c[:] is the exactly same thing as c. You seem to be worried about saving keystrokes, yet you use c[:] instead of c. It's like having an integer variable i and using ((i+0)*1) instead of i. -- Grant Edwards grante Yow! I want to read my new at poem about pork brains and visi.comouter space ... -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 8 style enforcing program
montyphyton wrote this on Thu, 31 May 2007 05:16:30 -0700. My reply is below. I understand that there are a lot of code beautifiers out there, but i haven't seen one specially tailored for Python. Consider PythonTidy: o http://lacusveris.com/PythonTidy/PythonTidy.python -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 75° — Wind SSE 9 mph — Sky haze. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
On 31 mai, 17:29, Josh Bloom [EMAIL PROTECTED] wrote: If the memory usage is that important to you, you could break this out into 2 programs, one that starts the jobs when needed, the other that does the processing and then quits. As long as the python startup time isn't an issue for you. On 31 May 2007 04:40:04 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Greets, I've some troubles getting my memory freed by python, how can I force it to release the memory ? I've tried del and gc.collect() with no success. Here is a code sample, parsing an XML file under linux python 2.4 (same problem with windows 2.5, tried with the first example) : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared #Usinghttp://www.pixelbeat.org/scripts/ps_mem.pyto get memory information import cElementTree as ElementTree #meminfo: 2.3 Mb private, 1.6 Mb shared import gc #no memory change et=ElementTree.parse('primary.xml') #meminfo: 34.6 Mb private, 1.6 Mb shared del et #no memory change gc.collect() #no memory change So how can I free the 32.3 Mb taken by ElementTree ?? The same problem here with a simple file.readlines() #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared del data #meminfo: 11.5 Mb private, 1.4 Mb shared gc.collect() # no memory change But works great with file.read() : #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared import gc #no memory change f=open('primary.xml') #no memory change data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared del data #meminfo: 1.1 Mb private, 1.4 Mb shared gc.collect() # no memory change So as I can see, python maintain a memory pool for lists. In my first example, if I reparse the xml file, the memory doesn't grow very much (0.1 Mb precisely) So I think I'm right with the memory pool. But is there a way to force python to release this memory ?! Regards, FP -- http://mail.python.org/mailman/listinfo/python-list Yes it's a solution, but I think it's not a good way, I did'nt want to use bad hacks to bypass a python specific problem. And the problem is everywhere, every python having to manage big files. I've tried xml.dom.minidom using a 66 Mb xml file = 675 Mb of memory that will never be freed. But that time I've got many unreachable object when running gc.collect() Using the same file with cElementTree took me 217 Mb, with no unreachable object. For me it's not a good behavior, it's not a good way to let the system swap this unused memory instead of freeing it. I think it's a really good idea to have a memory pool for performance reason, but why is there no 'free block' limit ? Python is a really really good language that can do many things in a clear, easier and performance way I think. It has always feet all my needs. But I can't imagine there is no good solution for that problem, by limiting the free block pool size or best, letting the user specify this limit and even better, letting the user completely freeing it (with also the limit manual specification) Like: import pool pool.free() pool.limit(size in megabytes) Why not letting the user choosing that, why not giving the user more flexibility ? I will try later under linux with the latest stable python Regards, FP -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
On Thu, 31 May 2007 07:59:35 -0700, Warren Stringer wrote: Still I prefer funcs[:]() Because, I can describe it in English as call everything that funcs has But that's not what it says. It says, call a copy of funcs. The simplest, most straightforward way of calling everything that funcs has is simply: for func in funcs: func() By the way... if you're worried about saving keystrokes on your mobile phone, why don't you do your development on a PC and upload it to the phone when it is done? Or have I misunderstood? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On May 31, 5:59 pm, Warren Stringer [EMAIL PROTECTED] wrote: Still I prefer funcs[:]() Because, I can describe it in English as call everything that funcs has Wouldn't funcs() be even better? It's shorter, and it seems like that's the only thing you're striving for. Why do you want to put the [:] in there all the time? -- http://mail.python.org/mailman/listinfo/python-list
RE: Is PEP-8 a Code or More of a Guideline?
Perhaps a foot pedal? Hmmm My two cellphones don't like underbars very much. And the shift key -- while much easier -- still is cumbersome. If outlook didn't autocaps on me, this message would be in all lowercase. In fact, when communicating with friends from outlook, to their sms, I take the trouble to correct my outlook's autocorrect. underbars are more of a reach and harder to read when you use a really nice font. camelBack -- damn, I just had to correct outlook's autocorrect on camelback -- so, what was I saying, oh yes -- camelBackNames are just freaking weird. So i.prefer.dots-- no, seriously sure it's slow, but forces you the think about names in a new way. or, perhaps going deep is sacrilege? -Original Message- From: [EMAIL PROTECTED] [mailto:python-list- [EMAIL PROTECTED] On Behalf Of Christophe Sent: Thursday, May 31, 2007 6:18 AM To: python-list@python.org Subject: Re: Is PEP-8 a Code or More of a Guideline? Joe Riopel a écrit : Each requires exactly the same number of key strokes when I do the math. (Too lazy to explain further...) foo_bar f, o, o, shift + underscore, b, a, r = 8 fooBar f, o, o, shift + b, a, r = 7 f, o, o, _, b, a, r = 7f, o, o, shift + b, a, r = 8 Also the shift+b is much more work than 2 keypresses IMHO. On the other hand, the underscore is done by pressing the 8 key without any other modifier which is very easy and accessible. Yeap, french layout rules for that naming convention :)-- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Form/Page and Navigation with multiple buttons
mosscliffe wrote: Excellent - thanks for all your help. I now have a form created by a python script executing an HTML page, doing everything I need, except for Session Data (probably use hidden fields ?? future research) and the actual paging logic !!! In fact you should find you can name all of the buttons the same. Then when you click one the value associated with that name tells you which button the user pressed. Just don't call your button submit, since that masks a JavaScript form method that you will probably end up using sooner or later. If I use a link. I have to add all my hidden fields to the query string, otherwise cgi.FieldStorage(), does not return the hidden fields. This would also mean users see all the hidden field data. Is there another way, other than a cookie ? Why is a link better than a button ? Beats me why you got that advice. Buttons are perfectly adequate for that purpose. However, you can if you want use links with javascript: ... href values to accomplish local scripting which can do funky stuff like setting form field values and submitting the form. This can get tricky though, and it sounds like you are maybe a little too new to the web to be messing with client-side scripting. Later ... I have been using 'post' for my form, to eliminate the displaying of field values. That does make the location bar easier on the user's eye, and is the standard way to proceed. It doesn't add anything in the way of security, however. I accept I am quite niave about FORM/HTML logic. We all have to start somewhere! regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
Re: How to clean a module?
ai a écrit : It assumes that there is a module A which have two global variables X and Y. If I run import A in the IDLE shell, then I can use A.X and A.Y correctly. But if I want to change the module A and then delete the variable Y, I find I can use A.Y just the same as before! It's unlikely to be true, see below. In fact, I have tried all the following methods but can't remove the A.Y: execute import A again reload(A) del A; import A Yes, if you use del A.Y, it works. But it is stupid since there are probably many names. In my thought, if no one references objects in A, del A will release all memory about A. But it seems that the fact is not. So I can not refresh the namespace to follow changes of a module easily and I will worry about the memory if I del a module. I want to know if there is a way to clear a module entirely. Actually I do not see your problem and your exact need, when I type the following in python prompt I just see expected behavior, what is a problem to you ? Maybe you could post a code explaining it. In [64]: import a In [65]: a.X Out[65]: 0 In [66]: a.X = 2 In [67]: del a In [68]: import a as b In [69]: b.X Out[69]: 2 In [71]: for name in [ n for n in b.__dict__ if not n.startswith('__') ] : : b.__dict__.__delitem__(name) : : In [72]: b.X --- type 'exceptions.AttributeError'Traceback (most recent call last) C:\Documents and Settings\maric\Bureau\ipython console in module() type 'exceptions.AttributeError': 'module' object has no attribute 'X' In [73]: reload(b) Out[73]: module 'a' from 'a.pyc' In [74]: b.X Out[74]: 0 In [75]: del b.X In [76]: del b In [77]: import a In [78]: a.b --- type 'exceptions.AttributeError'Traceback (most recent call last) C:\Documents and Settings\maric\Bureau\ipython console in module() type 'exceptions.AttributeError': 'module' object has no attribute 'b' -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
How is it more expressive? In the context you're concerned with, c[:] is the exactly same thing as c. You seem to be worried about saving keystrokes, yet you use c[:] instead of c. It's like having an integer variable i and using ((i+0)*1) instead of i. Nope, different. c[:] holds many behaviors that change dynamically. So c[:]() -- or the more recent go(c)() -- executes all those behaviors. This is very useful for many performers. The real world example that I'm working one is a collaborative visual music performance. So c can contain wrapped MIDI events or sequencer behaviors. c may get passed to a scheduler to execute those events, or c may get passed to a pickler to persist the performance. -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
On 2007-05-31, Warren Stringer [EMAIL PROTECTED] wrote: How is it more expressive? In the context you're concerned with, c[:] is the exactly same thing as c. You seem to be worried about saving keystrokes, yet you use c[:] instead of c. It's like having an integer variable i and using ((i+0)*1) instead of i. Nope, different. c[:] holds many behaviors that change dynamically. I've absolutely no clue what that sentence means. If c[:] does behave differently than c, then somebody's done something seriously weird and probably needs to be slapped around for felonious overriding. So c[:]() -- or the more recent go(c)() -- executes all those behaviors. Still no clue. This is very useful for many performers. What are performers? The real world example that I'm working one is a collaborative visual music performance. So c can contain wrapped MIDI events or sequencer behaviors. c may get passed to a scheduler to execute those events, or c may get passed to a pickler to persist the performance. I still don't see how c[:] is any different from c. -- Grant Edwards grante Yow! TONY RANDALL! Is YOUR at life a PATIO of FUN?? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: c[:]()
Grant Edwards wrote: On 2007-05-31, Warren Stringer [EMAIL PROTECTED] wrote: How is it more expressive? In the context you're concerned with, c[:] is the exactly same thing as c. You seem to be worried about saving keystrokes, yet you use c[:] instead of c. It's like having an integer variable i and using ((i+0)*1) instead of i. Nope, different. c[:] holds many behaviors that change dynamically. I've absolutely no clue what that sentence means. If c[:] does behave differently than c, then somebody's done something seriously weird and probably needs to be slapped around for felonious overriding. So c[:]() -- or the more recent go(c)() -- executes all those behaviors. Still no clue. This is very useful for many performers. What are performers? The real world example that I'm working one is a collaborative visual music performance. So c can contain wrapped MIDI events or sequencer behaviors. c may get passed to a scheduler to execute those events, or c may get passed to a pickler to persist the performance. I still don't see how c[:] is any different from c. It isn't. The OP is projecting a wish for a function call on a list to be interpreted as a call on each member of the list with the same arguments. The all-members slice notation is a complete red herring. It would require a pretty fundamental re-think to give such a construct sensible and consistent semantics, I think. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list