[ANN] Leipzig Python User Group - Meeting, October 13, 2009, 08:00pm
=== Leipzig Python User Group === We will meet on Tuesday, October 13 at 8:00 pm at the training center of Python Academy in Leipzig, Germany ( http://www.python-academy.com/center/find.html ). Food and soft drinks are provided. Please send a short confirmation mail to i...@python-academy.de, so we can prepare appropriately. Everybody who uses Python, plans to do so or is interested in learning more about the language is encouraged to participate. While the meeting language will be mainly German, we will provide English translation if needed. Current information about the meetings are at http://www.python-academy.com/user-group . Mike == Leipzig Python User Group === Wir treffen uns am Dienstag, 13.10.2009 um 20:00 Uhr im Schulungszentrum der Python Academy in Leipzig ( http://www.python-academy.de/Schulungszentrum/anfahrt.html ). Für das leibliche Wohl wird gesorgt. Eine Anmeldung unter i...@python-academy.de wäre nett, damit wir genug Essen besorgen können. Willkommen ist jeder, der Interesse an Python hat, die Sprache bereits nutzt oder nutzen möchte. Aktuelle Informationen zu den Treffen sind unter http://www.python-academy.de/User-Group zu finden. Viele Grüße Mike -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
ANN: next pyCologne meeting 14.10.2009 18:30 p.m.
[German announcement, forwarded from pyCologne mailing list] Hallo liebe Pythonfreunde, das nächste Treffen von pyCologne, der Kölner Python-UserGroup, findet statt: Datum: Mittwoch, den 14.10.2009 Uhrzeit: 18:30 Uhr c.t. Ort: Pool 0.14, Benutzerrechenzentrum (RRZK-B) der Universität Köln, Berrenrather Str. 136, 50937 Köln Programm: - Google Wave (Andi Albrecht, Florian Scheel) Ab ca. 20:30 Uhr werden wir den Abend gemütlich in einem nahe gelegenen Restaurant/Kneipe ausklingen lassen (al Caminetto - Berrenratherstrasse 202). Weitere Information zu pyCologne, inkl. Wegbeschreibung, Fotos und Protokollen vergangener Treffen usw., findet ihr auf unserer Seite im deutschen Python Wiki: http://wiki.python.de/pyCologne [momentan erreichbar unter: http://wiki.python-forum.de/pyCologne Chris] Viele Grüße, Thomas -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Docutils 0.6 released
Good morning, Release 0.6 is out. Changes are : * Two new writers for ODT and manpage (so there is no excuse for python software not having a manpage anymore). * Python2.2 is no longer supported. Release 0.6 is compatible with Python versions from 2.3 up to 2.6 and convertible to 3.1 code. * The newlatex writer is orphaned. * The LaTeX2e writer sports templates now and is the most active worked on part. There might be some suprises due to new defaults, but we tried to minimize breakage and choose sensible defaults. * The HTML writer supports a comma separated list of stylesheets. * Some changes to reStructuredText many thanks to all contributors. have a nice start into a new week. engelbert -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Python-3.2 (SVN) bug [was syntax question]
I wrote I'm trying to build the recent Python-3.2a (SVN). It fails in Lib/tokenize.py (line 87) 85 def group(*choices): return '(' + '|'.join(choices) + ')' 86 def any(*choices): return group(*choices) + '*' 87 def maybe(*choices): return group(*choices) + '?' with: TypeError: group() argument after ** must be a mapping, not tuple Meanwhile I could narrow this down to the --with-tsc configure option. Without it, it builds just fine. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
a=[1,2,3,4].reverse() - why a is None?
-- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to handle changing list of class imports
Dave Angel wrote: For that, I'd suggest reserving a directory at a known location, doing an os.path.dirname() on that directory, and building a list of module names. Then use __import__() to load them, and build a list of module objects, and a list of classes in those modules. Suggest classname to be simply formed by uppercasing the first letter of the module file. Another possibility would be to require each student's module to define a factory function with a standard name, such as 'create_strategy', so you wouldn't have to deal with a different class name in each module. Also, an alternative to using __import__() would be to use execfile() to load and execute the student's code. Then you wouldn't have to put the directory containing the students' modules on the import path, and they wouldn't get put into sys.modules, which would help to isolate them from each other. (Otherwise a student could cheat by importing someone else's stragegy class and passing it off as their own!) However, each student's submission would more or less be restricted to a single file in that case, whereas using __import__() would allow it to be a package with submodules. Whether that's a serious disadvantage depends on how big and complicated you expect the submissions to be. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: a=[1,2,3,4].reverse() - why a is None?
The reverse function is a function to reverse the list in place, not a function to get the reverse of the list: x = [1,2,3,4] y = x z = x.reverse() will result in: x = y = [4,3,2,1] z = None -- André Engels, andreeng...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: a=[1,2,3,4].reverse() - why a is None?
Andre Engels wrote: The reverse function is a function to reverse the list in place, not a function to get the reverse of the list: x = [1,2,3,4] y = x z = x.reverse() will result in: x = y = [4,3,2,1] z = None .reverse returns None. See the documentation. -- Erik Max Francis m...@alcyone.com http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM/Y!M/Skype erikmaxfrancis Sometimes a cigar is just a cigar. -- Sigmund Freud -- http://mail.python.org/mailman/listinfo/python-list
Re: a=[1,2,3,4].reverse() - why a is None?
...becauase you were looking for: reversed([1,2,3,4]) Chris -- Simplistix - Content Management, Batch Processing Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
SocketServer
This may not be the correct list for this issue, if so I would appreciate if anyone could forward it to the correct list. I had experienced a number of problems with standard library SocketServer when implementing a tcp forking server under python 2.6. I fixed every issue including some timing problems (e.g. socket request closed too fast before the last packet was grabbed) by overriding or extending methods as needed. Nonetheless, the one issue which may require a wider attention had to deal with method collect_children() of class TCPServer. This method makes the following os library call: pid, result = os.waitpid(child, options=0) Under some conditions the method breaks on this line with a message indicating that an unexpected keyword argument options was provided. In a continuous run reading thousands of packets from multiple client connects, this line seems to fail at times, but not always. Unfortunately, I did not record the specific conditions that caused this erroneous error message, which happened unpredicatbly multiple times. To correct the problem the line of code may be changed by removing the keyword to: pid, result = os.waitpid(child, 0); this never fails. Nonetheless, I believe that method collect_children() is too cumbersome as written and I did override it with the following simpler strategy. The developers of SocketServer may want to consider it as a replacement to the current code used for collect_children(). def collect_children(self): '''Collect Children - Overrides ForkingTCPServer collect_children method. The provided method in SocketServer modules does not properly work for the intended purpose. This implementation is a complete replacement. Each new child process id (pid) is added to list active_children by method process_request(). Each time a new connection is created by the method, a call is then made here for cleanup of any inactive processes. Returns: None ''' child = None try: if self.active_children: # a list of active child processes for child in self.active_children: try: val = os.waitpid(child, os.WNOHANG) # val = (pid, status) if not val[0]:# pid 0; child is inactive time.sleep(0.5) # wait to kill os.kill(child, signal.SIGKILL) # make sure it is dead self.active_children.remove(child) # remove from active list else: continue except OSError, err: if errno.ECHILD != err.errno: # do not report; child not found msg = '\tOS error attempting to terminate child process {0}.' self.errlog.warning(msg.format(str(child))) else: pass except: msg = '\tGeneral error attempting to terminate child process {0}.' self.errlog.exception(msg.format(str(child))) else: pass# for child loop else: pass except: msg = '\tGeneral error while attempting to terminate child process {0}.' self.errlog.exception(msg.format(str(child))) Things to note are: 1. Using os.WNOHANG instead of 0 as options values to os.waitpid 2. Detecting if we get a returned pid==0; hence assume child is done 3. Attempt a os.kill for defunct children after a time.sleep(0.5); allow dependent processes to complete their job before totally closing down the request. 4. Report os errors as exceptions; but not errno.ECHILD, which means trying to kill none existing child; keep this as a warning. This is more suscinct code and does the job. At least it does it for me. Thanks, Boris -- http://mail.python.org/mailman/listinfo/python-list
Multiprocessing Fail
This code fails: ## from multiprocessing import Manager manager = Manager() ns_proxy = manager.Namespace() evt_proxy = manager.Event() ns_proxy.my_event_proxy = evt_proxy print ns_proxy.my_event_proxy ## Traceback (most recent call last): File test_nsproxy.py, line 39, in module print ns_proxy.my_event_proxy File /usr/lib64/python2.6/multiprocessing/managers.py, line 989, in __getattr__ return callmethod('__getattribute__', (key,)) File /usr/lib64/python2.6/multiprocessing/managers.py, line 740, in _callmethod raise convert_to_error(kind, result) multiprocessing.managers.RemoteError: --- Unserializable message: ('#RETURN', threading._Event object at 0x1494790) --- This code creates a manager, uses the manager to create a Namespace and an Event. We store the proxies in variables 'ns_proxy' and 'evt_proxy' respectively. We set the name 'my_event_proxy' on the namespace proxy with the event proxy. This appears to pickle, transmit, and store the event proxy successfully. However, when we attempt to read back the event proxy from the namespace proxy, we get an exception. It appears that the namespace is attempting to return the real event and not the proxy and, of course, the real event is not pickable. The same error occurs if we substitute a dict or a list for the Namespace or any of the synchronization primitives for Event. The docs seem to indicate that nesting of manager elements should work. What is wrong here, multiprocessing's docs or its implementation? I tested this on: Python 2.6.2 (r262:71600, Sep 14 2009, 18:47:57) [GCC 4.3.2] on linux2 and: Python 2.7a0 (trunk:75375, Oct 11 2009, 17:50:44) [GCC 4.3.2] on linux2 with the same results on both. -Terrence -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Java - Perché i pythonisti ce l'hanno tanto con Java?
Enrico Franchi ha scritto: spazza spa...@alum.com wrote: ...snip... Non mi pare che al momento Python sia in grado di reggere tutto questo. Scusa, proseguendo in questa maniera andiamo pesantemente OT. Rimane pero' il problema di *dimostrare* la tua affermazione. Da quanto leggo, mi sembra che tu di Python sappia circa nulla e di conseguenza stai facendo affermazioni di inadeguatezza su una piattaforma che non conosci. Hai ragione, stiamo andando OT; però consideriamo solo questo: devi costruire un'applicazione per accedere ad un DB Oracle non nuovissimo che sai verrà aggiornato prima o poi. Cosa ti serve per Java e dove lo trovi? Scarichi direttamente dal sito Oracle il driver JDBC ultima release, che funziona con tutte le versioni più recenti di Java, e puoi sviluppare l'applicatione sul tuo PC, trasportandola poi su un altro ambiente senza colpo ferire. Al più, se hai prodotti molto datati, tipo Oracle DB 8.x o Java 1.3, devi prendere una versione del driver un po' più vecchia, tutto qui. Ma è molto probabile che l'applicazione continuerà a funzionare anche aggiornando in seguito il driver. Stessa situazione, cosa server con Python? Intanto, non è chiarissimo dove trovare il necessario: su OTN (Oracle) c'è scritto di usare cx_Oracle, ma ovviamente Oracle non ti supporta e dopo che hai speso svariati keuro per il canone di assistenza non è proprio il massimo. Poi, in ogni caso, cx_Oracle richiede l'installazione del client Oracle, che anche nella versione Instant è un affare abbastanza intrusivo e comunque è dipendente dal sistema operativo. Poi devi trovare tra i vari file di cx_Oracle la combinazione giusta tra versione di Python, versione dei driver Oracle e versione del sistema operativo corrispondente alla tua situazione. Se ti va male, es. usi Solaris, ti tocca anche provare a ricompilarlo. Quasi sicuramente, al primo upgrade massiccio del sistema in servizio devi ricominciare da capo. Non è nulla di impossibile, ma ritornando al punto: ti sembra praticabile da tutti? Ti sembra una soluzione sostenibile a medio/lungo termine in una realtà aziendale? -- http://mail.python.org/mailman/listinfo/python-list
Re: strange behaviour when inheriting from tuple
On Oct 11, 3:04 am, metal metal...@gmail.com wrote: Environment: PythonWin 2.5.4 (r254:67916, Apr 27 2009, 15:41:14) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. Evil Code: class Foo: def __init__(self, *args): print args Foo(1, 2, 3) # (1, 2, 3), good class Bar(tuple): def __init__(self, *args): print args Bar(1, 2, 3) # TypeError: tuple() takes at most 1 argument (3 given) what the heck? I even didn't call tuple.__init__ yet When subclassing immutable types you'll want to override __new__, and should ensure that the base type's __new__ is called: __ class MyTuple(tuple): __ def __new__(cls, *args): __ return tuple.__new__(cls, args) __ print MyTuple(1, 2, 3) (1, 2, 3) See http://www.python.org/download/releases/2.2.3/descrintro/#__new__ -- http://mail.python.org/mailman/listinfo/python-list
Re: save windows clipboard content temporarily and restore later
kakarukeys: I followed your hints, and wrote the following code. It works for most clipboard formats except files. Selecting and copying a file, followed by backup() and restore() throw an exception: For some formats the handle stored on the clipboard may not be a memory handle so may not be retrieved as memory. You could try using a list of formats to include or exclude or just pass over the exception. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: Plotting multiple datasets with gnuplot
On Oct 9, 1:36 pm, Rob Garrett rgagarr...@gmail.com wrote: Hi, I'm trying to get gnuplot to display multiple data series on a single plot using gnuplot in python. I've searched around and haven't found a solution to how to do this when I have a variable-length list of plots to add. What module are you using for interfacing python to gnuplot? I was using gnuplot.py (http://gnuplot-py.sourceforge.net) package and it was pretty easy to plot variable number of datasets on a single plot with or without multiplot (however more than seven datasets per plot looks ugly imho). In this case all you have to do is to create a proper string with commands and pass it to gnuplot. S.H. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
Steven D'Aprano wrote: Back in ancient days when dinosaurs walked the Earth, and I was programming in THINK Pascal on Apple Macintosh System 6, I'd go into nervous palpitations writing the equivalent of while True because if I got it wrong, I'd lock up the machine and need to hit the power button. That was true when just about *anything* went wrong in that environment, though -- I don't think you can blame while True in particular for it. (I remember my earliest Mac programming experiences, back when the Mac was too small to run its own development environment, and everything had to be cross-compiled. Debugging consisted of counting the number of times SysBeep got called before the bomb icon appeared...) -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Poll on Eval in Python
On 10.10.2009 5:03, Kazimir Majorinc wrote: I am Lisp programmer and I write an article on issues as macros, fexprs and eval. I want to compare opinions of programmers of various programming languages on eval. If you want to contribute your opinion on eval in Python (or you want to look at result), the adress is: I need more voters, if you can, please. blog: http://kazimirmajorinc.blogspot.com Thank you -- Kazimir Majorinc -- http://mail.python.org/mailman/listinfo/python-list
RE: a=[1,2,3,4].reverse() - why a is None?
Chris Withers wrote: ...becauase you were looking for: reversed([1,2,3,4]) OK, but my question is generic. Why when I use object's function that changed values of the object, I can't to get value of it on the fly without writing additional code? a=[1,3,2,4] a.sort() a.reverse() a [4, 3, 2, 1] Why I can't a==[1,3,2,4].sort().reverse() ? -- http://mail.python.org/mailman/listinfo/python-list
Daemon call python program
I have a daemon process which will call a python program. What do I do if I want to dump the exception when the python program exist by uncaught exception. Thanks a lot! -- [1;36m※Post by [37mcommand [36mfrom [33m59-124-255-226.HINET-IP.[m [1;36m老鼠的香香乳酪洞[31m˙[33m電子佈告欄系統[31m˙[32malexbbs.twbbs.org[31m˙[37m140.113.166.7[m -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
kj wrote: I'm coaching a group of biologists on basic Python scripting. One of my charges mentioned that he had come across the advice never to use loops beginning with while True. It's possible this is something he was told in relation to another language that has more options. For example, in C there's for(;;) as an alternative, although there's not much to choose between them. Also you can often use an assignment-as-condition trick to squeeze a loop-and- a-half into a while(), and you have do-while loops for testing at the end. Python is much more limited -- anything which isn't a for has to be a while of some shape, so it's harder to avoid while True without introducing extra complexities into the code. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: code in a module is executed twice (cyclic import problems) ?
Dave Angel wrote: The point you should get from that link is Don't do circular imports. Ever. No, I would say the lesson to be learned from this is don't use the same file as both a main script and an imported module. I would create another file called e.g. 'main.py' that simply contains import B and use that as the main script. Another benefit is that the compiled bytecode of B will be saved, so it will start up faster the next time you run it. That won't happen if you use B directly as a main script. (Circular imports are a different issue. There are perfectly legitimate uses for them, and they're fine as long as you understand the potential pitfalls and take steps to avoid them. Although it's probably best to avoid them until you do understand all the issues.) -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of Tkinter and IDLE
On Oct 12, 7:29 am, r rt8...@gmail.com wrote: Obviously you have never used packages that are meant for global importing or you would know how such systems are designed. OpenGL is a good example. OpenGL has over 3600 functions and constants all of which start with gl and GL respectivly. However the Tkinter package is not a good candidate for this in real use cases. Not only do you have all the widget classes and functions you have the constants imported too. ~180 names are imported this way, far too many when not protected by a naming convention! However learning to use Tkinter for the beginner is much eaiser when using global imports and i think that is OK. But very shortly after it is a good idea to get in the habit of quialifing names with tk.thisorthat(). I suppose you are right about that one, the largest things I've ever had to imported tops out around ~600 names; although only used in interactive mode, not finished product. One thing you should also learn about me, is I do not deal in absolutes. If you don't understand the meanings associated with that, then try importing yourbrain.reflection into a private namespace. On Oct 12, 7:29 am, r rt8...@gmail.com wrote: Sarcasm anyone? If you can't stand sarcasm, you are living on the wrong planet. On Oct 12, 7:29 am, r rt8...@gmail.com wrote: Yes IDLE is not meant for writing million line scripts but who would want to anyway? I would assume that is obvious 8=), however any editing interface may be used for writing million line anythings -- just look at ed http:// en.wikipedia.org/wiki/Ed_(text_editor). On Oct 12, 7:29 am, r rt8...@gmail.com wrote: You may find the IDLE and Tkinter useless but many people find both to be indispensable (especially noobs). I think this is a case of champagne taste's on a whiskey budget for you friend! You are both right and wrong: I find IDLE useless because I edit code written in more then one (programming) language, thus any editor that is not (more) language agnostic is useless to me, and probably every other programmer that refuses to waste time learning an IDE per language (and so on). Tkinter however is not, because it is an interface to Tk ;). Ok, if you have a broken display , then it is probably useless, guess you are right on that one too. I said I had never used Tk, not that it was useless. Depending on your style of parsing English, one could also call me a liar (or a louse), as I have used programs built on Tk but have never written programs with Tk. I'll leave individual readers to determine that result. On Oct 12, 7:29 am, r rt8...@gmail.com wrote: NO TEXT EDITOR SHOULD EVER COPY AN EMPTY STRING TO THE CLIPBOARD!! No, that is probably wrong. No it's exactly right and a one-liner to fix. And btw: pass the reefer because it ain't just whiskey clouding your mind fella! Adding data to the clipboard belongs in the program, the decision of *what* to place in the clipboard (generally) belongs with the user and not to their program. Mistakenly overwriting the contents of a buffer that you meant to retain for a longer period of time, is not the buffers problem. Get it? As I do not believe in absolutes, I therefore believe that there are times where my statement is False, in this case however I believe it is True. If you do not agree, then we have a _philosophical_ difference of opinion, and should agree to disagree. Also the whiskey thing was an obscured reference to a song, not a reference to my blood alcohol level. Which is probably much lower then whoever created Tkinter from the looks of both the package and your comments. On Oct 12, 7:29 am, r rt8...@gmail.com wrote: Why do you reply to a thread about a subject you obviously don't care about? Where I come from, one would say that you asked for feedback: On Aug 27, 9:22 pm, r rt8...@gmail.com wrote: - Final Thoughts - Well, that is all i can remember for now. If you've made it this far without losing your temper or your lunch well i am very surprised ;). Anyway, give me some feedback on these ideas so maybe i can get motivated to submit some patches/enhancements. psst... help is welcome too ya'know :) –noun 1. Electronics. a. the process of returning part of the output of a circuit, system, or device to the input, either to oppose the input (negative feedback) or to aid the input (positive feedback). 5. Psychology. knowledge of the results of any behavior, considered as influencing or modifying further performance. Compare biofeedback. Now if you only wanted Yes sir, that is a jolly good idea types of response, you should be more explicit about not wanting differing opinions included. On Oct 12, 7:29 am, r rt8...@gmail.com wrote: If you've never used Tkinter or IDLE (and never will) you have no reason to reply except for
How to transfer a string from cgi at server side to a javascript function at client side as an argument?
Hi everyone, How can I transfer a string from a cgi at server side to a javascript function at client side as an argument? Here is my case: 1. client side: javascript in html page: ... mygrid = new dhtmlXGridObject('gridbox'); ... var cgi3 = /bop-cgi/xbop; cgi3 += ?requestIds=[wisco.mProducts.dboProducts.mySearch]; cgi3 += amp;wisco.mProducts.dboProducts.searchString=1=1; mygrid.loadXML(cgi3); 2. server side cgi: wisco.mProducts.dboProducts.mySearch ... def mySearch(self): self.search() row_count = self.response['rowCount'] myStr = rows total_count=%s pos=%s% (row_count, 1) for i in range(len(self.response['dbcCode'])): a = self.response['dbcCode'][i] c = self.response['dbcId'][i] myStr = myStr + row id = '%s%c + ' myStr = myStr + cell + a + /cell myStr = myStr + cell%s%c + /cell myStr = myStr + /row myStr = myStr + /rows ... I want the myStr to be transferred to mygrid.loadXML like: mygrid.loadXML('rows total_count=100 pos=1row id=2cellx/cell/row/rows') Any ideas? Thanks in advance for your help. ouyang -- http://mail.python.org/mailman/listinfo/python-list
Re: Daemon call python program
※ 引述《command (找尋自己的一片天)》之銘言: : I have a daemon process which will call a python program. : What do I do if I want to dump the exception when the python program exist : by uncaught exception. : Thanks a lot! By the way, the python program is multi-thread -- [1;36m※Post by [37mcommand [36mfrom [33m59-124-255-226.HINET-IP.[m [1;36m老鼠的香香乳酪洞[31m˙[33m電子佈告欄系統[31m˙[32malexbbs.twbbs.org[31m˙[37m140.113.166.7[m -- http://mail.python.org/mailman/listinfo/python-list
Re: mxDateTime history (Re: mktime, how to handle dates before 01-01-1970 ?)
MRAB wrote: And when someone says January 30, do they really mean the day before the last day of the month? No, no, that's January -2, a *completely* different thing! -- Greg -- http://mail.python.org/mailman/listinfo/python-list
RE: a=[1,2,3,4].reverse() - why a is None?
Nadav Chernin wrote: Chris Withers wrote: ...becauase you were looking for: reversed([1,2,3,4]) OK, but my question is generic. Why when I use object's function that changed values of the object, I can't to get value of it on the fly without writing additional code? a=[1,3,2,4] a.sort() a.reverse() a [4, 3, 2, 1] Why I can't a==[1,3,2,4].sort().reverse() ? This is a FAQ. The reasoning is that operations that modify a collection in place (the same goes for .sort()) don't return the collection to prevent errors from creeping up like this: unsorted = ... sorted = unsorted.sort() where the assumption is that unsorted is still that - unsorted. You can read a lot of the pro + cons on this NG/ML if you google for it, but you won't reach a change in semantics. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: New hire
Emeka wrote: Hello All, I am new to python , and my aim is to use it to write sugar-based applications on XO(OLPC). I am not new to programming in general, I would want to know the best route to take in learning python. I have background in FP and Imperative languages. Regards, Emeka Welcome. http://wiki.python.org/moin/BeginnersGuide/Programmers JM -- http://mail.python.org/mailman/listinfo/python-list
start external program from python
Hi, I woul like to start a program from within python (under linux): This works fine: import os path = 'tclsh AppMain.tcl hej.gb' os.system(path) The file AppMain.tcl is the executable and the file hej.gb is a textfile in the same directory. The text file gets opened in the app in the correct way. I wonder if I could pass information from the clipboard to the AppMain.tcl instead of the file hej.gb ? I use wxPython. any comment is appreciated! /bjorn -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-3.2 (SVN) bug [was syntax question]
On Oct 12, 7:55 am, Helmut Jarausch jarau...@igpm.rwth-aachen.de wrote: I wrote I'm trying to build the recent Python-3.2a (SVN). It fails in Lib/tokenize.py (line 87) 85 def group(*choices): return '(' + '|'.join(choices) + ')' 86 def any(*choices): return group(*choices) + '*' 87 def maybe(*choices): return group(*choices) + '?' with: TypeError: group() argument after ** must be a mapping, not tuple It looks like there's already a tracker issue open for this (or for something that looks an awful lot like this issue): http://bugs.python.org/issue6603 but work on that bug has stalled, because core developers have been unable to reproduce the problem. It would be really helpful if you could add a comment to that bug report, giving as much system information (including compiler information) as possible. If you can come up with any ideas about what might be causing the failure, that would also be useful. Like Antoine, I'd be inclined to suspect that it's a compiler bug, but it could also be caused by some not-quite-standards-compliant C code in Python somewhere. What happens if you turn compiler optimizations off? (E.g., by editing configure.in to remove all occurrences of '-O3' and then rerunning autoconf and autoheader.) Thanks, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: a=[1,2,3,4].reverse() - why a is None?
On Mon, Oct 12, 2009 at 10:44 AM, Nadav Chernin nada...@qualisystems.com wrote: Chris Withers wrote: ...becauase you were looking for: reversed([1,2,3,4]) OK, but my question is generic. Why when I use object's function that changed values of the object, I can't to get value of it on the fly without writing additional code? a=[1,3,2,4] a.sort() a.reverse() a [4, 3, 2, 1] Why I can't a==[1,3,2,4].sort().reverse() ? I think it is to avoid programming mistakes. If reverse() or sort() returned the reversed or sorted list, people are prone to using them for that purpose, and you get people wondering why b = [1,2,3,4] a = b.reverse() would change the value of b. By having functions and methods have either return a value but not have a side effect (that is, changing variables or objects), or have a side effect but not return a value, one eliminates the risk that people use a function to obtain a value but do not realize its side effect. -- André Engels, andreeng...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: mxDateTime history (Re: mktime, how to handle dates before 01-01-1970 ?)
greg g...@cosc.canterbury.ac.nz (g) wrote: g MRAB wrote: And when someone says January 30, do they really mean the day before the last day of the month? g No, no, that's January -2, a *completely* different thing! But for someone else it would be February -2. -- Piet van Oostrum p...@vanoostrum.org WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] -- http://mail.python.org/mailman/listinfo/python-list
Re: postprocessing in os.walk
kj wrote: Perl's directory tree traversal facility is provided by the function find of the File::Find module. This function accepts an optional callback, called postprocess, that gets invoked just before leaving the currently processed directory. The documentation goes on to say This hook is handy for summarizing a directory, such as calculating its disk usage, which is exactly what I use it for in a maintenance script. This maintenance script is getting long in the tooth, and I've been meaning to add a few enhancements to it for a while, so I thought that in the process I'd port it to Python, using the os.walk function, but I see that os.walk does not have anything like this File::Find::find's postprocess hook. Is there a good way to simulate it (without having to roll my own File::Find::find in Python)? TIA! kynn Why would you need a special hook when the os.walk() generator yields exactly once per directory? So whatever work you do on the list of files you get, you can then put the summary logic immediately after. Or if you really feel you need a special hook, then write a wrapper for os.walk(), which takes a hook function as a parameter, and after yielding each file in a directory, calls the hook. Looks like about 5 lines. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: mxDateTime history (Re: mktime, how to handle dates before 01-01-1970 ?)
On Mon, Oct 12, 2009 at 4:27 AM, Piet van Oostrum p...@cs.uu.nl wrote: greg g...@cosc.canterbury.ac.nz (g) wrote: g MRAB wrote: And when someone says January 30, do they really mean the day before the last day of the month? g No, no, that's January -2, a *completely* different thing! But for someone else it would be February -2. And for still others, it's the last $DAYOFWEEK of the month, which just happened to fall on the 30th. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: code in a module is executed twice (cyclic import problems) ?
greg wrote: div class=moz-text-flowed style=font-family: -moz-fixedDave Angel wrote: The point you should get from that link is Don't do circular imports. Ever. No, I would say the lesson to be learned from this is don't use the same file as both a main script and an imported module. I would create another file called e.g. 'main.py' that simply contains import B and use that as the main script. Another benefit is that the compiled bytecode of B will be saved, so it will start up faster the next time you run it. That won't happen if you use B directly as a main script. (Circular imports are a different issue. There are perfectly legitimate uses for them, and they're fine as long as you understand the potential pitfalls and take steps to avoid them. Although it's probably best to avoid them until you do understand all the issues.) You prove my point by trying to contradict it. Importing a script from the same or another module is a circular import, and therefore should be avoided. If you understand all the issues, you can get away with it, but few programmers understand them all like they think they do. The *only* difference between this circular import and any other is that the problems it can trigger are a little more obvious, and a lot more likely. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Why ELIF?
TerryP wrote: Somehow I doubt that Look up X in dictionary D could ever be more efficient (in terms of space and time, at least) then Check if X is equal to Y. It's not about what you get in runtime but what you get in monkey time. Most expressions that would make someone reach for a C-like switch() statement can be expressed with dictionaries or attributes instead. Here is a dorks approach to calling a specific function with arguments based on a command: ... Here is more of a look up table approach: ... Neat -- thanks for sharing this TerryP Esmail -- http://mail.python.org/mailman/listinfo/python-list
deepcopy of class inherited from Thread
Dear All I am running this piece of code: from threading import Thread import copy class Ashish(Thread): def __init__(self, i): Thread.__init__(self) self.foo = i def run(self): print (self, self.foo) d= Ashish(4) e = copy.deepcopy(d) --- Exception here d.start() e.start() d.join() e.join() But I am getting this error: Traceback (most recent call last): File D:\Profiles\ntb837\Desktop\threadprob.py, line 13, in module e = copy.deepcopy(d) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 295, in _reconstruct state = deepcopy(state, memo) File C:\Python31\lib\copy.py, line 146, in deepcopy y = copier(x, memo) File C:\Python31\lib\copy.py, line 235, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 295, in _reconstruct state = deepcopy(state, memo) File C:\Python31\lib\copy.py, line 146, in deepcopy y = copier(x, memo) File C:\Python31\lib\copy.py, line 235, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 280, in _reconstruct y = callable(*args) File C:\Python31\lib\copyreg.py, line 88, in __newobj__ return cls.__new__(cls, *args) TypeError: object.__new__(_thread.lock) is not safe, use _thread.lock.__new__() Could someone please help me find a solution? Regards, Ashish Vyas -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Sunday 11 October 2009 11:56:55 pm Dennis Lee Bieber wrote: In this situation, the middle exit works best -- using non-optimal Python while True: lin = file_object.readline() if not lin: break do something with lin Actually, in python, this works even better: for lin in iter(file_object.readline, ): ... do something with lin -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: best vi / emacs python features
On Wed, 2009-10-07, OdarR wrote: hello, * this is not a troll * which kind of help you have with your favorite editor ? Syntax highlighting and help with the indentation (move to the right after an else:, keep in the same column normally, etc). Nothing else specific to Python. personnally, I find emacs very nice, in the current state of my knowledge, when I need to reindent the code. you know how this is critical in python...:-) Moving a block one step right or left? Oh, I use that, too. I am also a heavy user of dabbrev-expand (that's an Emacs term, but it exists in Vim too). Also some other vital features which aren't specific to Python. The best help an editor can give is language- independent. /Jorgen -- // Jorgen Grahn grahn@ Oo o. . . \X/ snipabacken.se O o . -- http://mail.python.org/mailman/listinfo/python-list
Re: deepcopy of class inherited from Thread
VYAS ASHISH M-NTB837 wrote: Dear All I am running this piece of code: from threading import Thread import copy class Ashish(Thread): def __init__(self, i): Thread.__init__(self) self.foo = i def run(self): print (self, self.foo) d= Ashish(4) e = copy.deepcopy(d) --- Exception here d.start() e.start() d.join() e.join() But I am getting this error: Traceback (most recent call last): File D:\Profiles\ntb837\Desktop\threadprob.py, line 13, in module e = copy.deepcopy(d) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 295, in _reconstruct state = deepcopy(state, memo) File C:\Python31\lib\copy.py, line 146, in deepcopy y = copier(x, memo) File C:\Python31\lib\copy.py, line 235, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 295, in _reconstruct state = deepcopy(state, memo) File C:\Python31\lib\copy.py, line 146, in deepcopy y = copier(x, memo) File C:\Python31\lib\copy.py, line 235, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 280, in _reconstruct y = callable(*args) File C:\Python31\lib\copyreg.py, line 88, in __newobj__ return cls.__new__(cls, *args) TypeError: object.__new__(_thread.lock) is not safe, use _thread.lock.__new__() Could someone please help me find a solution? Regards, Ashish Vyas Is there some reason you need to copy such an object? In general, you can get into trouble doing deep copies of structures which involve OS data, because not all such data can be safely copied. Sometimes such copies just quietly malfunction, but this time you were fortunate enough to get a runtime error. What is your use-case? Perhaps there's some other approach that would accomplish the real task. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Mon, Oct 12, 2009 at 11:32 PM, Luis Zarrabeitia ky...@uh.cu wrote: Actually, in python, this works even better: for lin in iter(file_object.readline, ): ... do something with lin What about with open(path_string) as f: for line in f: # do something Cheers, Xav -- http://mail.python.org/mailman/listinfo/python-list
Re: What do I do now?
On 11 Oct, 10:53 pm, fordhai...@gmail.com wrote: I've been programming since about 3 years, and come to think of it never written anything large. I know a few languages: c, python, perl, java. Right now, I just write little IRC bots that basically don't do anything. I have two questions: 1) What should I start programming (project that takes 1-2 months, not very short term)? You should make sure you pick something you find interesting. It can be a challenge to work on a long term project that isn't appealing to you personally in some way. 2) Whtat are some good open source projects I can start coding for? I think that Twisted is one of the better projects to work on if you're looking to improve your skills. We have a well-structured development process which includes lots of feedback from other developers. This sort of feedback is one of the best ways I know of to improve ones development skills. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: mxDateTime history (Re: mktime, how to handle dates before 01-01-1970 ?)
Piet van Oostrum wrote: greg g...@cosc.canterbury.ac.nz (g) wrote: g MRAB wrote: And when someone says January 30, do they really mean the day before the last day of the month? g No, no, that's January -2, a *completely* different thing! But for someone else it would be February -2. When is February 0? :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-3.2 (SVN) bug [was syntax question]
On Oct 12, 7:55 am, Helmut Jarausch jarau...@igpm.rwth-aachen.de wrote: I wrote I'm trying to build the recent Python-3.2a (SVN). It fails in Lib/tokenize.py (line 87) [...] with: TypeError: group() argument after ** must be a mapping, not tuple I believe I've found the source of this problem: the --with-tsc configure option enables some buggy inline assembly: see the READ_TIMESTAMP macro in Python/ceval.c. This uses the constraint A for the output of the x86 'rdtsc' instruction; for x86 that's fine, but for x86_64 it apparently refers to the 'rax' register, which is wrong: rdtsc loads its result into the edx and eax registers. So the edx register ends up being clobbered without gcc knowing about it, and all hell breaks loose as a result. So it is a Python bug, not a compiler bug. I've updated the bug report, and the bug should be fixed soonish. Thanks for reporting this, and for whittling the failure down to the --with-tsc configure option! Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of Tkinter and IDLE
Ben Finney wrote: TerryP bigboss1...@gmail.com writes: One thing you should also learn about me, is I do not deal in absolutes. What, *never*? That's a pretty uncompromising position to h— I'll get my coat. Note, he said he does not deal in absolutes. He didn't deny that he does. Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
Luis Zarrabeitia wrote: On Sunday 11 October 2009 11:56:55 pm Dennis Lee Bieber wrote: In this situation, the middle exit works best -- using non-optimal Python while True: lin = file_object.readline() if not lin: break do something with lin Actually, in python, this works even better: for lin in iter(file_object.readline, ): ... do something with lin And one can do this oneself. Faced with while True: stuff_required_to_make_the_decision() if the_decision(): break other_stuff() Wrapping the `stuff_required_...` and `the_decision` up into a generator would simplify the statement, and if it were done well the code overall would probably be better. Mel. -- http://mail.python.org/mailman/listinfo/python-list
pickle's backward compatibility
Hi, If I define my own class and use pickle to serialize the objects in this class, will the serialized object be successfully read in later version of python. What if I serialize (using pickle) an object of a class defined in python library, will it be successfully read in later version of python? Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list
POST value related question
hello im using mechanize . i want to send some post value by use mechanize. but problem is one of POST value in html source is looks like below. post.category.categoryNo=[*1] anyway so i was tried several method but all failed. here is source . . . br = mechanize.browser() br.select_form(nr=0) br.form['post.category.categoryNo']=[*1] br.form['contents.contentsValue'] = 'hello' br.submit() . . if anyone who know please help me . thanks in advance. -- View this message in context: http://www.nabble.com/POST-value-related-question-tp25857587p25857587.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Error en el bus from python
On 12 oct, 00:08, Philip Semanchuk phi...@semanchuk.com wrote: On Oct 11, 2009, at 11:56 PM, Dennis Lee Bieber wrote: On Sun, 11 Oct 2009 13:45:54 -0700 (PDT), Yusniel yhidalg...@gmail.com declaimed the following in gmane.comp.python.general: prolog.consult(hanoi.pl) snip where hanoy.pl is a program with python code. Any solution for this error?. Thanks. Are you sure? .pl is a common extension for PERL programs, not Python. My guess is that it is also a common extension for Prolog programs. I think the OP's program with python code should have been program with prolog code. Exactly. hanoi.pl is a prolog program. I'm using Ubuntu(9.04) 32 bit. In this case, this error is generated when I try run the above script. However, others scripts in python, not throws this error, I think that there are some problem with this library. -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle's backward compatibility
On 03:17 pm, pengyu...@gmail.com wrote: Hi, If I define my own class and use pickle to serialize the objects in this class, will the serialized object be successfully read in later version of python. What if I serialize (using pickle) an object of a class defined in python library, will it be successfully read in later version of python? Sometimes. Sometimes not. Python doesn't really offer any guarantees regarding this. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Error en el bus from python
On Oct 12, 2009, at 11:27 AM, Yusniel wrote: On 12 oct, 00:08, Philip Semanchuk phi...@semanchuk.com wrote: On Oct 11, 2009, at 11:56 PM, Dennis Lee Bieber wrote: On Sun, 11 Oct 2009 13:45:54 -0700 (PDT), Yusniel yhidalg...@gmail.com declaimed the following in gmane.comp.python.general: prolog.consult(hanoi.pl) snip where hanoy.pl is a program with python code. Any solution for this error?. Thanks. Are you sure? .pl is a common extension for PERL programs, not Python. My guess is that it is also a common extension for Prolog programs. I think the OP's program with python code should have been program with prolog code. Exactly. hanoi.pl is a prolog program. I'm using Ubuntu(9.04) 32 bit. In this case, this error is generated when I try run the above script. However, others scripts in python, not throws this error, I think that there are some problem with this library. Sounds like it's time to talk to whoever supports the Prolog library, then. Good luck Philip -- http://mail.python.org/mailman/listinfo/python-list
Re: Error en el bus from python
Yusniel wrote: Exactly. hanoi.pl is a prolog program. I'm using Ubuntu(9.04) 32 bit. In this case, this error is generated when I try run the above script. However, others scripts in python, not throws this error, I think that there are some problem with this library. Maybe, but it's impossible to tell what exactly the problem is if you don't show us your code. hanoi.pl is part of your code, but you haven't posted it. Please post it. -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: POST value related question
james27 wrote: hello im using mechanize . i want to send some post value by use mechanize. but problem is one of POST value in html source is looks like below. post.category.categoryNo=[*1] anyway so i was tried several method but all failed. here is source . . . br = mechanize.browser() br.select_form(nr=0) br.form['post.category.categoryNo']=[*1] You are missing quotes here. br.form['post.category.categoryNo']=[*1] br.form['contents.contentsValue'] = 'hello' br.submit() HTH, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: start external program from python
On Oct 12, 10:15 am, Bjorn bjornj...@gmail.com wrote: Hi, I woul like to start a program from within python (under linux): This works fine: import os path = 'tclsh AppMain.tcl hej.gb' os.system(path) The file AppMain.tcl is the executable and the file hej.gb is a textfile in the same directory. The text file gets opened in the app in the correct way. I wonder if I could pass information from the clipboard to the AppMain.tcl instead of the file hej.gb ? I use wxPython. any comment is appreciated! /bjorn Option A.) Use a program such as xclip or xcb to pipe the clipboard data into AppMain.tcl Option B.) Make your Python program able to get/set the clipboard at will, then set it before calling the program. Do like wise with AppMain.tcl but have it get the clipboard. Option C.) Create some external program that can do the B dance for them. Using option A takes advantage of your use of os.system, because it delegates to the shell. if going for option B, you should probably look at avoiding use of the shell at all (look at args to the subprocess module). Bonus points if you can think of an Option D. -- http://mail.python.org/mailman/listinfo/python-list
Looking for a buffered/windowed iterator
I have Python program that lets me interact with a bunch of files. Unfortunately, the program assumes that the bunch is fairly small, and I have thousands of files on relatively slow storage. Just creating a list of the file names takes several minutes, so I'm planning to replace the list with an iterator in another thread. However, each file requires several seconds to load before I can work with it. The current code alleviates this via a thread that loads the next file while I'm examining the current one. I'd like my new iterator to provide a fixed window around the current item. I've looked at the pairwise recipe, but it doesn't allow me to peek at items within the window (to generate thumbnails, etc), and I've looked at arrayterator, but it divides the stream into small contiguous blocks where crossing a block boundary is relatively expensive. Previous discussions in c.l.py (primarily those that propose new functions to be added to itertools) claim that people do this all the time, but seem woefully short of actual examples. Before I possibly re-invent the wheel(*), could someone point me to some actual code that approximates what I want to do? Thanks. (*) Re-inventing a wheel is generally pretty simple. But then you discover that you also need to invert axle grease, a leaf spring suspension, etc. -- http://mail.python.org/mailman/listinfo/python-list
RE: deepcopy of class inherited from Thread
Hi I have an object which has a run() method. But I can call it only once. Calling the start() again will give RuntimeError: thread already started So what is the way to do this? I thought of doing a deep copy of the object, as shallow copy will also lead to the above error. I tried this: - deepcopy the object - call start() for the object you got from deepcopy - delete the object. Is there a simpler way to achieve this? Regards, Ashish Vyas -Original Message- From: Dave Angel [mailto:da...@ieee.org] Sent: Monday, October 12, 2009 7:14 PM To: VYAS ASHISH M-NTB837 Cc: python-list@python.org Subject: Re: deepcopy of class inherited from Thread VYAS ASHISH M-NTB837 wrote: Dear All I am running this piece of code: from threading import Thread import copy class Ashish(Thread): def __init__(self, i): Thread.__init__(self) self.foo = i def run(self): print (self, self.foo) d= Ashish(4) e = copy.deepcopy(d) --- Exception here d.start() e.start() d.join() e.join() But I am getting this error: Traceback (most recent call last): File D:\Profiles\ntb837\Desktop\threadprob.py, line 13, in module e = copy.deepcopy(d) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 295, in _reconstruct state = deepcopy(state, memo) File C:\Python31\lib\copy.py, line 146, in deepcopy y = copier(x, memo) File C:\Python31\lib\copy.py, line 235, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 295, in _reconstruct state = deepcopy(state, memo) File C:\Python31\lib\copy.py, line 146, in deepcopy y = copier(x, memo) File C:\Python31\lib\copy.py, line 235, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File C:\Python31\lib\copy.py, line 173, in deepcopy y = _reconstruct(x, rv, 1, memo) File C:\Python31\lib\copy.py, line 280, in _reconstruct y = callable(*args) File C:\Python31\lib\copyreg.py, line 88, in __newobj__ return cls.__new__(cls, *args) TypeError: object.__new__(_thread.lock) is not safe, use _thread.lock.__new__() Could someone please help me find a solution? Regards, Ashish Vyas Is there some reason you need to copy such an object? In general, you can get into trouble doing deep copies of structures which involve OS data, because not all such data can be safely copied. Sometimes such copies just quietly malfunction, but this time you were fortunate enough to get a runtime error. What is your use-case? Perhaps there's some other approach that would accomplish the real task. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a buffered/windowed iterator
On 2009-10-12 11:21 AM, samwyse wrote: Previous discussions in c.l.py (primarily those that propose new functions to be added to itertools) claim that people do this all the time, but seem woefully short of actual examples. Before I possibly re-invent the wheel(*), could someone point me to some actual code that approximates what I want to do? Thanks. From grin, my grep-alike: http://pypi.python.org/pypi/grin def sliding_window(seq, n): Returns a sliding window (up to width n) over data from the iterable Adapted from the itertools documentation. s - (s0,), (s0, s1), ... (s0,s1,...s[n-1]), (s1,s2,...,sn), ... it = iter(seq) result = () for i, elem in itertools.izip(range(n), it): result += (elem,) yield result for elem in it: result = result[1:] + (elem,) yield result A slight modification of this should get what you want. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: What do I do now?
On Oct 12, 12:19 am, Donn donn.in...@gmail.com wrote: On Monday 12 October 2009 00:53:42 Someone Something wrote: 1) What should I start programming (project that takes 1-2 months, not very short term)? 2) Whtat are some good open source projects I can start coding for? These kinds of questions amaze me. Surely you are a kid in a candy shop when it comes to things to code? The best place to start a project is to scratch an itch: pick something that really bugs you, or something that is plain missing, or something that you are interested in, and start solving the problem. No O/S or Desktop or App is perfect. There are a thousand gaps between all those things that need solutions or improvements. Find an itch and either: 1. Find a project in that direction and try to join. 2. Start your own. \d As long it is not another new code editor for Python. There are a lot already. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Monday 12 October 2009 09:47:23 am Xavier Ho wrote: On Mon, Oct 12, 2009 at 11:32 PM, Luis Zarrabeitia ky...@uh.cu wrote: Actually, in python, this works even better: for lin in iter(file_object.readline, ): ... do something with lin What about with open(path_string) as f: for line in f: # do something Gah. You are right, of course! Even my for should've been: for lin in file_object: ... and nothing more. I use that iter trick only when I don't want the buffering (like, when I'm reading from stdin in a squid authenticator helper). I guess that the 'for line in f' is so... natural for me, that the only reason I could think for writing while True for a file iteration was when I needed to use readline explicitly. But yes, with! -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: What do I do now?
Che M wrote: 2. Start your own. As long it is not another new code editor for Python. There are a lot already. How about writing a web framework instead? [grins ducks] -tkc -- http://mail.python.org/mailman/listinfo/python-list
how to move a webiste in python
Hi, I am new to python I have few questions regarding it. I have to me a website with python scripts from one server to another server , when I moved the content the website is not working, do I have to recompile the code in new server too. Can any help me to resolve this issue ?? Thanks Bhanu -- http://mail.python.org/mailman/listinfo/python-list
Re: deepcopy of class inherited from Thread
VYAS ASHISH M-NTB837 schrieb: I have an object which has a run() method. But I can call it only once. Calling the start() again will give RuntimeError: thread already started So what is the way to do this? I thought of doing a deep copy of the object, as shallow copy will also lead to the above error. I tried this: - deepcopy the object - call start() for the object you got from deepcopy - delete the object. Is there a simpler way to achieve this? Indeed, there is: def threaded(): do threaded stuff here Thread(target=threaded).start() Thread(target=threaded).start() Thread(target=threaded).start() Thread(target=threaded).start() Thread(target=threaded).start() Now threaded() runs five times. Python is not Java where one has to subclass from Thread (AFAIR the dark ages where I used to speak Javanese). Mick, -- http://mail.python.org/mailman/listinfo/python-list
Re: AJAX Widget Framework
On Oct 1, 6:01 pm, Laszlo Nagy gand...@shopzeus.com wrote: I'm looking for an open source, AJAX based widget/windowing framework. Here is what I need: - end user opens up a browser, points it to a URL, logs in - on the server site, sits my application, creating a new session for each user that is logged in - on the server site, I create windows(frames), put widgets on them, write event handlers etc. Just like with wx or pygtk. - However, windows are created in the user's browser, and events are triggered by Javascript, and sent back to server through AJAX. - the server side would be - of course - written in Python. I was looking these projects: http://www.uize.com/http://pyjs.org/ There are many frameworks listed here which I did not check:http://internetmindmap.com/javascript_frameworks. I have no idea which has Python support, and probably there are only a few that worth looking at. I wonder if you could tell me which are the pros and contras for these frameworks. If there is a comparison available on the NET, pointing me to the right URL would help a lot. The bottom line... My main goal is to develop enterprise class OLTP database applications. I'll need grid widget to display data in tabular format, and I'll use events heavily for data manipulation, live search, tooltips etc. I'm familiar with wxWidgets, pygtk and other toolkits, but not with AJAX. I have never used a system like that. pyjamas is, despite having a browser-based option, about as far away from web development as you can possibly get, with only the lack of access to standard python libraries and having to work with python reimplementations of math.py, re.py, time.py etc. being the stark reminder that you're reaallly not in kansas. the only thing that you have to get used to is that communication with the external world is done through HTTPRequest.py and, typically, its derivative, JSONService.py - even in the desktop version of pyjamas. but, if you're used to event-driven desktop environments such as wxWidgets and pygtk then the asynchronous nature of JSONService won't be a problem for you. i recommend that if you intend to develop an enterprise-style CRUD (create-retrieve-update-delete) application, that you take a look at the PureMVC-based examples: http://pyjs.org/examples/ search for employeeadmin and timesheet. kees bos joined the project a few months ago, and his very first task that he set himself was to improve the pyjs compiler to the point where http://puremvc.org's python library could be used *unmodified* in pyjamas applications. he then set about porting (and bug-fixing!) the two wxWidgets python-puremvc examples to use pyjamas widgets. these two examples should give you a big head-start on what you want to achieve. if you are stuck on pure javascript frameworks, however, and you need widgets, then there is one that i can tentatively recommend (with some trepidation, due to its enooormous size): extjs [no don't even _think_ of trying to combine it with pyjamas] and the other one is qooxdoo which is veery easy and intuitive, and well-designed. i don't honestly know if qooxdoo has a grid widget, but extjs most certainly does (and then some). the only issue with extjs is the sheer number of options and the whopping great size. whichever option you pick, you're basically in for quite a bit of learning, to get started. if you pick pyjamas and you post on the pyjamas-dev list _please_ do remember to follow the rules about providing full context and a worked example if it's a programming issue, to help save people time, ok? :) l. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Oct 12, 3:36�am, greg g...@cosc.canterbury.ac.nz wrote: Mensanator wrote: while not done: � � ... � � if n==1: done = True � � ... Seems to me that 'while not done:' is no better than 'while True:', because in both cases you have to look inside the loop to find out what the exit condition is. Using a more meaningful name for the flag can help, but you can't teach someone that just by giving them an overly simplified rules such as never use while True:. They'll probably just replace it with 'while not done:' and think they've improved things, without ever really understanding the issue. You're missing the point. It's not that you have to look inside for the terminating condition. It's that you don't need a break. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: some site login problem help plz..
On Oct 5, 8:26 am, Diez B. Roggisch de...@nospam.web.de wrote: james27 wrote: hello.. im new to python. i have some problem with mechanize. before i was used mechanize with no problem. but i couldn't success login with some site. for several days i was looked for solution but failed. my problem is , login is no probelm but can't retrieve html source code from opened site. actually only can read some small html code, such like below. html script language=javascript location.replace(http://www.naver.com;); /script /html i want to retrive full html source code..but i can't . i was try with twill and mechanize and urllib and so on. i have no idea.. anyone can help me? Your problem is that the site usesJavaScriptto replace itself. Mechanize can't do anything about that. You might have more luck with scripting a browser. No idea if there are any special packages available for that though. yes, there are. i've mentioned this a few times, on comp.lang.python, (so you can search for them) and have the instances documented here: http://wiki.python.org/moin/WebBrowserProgramming basically, you're not going to like this, but you actually need a _full_ web browser engine, and to _execute_ the javascript. then, after a suitable period of time (or after the engine's stopped executing callback has been called, if it has one) you can then node-walk the DOM of the engine, grab the engine's document.body.innerHTML property, or use the engine's built-in XPath support (if it has it) to find specific parts of the DOM faster than if you extracted the text (into lxml etc). you should not be shocked by this - by the fact that it takes a whopping 10 or 20mb library, including a graphical display mechanism, to execute a few bits of javascript. also, if you ask him nicely, flier liu is currently working on http://code.google.com/p/pyv8 and on implementing the W3C DOM standard as a daemon service (i.e. with no GUI component) and he might be able to help you out. the pyv8 project comes with an example w3c.py file which implements DOM partially, but i know he's done a lot more. so - it's all doable, but for a given value of do :) l. -- http://mail.python.org/mailman/listinfo/python-list
RE: deepcopy of class inherited from Thread
The function that I want to run is part of a class, not a standalone function. There are several class member variables also. Regards, Ashish Vyas -Original Message- From: python-list-bounces+ntb837=motorola@python.org [mailto:python-list-bounces+ntb837=motorola@python.org] On Behalf Of Mick Krippendorf Sent: Monday, October 12, 2009 10:52 PM To: python-list@python.org Subject: Re: deepcopy of class inherited from Thread VYAS ASHISH M-NTB837 schrieb: I have an object which has a run() method. But I can call it only once. Calling the start() again will give RuntimeError: thread already started So what is the way to do this? I thought of doing a deep copy of the object, as shallow copy will also lead to the above error. I tried this: - deepcopy the object - call start() for the object you got from deepcopy - delete the object. Is there a simpler way to achieve this? Indeed, there is: def threaded(): do threaded stuff here Thread(target=threaded).start() Thread(target=threaded).start() Thread(target=threaded).start() Thread(target=threaded).start() Thread(target=threaded).start() Now threaded() runs five times. Python is not Java where one has to subclass from Thread (AFAIR the dark ages where I used to speak Javanese). Mick, -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: mxDateTime history (Re: mktime, how to handle dates before 01-01-1970 ?)
Tim Chase wrote: Month arithmetic is a bit of a mess, since it's not clear how to map e.g. Jan 31 + one month. Jan 31 + one month usually means add one to the month value and then keep backing off the day if you get an exception making the date, so you'd get Feb 31, exception, Feb 30, exception, Feb 29, possibly an exception, and possibly/finally Feb 28th. This makes pretty intuitive sense to most folks and is usually what's meant. Well, yes, but that's just one way to solve the problem. I guess I'll just add all possible solutions and then let the user decide what's best in some way. I've found that issues and confusion stem more from the non-commutative reality that Jan 31 + (1 month) + (-1 month) != Jan 31 + (-1 month) + (1 month) or the non-associative Jan 31 + (1 month + 1 month) != (Jan 31 + 1 month) + 1 month :-/ That's why mxDateTime actually returning a day in March... mx.DateTime.DateTime(2009, 1, 31) + mx.DateTime.RelativeDateTime(months=+1) mx.DateTime.DateTime object for '2009-03-03 00:00:00.00' at 2ba43f93ebe0 That's intuitive for mathematicians only, though ;-) So yes, messy it is! Indeed. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 12 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: mxDateTime history (Re: mktime, how to handle dates before 01-01-1970 ?)
Rhodri James wrote: On Fri, 09 Oct 2009 13:39:43 +0100, Tim Chase python.l...@tim.thechases.com wrote: Month arithmetic is a bit of a mess, since it's not clear how to map e.g. Jan 31 + one month. Jan 31 + one month usually means add one to the month value and then keep backing off the day if you get an exception making the date, so you'd get Feb 31, exception, Feb 30, exception, Feb 29, possibly an exception, and possibly/finally Feb 28th. This makes pretty intuitive sense to most folks and is usually what's meant. I've found that issues and confusion stem more from the non-commutative reality that Jan 31 + (1 month) + (-1 month) != Jan 31 + (-1 month) + (1 month) or the non-associative Jan 31 + (1 month + 1 month) != (Jan 31 + 1 month) + 1 month :-/ I'd hazard a guess that what we're actually seeing is people mentally rebasing their indices, i.e. counting from the end of the month rather than the start, which makes the last day of January and January 31 not the same thing really. Unfortunately we're very fuzzy about when we do things like this, which makes it hard on a poor programmer. Ah, for that we have RelativeDateTime: # next month, last day of the month mx.DateTime.DateTime(2009, 1, 31) + mx.DateTime.RelativeDateTime(months=+1, day=-1) mx.DateTime.DateTime object for '2009-02-28 00:00:00.00' at 2ba43f95c088 -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 12 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
Mensanator wrote: On Oct 12, 3:36�am, greg g...@cosc.canterbury.ac.nz wrote: Mensanator wrote: while not done: � � ... � � if n==1: done = True � � ... Seems to me that 'while not done:' is no better than 'while True:', because in both cases you have to look inside the loop to find out what the exit condition is. Using a more meaningful name for the flag can help, but you can't teach someone that just by giving them an overly simplified rules such as never use while True:. They'll probably just replace it with 'while not done:' and think they've improved things, without ever really understanding the issue. You're missing the point. It's not that you have to look inside for the terminating condition. It's that you don't need a break. Nothing wrong with a having a break IMHO. while not done: seems very dangerous to me as you'd have to del done before writing the same construct again. That's the sort of thing that leads to errors. -- http://mail.python.org/mailman/listinfo/python-list
Re: deepcopy of class inherited from Thread
VYAS ASHISH M-NTB837 schrieb: The function that I want to run is part of a class, not a standalone function. There are several class member variables also. Then try: class MyClass(object): ... def run(self): do threaded stuff here ... Thread(target=MyClass().run).start() Thread(target=MyClass().run).start() Thread(target=MyClass().run).start() Thread(target=MyClass().run).start() Thread(target=MyClass().run).start() And *please* don't always quote the whole article in your answer. Mick. -- http://mail.python.org/mailman/listinfo/python-list
Re: organizing your scripts, with plenty of re-use
On Oct 10, 9:44 am, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: The good thing is that, if the backend package is properly installed somewhere in the Python path ... it still works with no modifications. I'd like to get to zero-installation if possible. It's easy with simple python scripts, why not packages too? I know the technical reasons, but I haven't heard any practical reasons. If the reasons are purely technical, it smells like a PEP to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
Mensanator wrote: On Oct 12, 3:36�am, greg g...@cosc.canterbury.ac.nz wrote: Mensanator wrote: while not done: � � ... � � if n==1: done = True � � ... Seems to me that 'while not done:' is no better than 'while True:', because in both cases you have to look inside the loop to find out what the exit condition is. Using a more meaningful name for the flag can help, but you can't teach someone that just by giving them an overly simplified rules such as never use while True:. They'll probably just replace it with 'while not done:' and think they've improved things, without ever really understanding the issue. You're missing the point. It's not that you have to look inside for the terminating condition. It's that you don't need a break. What's wrong with breaks? I'll agree that they can be overused and abused, but I am not aware of *any* programming costruct that cannot be. If you rule out one way of doing things for every situation you can end up making messes just as bad as the ones you're trying to avoid. Good programming, as all good endeavors, requires thinking too. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
It Doesn't Add Up!
Hi; I have the following code: for row in data: i += 1 total = 0 quantity = form.getfirst('order_' + str(i), '') if quantity != '': sql = 'select * from products p join %s c on p.ID=c.ID where c.ID=%s;' % (client, str(i)) cursor.execute(sql) stuff = cursor.fetchone() price = str(int(stuff[5]*100)) price = price[0:len(price)-2] + '.' + price[-2:] item, price, description, discount = stuff[2], price, stuff[3], stuff[8] order += 'Item #: ' + item + '\tQuantity: ' + quantity + '\tPrice: ' + price + '\tDiscount: ' + str(discount) + '\tDescription: ' + description[:20] + '...br /\n' print 'Total 1: %sbr /' % total total += float(price) * int(quantity) * (100 - discount)/100 print 'Total 2: %sbr /' % total order += 'TOTAL: $' + str(total) It prints out the following to screen with the print statements: Total 1: 0 Total 2: 1.98 Total 1: 0 Total 2: 6.3 As you can see, the total doesn't accumulate! There are two rows. The second Total 1: should show 1.98, not 0! What gives? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: mxDateTime history (Re: mktime, how to handle dates before 01-01-1970 ?)
Chris Rebert wrote: On Mon, Oct 12, 2009 at 4:27 AM, Piet van Oostrum p...@cs.uu.nl wrote: greg g...@cosc.canterbury.ac.nz (g) wrote: g MRAB wrote: And when someone says January 30, do they really mean the day before the last day of the month? g No, no, that's January -2, a *completely* different thing! But for someone else it would be February -2. And for still others, it's the last $DAYOFWEEK of the month, which just happened to fall on the 30th. That's a little more complicated: mx.DateTime.DateTime(2009, 1, 31).day_of_week 5 # which is a ... mx.DateTime.Weekday[mx.DateTime.DateTime(2009, 1, 31).day_of_week] 'Saturday' Now: # next month, last Saturday mx.DateTime.DateTime(2009, 1, 31) + mx.DateTime.RelativeDateTime(months=+1, day=1, weekday=(5, -1)) mx.DateTime.DateTime object for '2009-02-28 00:00:00.00' at 2ba43f93ebe0 -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 12 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Oct 12, 1:02�pm, John Reid j.r...@mail.cryst.bbk.ac.uk wrote: Mensanator wrote: On Oct 12, 3:36 am, greg g...@cosc.canterbury.ac.nz wrote: Mensanator wrote: while not done: ... if n==1: done = True ... Seems to me that 'while not done:' is no better than 'while True:', because in both cases you have to look inside the loop to find out what the exit condition is. Using a more meaningful name for the flag can help, but you can't teach someone that just by giving them an overly simplified rules such as never use while True:. They'll probably just replace it with 'while not done:' and think they've improved things, without ever really understanding the issue. You're missing the point. It's not that you have to look inside for the terminating condition. It's that you don't need a break. Nothing wrong with a having a break IMHO. My opinion is that there is everything wrong with having a break. I don't think I have ever used one, I write code that doesn't depend on that crutch. while not done: seems very dangerous to me as you'd have to del done before writing the same construct again. That's the sort of thing that leads to errors. Duh. I won't write silly code like that either. If I need more than one loop structure then I'll do something like while not done_with_this while not done_with_that Besides, since I _always_ initialize the flag before entering a loop, the flag can be reused and doesn't have to be deleted (as long as the loops aren't nested). And since I don't use goto, there's no chance the initialization can be avoided. The best way to avoid the pitfalls of spaghetti code is to not write it in the first place. -- http://mail.python.org/mailman/listinfo/python-list
Re: It Doesn't Add Up!
Chris On Mon, Oct 12, 2009 at 11:33 AM, Victor Subervi victorsube...@gmail.comwrote: Hi; I have the following code: for row in data: i += 1 total = 0 In the above line, you're setting total to 0 each time the loop runs. quantity = form.getfirst('order_' + str(i), '') if quantity != '': sql = 'select * from products p join %s c on p.ID=c.ID where c.ID=%s;' % (client, str(i)) cursor.execute(sql) stuff = cursor.fetchone() price = str(int(stuff[5]*100)) price = price[0:len(price)-2] + '.' + price[-2:] item, price, description, discount = stuff[2], price, stuff[3], stuff[8] order += 'Item #: ' + item + '\tQuantity: ' + quantity + '\tPrice: ' + price + '\tDiscount: ' + str(discount) + '\tDescription: ' + description[:20] + '...br /\n' print 'Total 1: %sbr /' % total total += float(price) * int(quantity) * (100 - discount)/100 print 'Total 2: %sbr /' % total order += 'TOTAL: $' + str(total) It prints out the following to screen with the print statements: Total 1: 0 Total 2: 1.98 Total 1: 0 Total 2: 6.3 As you can see, the total doesn't accumulate! There are two rows. The second Total 1: should show 1.98, not 0! What gives? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: It Doesn't Add Up!
On Mon, 12 Oct 2009 11:33:31 -0700, Victor Subervi victorsube...@gmail.com wrote: Hi; I have the following code: for row in data: i += 1 total = 0 [snip] As you can see, the total doesn't accumulate! There are two rows. The second Total 1: should show 1.98, not 0! What gives? You are setting total = 0 inside the for loop, so it is getting rebound for every row... -- http://mail.python.org/mailman/listinfo/python-list
Re: It Doesn't Add Up!
Ouch! You're right! ;) V On Mon, Oct 12, 2009 at 1:38 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: On Mon, 12 Oct 2009 11:33:31 -0700, Victor Subervi victorsube...@gmail.com wrote: Hi; I have the following code: for row in data: i += 1 total = 0 [snip] As you can see, the total doesn't accumulate! There are two rows. The second Total 1: should show 1.98, not 0! What gives? You are setting total = 0 inside the for loop, so it is getting rebound for every row... -- http://mail.python.org/mailman/listinfo/python-list
Re: It Doesn't Add Up!
Victor Subervi wrote: Hi; I have the following code: [snip] price = str(int(stuff[5]*100)) price = price[0:len(price)-2] + '.' + price[-2:] [snip] This is simpler: price = %.2f % stuff[5] (not that I like what you're doing with it; leaving it as a float and just formatting to 2 decimal places when printing it would be better! :-)) -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Oct 12, 12:32 pm, Mensanator mensana...@aol.com wrote: On Oct 12, 1:02 pm, John Reid j.r...@mail.cryst.bbk.ac.uk wrote: Mensanator wrote: On Oct 12, 3:36 am, greg g...@cosc.canterbury.ac.nz wrote: Mensanator wrote: while not done: ... if n==1: done = True ... Seems to me that 'while not done:' is no better than 'while True:', because in both cases you have to look inside the loop to find out what the exit condition is. Using a more meaningful name for the flag can help, but you can't teach someone that just by giving them an overly simplified rules such as never use while True:. They'll probably just replace it with 'while not done:' and think they've improved things, without ever really understanding the issue. You're missing the point. It's not that you have to look inside for the terminating condition. It's that you don't need a break. Nothing wrong with a having a break IMHO. My opinion is that there is everything wrong with having a break. I don't think I have ever used one, I write code that doesn't depend on that crutch. while not done: seems very dangerous to me as you'd have to del done before writing the same construct again. That's the sort of thing that leads to errors. Duh. I won't write silly code like that either. If I need more than one loop structure then I'll do something like while not done_with_this while not done_with_that Besides, since I _always_ initialize the flag before entering a loop, the flag can be reused and doesn't have to be deleted (as long as the loops aren't nested). And since I don't use goto, there's no chance the initialization can be avoided. The best way to avoid the pitfalls of spaghetti code is to not write it in the first place. How do you manage code where you need to drop out of a neatly written for or while loop early? I don't use break frequently, but just like gotos, it does have it's place in well written code. Glad to hear, by the way, that you don't use gotos in Python. =D Garrick -- http://mail.python.org/mailman/listinfo/python-list
Hello python users
Hi, I am new to this list. I have some goals in mind but I am unsure of where to start. I want to connect to my gmail account, find specific emails and save the contents of the emails to a txt file. I would like to open none txt files (.nc files) which can be opened in note pad and saved as a txt. I also want to make a synchronizing program. Lastly, I love poker and I would love even more to make a cool app for poker maybe an iPhone app or something I can post to the iGoogle page. So with that in mind where would you start? Thanks, Spencer -- http://mail.python.org/mailman/listinfo/python-list
Re: start external program from python
On Mon, 2009-10-12, Bjorn wrote: Hi, I woul like to start a program from within python (under linux): This works fine: import os path = 'tclsh AppMain.tcl hej.gb' os.system(path) The file AppMain.tcl is the executable Not really -- tclsh is the executable from Python's and the system's view. If you are on Unix, you might want to use a shebang http://en.wikipedia.org/wiki/Shebang_(Unix) and rename AppMain.tcl AppMain so you don't have to rewrite your Python program just because you rewrite the Tcl program in some other (more modern) language. and the file hej.gb is a textfile in the same directory. The text file gets opened in the app in the correct way. So the subject line doesn't really capture your question? I wonder if I could pass information from the clipboard to the AppMain.tcl instead of the file hej.gb ? I use wxPython. any comment is appreciated! Sure you can, but the clipboard wasn't really designed for that. You can document 'AppMain' as taking its input from whatever is in the clipboard when it starts, but if there is nothing there it cannot wait for it, and there are no guarantees that the user or some other program (or another copy of the program) hasn't put something else there in the milliseconds it takes to start AppMain. It's also not a private channel; any other program can read it. Why do you want to use the clipboard? If you think you need it because you don't want a temporary file, maybe you can let AppMain read from standard input, and let the Python program write the data using os.popen or one of the alternatives. /Jorgen -- // Jorgen Grahn grahn@ Oo o. . . \X/ snipabacken.se O o . -- http://mail.python.org/mailman/listinfo/python-list
which dictionary with attribute-style access?
Hello, googling I found several ways of implementing a dictionary with attribute-style access. 1. ActiveState cookbook: http://code.activestate.com/recipes/473786/ 2. ActiveState cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 3. web2py codebase: Storage(dict) I enclosed the three implementations below. My question to the Python specialists: which one is the most correct? Are there restrictions with regards to pickling or copy()? Which one should I choose? Regards, Andreas -- Andreas Balogh baloand (at) gmail.com --- class AttrDict(dict): comments removed A dictionary with attribute-style access. It maps attribute access to the real dictionary. def __init__(self, init={}): dict.__init__(self, init) def __getstate__(self): return self.__dict__.items() def __setstate__(self, items): for key, val in items: self.__dict__[key] = val def __repr__(self): return %s(%s) % (self.__class__.__name__, dict.__repr__(self)) def __setitem__(self, key, value): return super(AttrDict, self).__setitem__(key, value) def __getitem__(self, name): return super(AttrDict, self).__getitem__(name) def __delitem__(self, name): return super(AttrDict, self).__delitem__(name) __getattr__ = __getitem__ __setattr__ = __setitem__ def copy(self): ch = AttrDict(self) return ch --- class attrdict(dict): comments removed def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self --- class Storage(dict): comments removed def __getattr__(self, key): try: return self[key] except KeyError, k: return None def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError, k: raise AttributeError, k def __repr__(self): return 'Storage ' + dict.__repr__(self) + '' def __getstate__(self): return dict(self) def __setstate__(self, value): for (k, v) in value.items(): self[k] = v -- http://mail.python.org/mailman/listinfo/python-list
Re: Daemon call python program
On Mon, 2009-10-12, §ä´m¦Û¤vª�...@¤ù¤Ñ wrote: ?? ???z?mcommand (???m???v...@)?n???G : I have a daemon process which will call a python program. : What do I do if I want to dump the exception when the python program exist : by uncaught exception. : Thanks a lot! By the way, the python program is multi-thread It doesn't really matter if it's multi-threaded, or even that it is Python. You would have the same problem with any program which may print stuff to standard output or standard error, and/or exit. I think it depends completely on the design of your daemon, and why it calls another program. And what it does while that other program is running. inetd/xinetd on Unix is one example, but they feed the program's output (all of it, both standard output and standard error, IIRC) to the remote client. Same with CGI, I think. /Jorgen -- // Jorgen Grahn grahn@ Oo o. . . \X/ snipabacken.se O o . -- http://mail.python.org/mailman/listinfo/python-list
Re: Error en el bus from python
On Mon, 2009-10-12, Philip Semanchuk wrote: On Oct 11, 2009, at 4:45 PM, Yusniel wrote: Hi. I did installed a library for python named pyswip-0.2.2 but when I run a python example with the next lines, the python interpreter, it throw me the following error: Error en el bus. The code lines are: Makes me think of that guy from the Simpsons, in the bumble-bee suit ... fortunately you don't need to know tech Spanish to decode this one. ... Are you on a Mac by any chance? I get a bus error out of Python once in a while, usually when a C library has done something bad. I don't know if this error is specific to OS X or not. Bus Error is an old BSD-ism which I guess you don't see much in Linux or Solaris these days (or maybe I never run buggy code ;-). It translates roughly to segmentation fault, but IIRC it is more about accessing memory words on nonaligned adresses than about accessing addresses your process doesn't own. [...] /Jorgen -- // Jorgen Grahn grahn@ Oo o. . . \X/ snipabacken.se O o . -- http://mail.python.org/mailman/listinfo/python-list
Re: best vi / emacs python features
Hey guys, this is supposed to be a Python mailing list... Both editors are great and are with great potentials. I do use both of them daily, though for different purposes. It is meaningless to start this old issue of preferences anew. -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
What is the correct way to define __hash__?
Hi, I'm wondering what is the general way to define __hash__. I could add up all the members. But I am wondering if this would cause a performance issue for certain classes. Regards, Peng #!/usr/bin/env python class A: def __init__(self, a, b) : self._a = a self._b = b def __str__(self): return 'A(%s, %s)' %(self._a, self._b) __repr__ = __str__ def __cmp__(self, other): if self._a other._a: return -1 elif self._a other._a: return 1 elif self._b other._b: return -1 elif self._b other._b: return 1 else: return 0 def __hash__(self): return self._a + self._b if __name__ == '__main__': x = A(1, 1) aset = set() aset.add(x) print aset -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the correct way to define __hash__?
On Mon, Oct 12, 2009 at 3:45 PM, Peng Yu pengyu...@gmail.com wrote: Hi, I'm wondering what is the general way to define __hash__. I could add up all the members. But I am wondering if this would cause a performance issue for certain classes. Regards, Peng #!/usr/bin/env python class A: def __init__(self, a, b) : self._a = a self._b = b def __str__(self): return 'A(%s, %s)' %(self._a, self._b) __repr__ = __str__ def __cmp__(self, other): if self._a other._a: return -1 elif self._a other._a: return 1 elif self._b other._b: return -1 elif self._b other._b: return 1 else: return 0 def __hash__(self): return self._a + self._b if __name__ == '__main__': x = A(1, 1) aset = set() aset.add(x) print aset What if A has a third member, which is a string? Is there a function to convert an arbitrary string to an int? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the correct way to define __hash__?
On 2009-10-12 15:45 PM, Peng Yu wrote: Hi, I'm wondering what is the general way to define __hash__. I could add up all the members. But I am wondering if this would cause a performance issue for certain classes. Unless if you are very familiar with the math of hash functions, I don't recommend that you try to implement one directly. Instead, make a tuple of the hashable content of your class and return the result of calling hash() on that tuple. Be sure to make your equality comparison do the right thing. class A(object): def __init__(self, a, b): self.a = a self.b = b def _key(self): # I include the name of the class so as to differentiate between other # classes that might also have a _key() method. If you have several classes # or subclasses that are allowed to compare equal to each other, use some # other common string here. return (type(self).__name__, a, b) def __hash__(self): return hash(self._key()) # Coincidentally, the _key() method can usually be reused for comparisons. # I recommend doing this for the equality comparisons, at least, when you can # because of the requirement that two items that compare equal must have the # same hash value. def __eq__(self, other): return self._key() == other._key() def __ne__(self, other): return not (self == other) ... -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the correct way to define __hash__?
Peng Yu schrieb: Hi, I'm wondering what is the general way to define __hash__. I could add up all the members. But I am wondering if this would cause a performance issue for certain classes. def __hash__(self): return self._a + self._b The hash of a tuple is based on the hash of its values. A common way to define a hash method is: def __hash__(self): return hash((self._a, self._b)) Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Oct 12, 2:18 pm, Falcolas garri...@gmail.com wrote: On Oct 12, 12:32 pm, Mensanator mensana...@aol.com wrote: On Oct 12, 1:02 pm, John Reid j.r...@mail.cryst.bbk.ac.uk wrote: Mensanator wrote: On Oct 12, 3:36 am, greg g...@cosc.canterbury.ac.nz wrote: Mensanator wrote: while not done: ... if n==1: done = True ... Seems to me that 'while not done:' is no better than 'while True:', because in both cases you have to look inside the loop to find out what the exit condition is. Using a more meaningful name for the flag can help, but you can't teach someone that just by giving them an overly simplified rules such as never use while True:. They'll probably just replace it with 'while not done:' and think they've improved things, without ever really understanding the issue. You're missing the point. It's not that you have to look inside for the terminating condition. It's that you don't need a break. Nothing wrong with a having a break IMHO. My opinion is that there is everything wrong with having a break. I don't think I have ever used one, I write code that doesn't depend on that crutch. while not done: seems very dangerous to me as you'd have to del done before writing the same construct again. That's the sort of thing that leads to errors. Duh. I won't write silly code like that either. If I need more than one loop structure then I'll do something like while not done_with_this while not done_with_that Besides, since I _always_ initialize the flag before entering a loop, the flag can be reused and doesn't have to be deleted (as long as the loops aren't nested). And since I don't use goto, there's no chance the initialization can be avoided. The best way to avoid the pitfalls of spaghetti code is to not write it in the first place. How do you manage code where you need to drop out of a neatly written for or while loop early? I don't. If I thought there would ever be a case when a for loop had to exit early, I wouldn't use a for loop. Similarly, if I ever felt the need to escape from a while loop, I would rewrite it to avoid that situation. I don't use break frequently, but just like gotos, it does have it's place in well written code. Glad to hear, by the way, that you don't use gotos in Python. =D Python doesn't have goto? Gee, I guess I never looked for one. Learned my lesson from Pascal, eh? Garrick -- http://mail.python.org/mailman/listinfo/python-list
POST value related question
hello i have some problem to send POST value by use mechanize. i can't write my article to my blog site. here is full source. and what i want to do is, im posting my article to my blog site. thanks in advance. # -*- coding: cp949 -*- import mechanize import cookielib # Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Want debugging messages? #br.set_debug_http(True) #br.set_debug_redirects(True) #br.set_debug_responses(True) # User-Agent (this is cheating, ok?) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en- US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] # Open some site, let's pick a random one, the first that pops in mind: r = br.open('http://nid.naver.com/nidlogin.login') html = r.read() #print html # Show the source #print html # or #print br.response().read() # Show the html title #print br.title() # Show the response headers #print r.info() # or #print br.response().info() # Show the available forms for f in br.forms(): print f # Select the first (index zero) form br.select_form(nr=0) # Let's search br.form['id']='lbu142vj' br.form['sID']=['on'] br.form['pw']='wbelryl' br.submit() #print br.response().read() r = br.open(http://www.naver.com;) rs = r.read().decode('utf-8') #print rs r = br.open(http://blog.naver.com/PostWriteForm.nhn? Redirect=WriteblogId=lbu142vjwidgetTypeCall=true) rs = r.read() print rs for f in br.forms(): print f br.select_form(nr=0) br.form['post.category.categoryNo']=[*1] br.form['post.title']='subject' br.form['contents.contentsValue'] = 'content' br.submit() -- http://mail.python.org/mailman/listinfo/python-list
Work around metaclass programming
I have a class called Signal which is a descriptor. It is a descriptor so that it can create BoundSignals, much like the way methods work. What I would like to do is to have the class be a descriptor when instantiated in what will be the locals of the class, but not a descriptor everywhere else. Can I do this without requiring the class to use a special metaclass that does the transformation? One way I can think of which would work if there is such a thing would be a hook that type will call on the value of locals if that value is defined. That way I could just return the descriptor from that hook. The advantage of this over using a metaclass is that these are combinable. Am I making sense? -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games -- http://mail.python.org/mailman/listinfo/python-list
Re: windows side-by-side configuration woes on windows HPC
It is indeed a pain. I would really like a work-around. Matplotlib is supposed to be immune to this nowadays but it's not. Nor are some other third-party modules. Did they break with the new release? (2.6.3?) -nick On Thu, Oct 8, 2009 at 1:12 PM, M.-A. Lemburg m...@egenix.com wrote: Nick Touran wrote: Copying my local copy of Python 2.6 to a Windows HPC 2008 system is giving dll side-by-side configuration errors for some third-party packages (matplotlib, pyMSSQL, in particular). I understand that there is a tradition of Python supporting XCOPY deployment, and would really like to be able to just copy my C:\python26 folder to the network drive and have it run on the server. I got around a related issue (http://bugs.python.org/issue4566) just by upgrading to 2.6.3 and was able to import socket and mpi4py and everything, except matplotlib and pyMSSQL, that is. I also understand that if I were to install the MS Visual Studio 2008 redistribution package on the server that everything would be fine because the modules just can't find the proper C run-time DLL. The problem with that is two-fold: I don't have admin rights on the machine and there are over 1000 machines on the cluster and I don't think the admin is going to install that on all of them. So is there any way to set an environmental variable or something to get these packages to know where to find the proper msvcr90.dll, akin to setting LD_LIBRARY_PATH in Linux? Is there another solution? I assume this is related to this new problem: http://bugs.python.org/issue4120 Manifests were meant to solve some of the DLL mess... apparently they cause even more grief. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 08 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: which dictionary with attribute-style access?
On Mon, 12 Oct 2009 20:58:35 +0100, Andreas Balogh balo...@gmail.com wrote: Hello, googling I found several ways of implementing a dictionary with attribute-style access. 1. ActiveState cookbook: http://code.activestate.com/recipes/473786/ 2. ActiveState cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 3. web2py codebase: Storage(dict) I enclosed the three implementations below. My question to the Python specialists: which one is the most correct? Accessing the dictionary as a dictionary. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: windows side-by-side configuration woes on windows HPC
Nick Touran wrote: It is indeed a pain. I would really like a work-around. Matplotlib is supposed to be immune to this nowadays but it's not. Nor are some other third-party modules. Did they break with the new release? (2.6.3?) The main problem appears to be that the the MS VC9 compiler defaults to embedding a dependency on the MS VC90 CRT DLL into extension modules: dependency dependentAssembly assemblyIdentity type=win32 name=Microsoft.VC90.CRT version=9.0.21022.8 processorArchitecture=x86 publicKeyToken=1fc8b3b9a1e18e3b/assemblyIdentity /dependentAssembly /dependency Unless you have installed the CRT runtime DLLs installed system-wide, this will require the DLLs to be installed next to the extension module DLL or PYD file... and that even though the Python process itself will already have loaded the DLL from the Python directory. A work-around is attached to the ticket as patch. Even though a fix for distutils is planned in 2.6.4, this type of problem will pop up for all kinds of software using VC90-based DLLs as plugins, so it's probably better to just install the CRT runtime DLLs in the WinSxS directory using the CRT installers: x86: http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2displaylang=en x86_64: http://www.microsoft.com/downloads/details.aspx?familyid=BA9257CA-337F-4B40-8C14-157CFDFFEE4Edisplaylang=en On Thu, Oct 8, 2009 at 1:12 PM, M.-A. Lemburg m...@egenix.com wrote: Nick Touran wrote: Copying my local copy of Python 2.6 to a Windows HPC 2008 system is giving dll side-by-side configuration errors for some third-party packages (matplotlib, pyMSSQL, in particular). I understand that there is a tradition of Python supporting XCOPY deployment, and would really like to be able to just copy my C:\python26 folder to the network drive and have it run on the server. I got around a related issue (http://bugs.python.org/issue4566) just by upgrading to 2.6.3 and was able to import socket and mpi4py and everything, except matplotlib and pyMSSQL, that is. I also understand that if I were to install the MS Visual Studio 2008 redistribution package on the server that everything would be fine because the modules just can't find the proper C run-time DLL. The problem with that is two-fold: I don't have admin rights on the machine and there are over 1000 machines on the cluster and I don't think the admin is going to install that on all of them. So is there any way to set an environmental variable or something to get these packages to know where to find the proper msvcr90.dll, akin to setting LD_LIBRARY_PATH in Linux? Is there another solution? I assume this is related to this new problem: http://bugs.python.org/issue4120 Manifests were meant to solve some of the DLL mess... apparently they cause even more grief. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 08 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 12 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: organizing your scripts, with plenty of re-use
On Oct 12, 11:24 am, Buck workithar...@gmail.com wrote: On Oct 10, 9:44 am, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: The good thing is that, if the backend package is properly installed somewhere in the Python path ... it still works with no modifications. I'd like to get to zero-installation if possible. It's easy with simple python scripts, why not packages too? I know the technical reasons, but I haven't heard any practical reasons. No it's purely technical. Well mostly technical (there's a minor issue of how a script would figure out its root). No language is perfect, not even Python, and sometimes you just have to deal with things the way they are. We're trying to help you with workarounds, but it seems like you just want to vent more than you want an actual solution. If it makes you feel better, go ahead and vent. If you want a solution, try instead to sit down and implement the advice Steven, Gabriel, or I gave you. If the reasons are purely technical, it smells like a PEP to me. Good luck with that. I'd wholeheartedly support a good alternative, I just want to warn you that it's not a simple issue to fix, it would be involve spectacular and highly backwards-incompatible changes. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
In python CGI, how to pass hello back to a javascript function as an argument at client side?
Hi everyone, How can I pass a string generated from python cgi at server side to a javascript function as an argument at client side? Here is my case: 1. client side: load is a javascript function in a html page. It starts the python CGI test.py via Apache: html script language=javascript ... load(test.py ); ... /script ... /html I want test.py to return a hello back so the javascript function load takes hello as argument like load(hello). 2. server side: test.py ... #!c:\python24\python.exe def main(): message = 'hello' #return message main() ... Any ideas? Thanks in advance for your help. ouyang -- http://mail.python.org/mailman/listinfo/python-list
Re: organizing your scripts, with plenty of re-use
Stef Mientki wrote: Gabriel Genellina wrote: [snip] That's what I meant to say. It IS a zero-installation schema, and it also works if you properly install the package. Quoting Steven D'Aprano (changing names slightly): You would benefit greatly from separating the interface from the backend. You should arrange matters so that the users see something like this: project/ +-- animal +-- mammal +-- reptile +-- somepackagename/ +-- __init__.py +-- animals.py +-- mammals/ +-- __init__.py +-- horse.py +-- otter.py +-- reptiles/ +-- __init__.py +-- gator.py +-- newt.py +-- misc/ +-- __init__.py +-- lungs.py +-- swimming.py [snip] The key is to put all the core functionality into a package, and place the package where Python can find it. Also, it's a good idea to use relative imports from inside the package. There is no need to juggle with sys.path nor even set PYTHONPATH nor import __main__ nor play any strange games; it Just Works (tm). please don't get angry, I'm not a programmer, I'm just a human ;-) Hierarchical choices are done on todays knowledge, tomorrow we might have different views and want/need to arrange things in another way. An otter may become a reptile ;-) So from the human viewpoint the following should be possible (and is for example possible in Delphi) - I can move the complete project anywhere I like and it should still work without any modifications (when I move my desk I can still do my work) Move a complete package anywhere along the PYTHONPATH and it will still work. Check. - I can move any file in he project to any other place in the project and again everything should work without any modifications ( when I rearrange my books, I can still find a specific book) Move any file in any directory to any other spot in that same directory and it will still work. Check. ;-) Humans are a lot smarter than computers. Even 'just humans'. ;-) If you move your book, then can't find it on the last shelf it used to be on, you look on other shelves, you look on your desk, you look on the coffe table, you look in your car, etc, etc, and so forth. If you move a file in a package to somewhere else, and you don't tell the package where it's at, it's not going to start looking all over the hard-drive for it. If that were the case you would have to be extra careful to have every module's name be distinct, and then what's the point of having packages? ~Ethan~ In my humble opinion if these actions are not possible, there must be redundant information in the collection. The only valid reason for redundant information is to perform self healing (or call it error correction), and here we have a catch-22. cheers, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: Error en el bus from python
Jorgen Grahn wrote: Bus Error is an old BSD-ism which I guess you don't see much in Linux or Solaris these days (or maybe I never run buggy code ;-). It translates roughly to segmentation fault, but IIRC it is more about accessing memory words on nonaligned adresses than about accessing addresses your process doesn't own. I think the term goes back to the PDP-11 or thereabouts. The Unibus used a handshaking protocol, and if you tried to access an address that didn't have any memory or I/O device assigned to it, the bus hardware would time out and you got an interrupt. The 68K family also used the term in a similar way. I think the distinction between a bus error and a seg fault is that bus errors are to do with physical addresses, and seg faults are to do with virtual addresses. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle's backward compatibility
En Mon, 12 Oct 2009 12:17:52 -0300, Peng Yu pengyu...@gmail.com escribió: If I define my own class and use pickle to serialize the objects in this class, will the serialized object be successfully read in later version of python. From http://docs.python.org/library/pickle.html: The pickle serialization format is guaranteed to be backwards compatible across Python releases. What you save now should be readable by a later version. Your own class must be able to process what you saved (regarding added/deleted/renamed attributes, changes in meaning, renamed/moved classes...) What if I serialize (using pickle) an object of a class defined in python library, will it be successfully read in later version of python? As JPC said: no guarantees. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list