FREE Tutorials on HTML XHTML CSS JavaScript XML XSL ASP SQL ADO VBScript, SAP - ABAP
FREE Tutorials on HTML XHTML CSS JavaScript XML XSL ASP SQL ADO VBScript, SAP - ABAP visit ebooks.univdatabase.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Another Question
On May 23, 10:47 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote: > On May 23, 1:44 pm, Gandalf <[EMAIL PROTECTED]> wrote: > > > you've been very helpful but still i have only one problem. I wont the > > window not to be close after clicking the X button. > > I wont the program to stay on the toolbar > > > thanks! > > Well then, in your event handler, just don't do anything. > > def onClose(self, event): > pass > > or maybe you want to hide the frame? > > def onClose(self, event): > self.frame.Hide() > > Just make sure you give the user some other way to close it and in > that handler, you'll need to call self.frame.Destroy(). > > Alternatively, you can just tell the frame not to create the "X" > button: > > self.frame = wx.Frame(None, -1, title="My Frame", > style=wx.SYSTEM_MENU) > > However, that makes it pretty annoying to close. > > Mike OK the first method still didn't work. no matter what i do the window keep closing but the last one worked nice and all the top menu disappear thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
Judging python's speed by how fast websites go is not going to work very well. There are many things that can bog down the "speed" of loading a web site, especially if you are judging speed by how long a page takes to load. torontolife.com is loading extremely slow for me also. So is wikipedia. Much slower than say, code.google.com, or the trac site I have running on my remote server. I have seen just as many slow php sites as slow python sites. Also, the hosting solution plays a huge part in how fast a site responds. If someone is using python through cgi, that IS going to be very slow, whereas other solutions are faster. PHP sites are not hosted on cgi, while many python solutions sadly still are. So yeah, finding specific sites that are slow and written in python and claiming that it's slow is trolling. Youtube is slow these days, but a year or more ago it was very fast. They just haven't been able to keep up with demand. (Even movies play slow, constantly buffering, and the movies don't even play from python). Of all domains, the web domain needs speed (from logic code, where python resides) the LEAST, because so much of the time is spent buffering packets, alternating between threads or processes, or accessing the database or files. All of these operations contribute the most to slow web pages. And before you complain that python has to "buffer packets", or "access the database", all of these operations are done at the C level (or lower). Python is slow, but php is slower. And python's speed is always improving. On the other hand, it is much easier to find good php hosting services, due to it's wide availability - better hosting = faster sites. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
I love it when a troll tries to make his/hers/its point with a vague, biased assumption: "I mean, it's not that slow - wait, I guess it's slower, because I... I think so! Yeah! It's slow! At least it feels like it..." It's all about choosing the right tool. If you think Python doesn't suit your needs, you really should look for something that does, instead of wasting your (and our) time with "guesses" and "feelings". Research/develop/execute a benchmark. Gather and analyze relevant data. Make a real contribution. Peace, Paolo On May 24, 3:12 am, Torsten Bronger <[EMAIL PROTECTED]> wrote: > Hallöchen! > > cm_gui writes: > > [...] > > > if python is such a good programming/scripting language, > > why can't they build a faster interpreter/compiler engine? > > and beat php and zend. > > to the python team, rebuild your interpreter! > > > torontolife.com is slow. > > For me, torontolife.com is exactly as fast as Wikipedia. > > Tschö, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > Jabber ID: [EMAIL PROTECTED] >(Seehttp://ime.webhop.orgfor further contact info.) -- http://mail.python.org/mailman/listinfo/python-list
Python, Daemons and D-Bus
Seeking feedback from group members on a design I'm looking at using in a project. I've created an XML-RPC server and a number of Daemons, the idea is that the XML-RPC server gets a request from a user interface of some sort and then sends data to the Daemon processes to do work. Daemons will also need to feed back task information to the XML-RPC server. For the communications between the Daemons and XML-RPC server I was thinking of using D-Bus (The project is for Linux and *BSD) but wanted to hear what others thought of the idea? Would you use D-Bus or a more traditional IPC method such as sockets? Although D-Bus is relatively new it looks interesting, just not sure it would work well in this kind of project. Thanks in advance for your thoughts and opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing objects in relational database
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > I don't know if you'd label it 'elegant', but as far as I'm > concerned, storing serialized objects as blobs in a relational > database is mostly non-sense. If I use a relational database, it's > because it is a *relational* database. If you want an OODB, then we > have the ZODB, Durus and a couple others. ... not to forget object-relational mappers like SQLAlchemy, SQLObject... -- http://mail.python.org/mailman/listinfo/python-list
Re: Unhandled exceptions checking
On Sat, May 24, 2008 at 3:31 AM, Yosifov Pavel <[EMAIL PROTECTED]> wrote: > Does somebody know existent tool for checking unhandled exceptions? > Like in Java when method throws exception but in code using this > method, try...catch is missed. May be something like PyChecker? > Python is too dynamic to do this reliably. eg: e = exception_returning_func() raise e You'll probably be better served by capturing and logging all unhandled exceptions in your app ("logger.exception(e)" works nicely in a high level "catch Exception e" block), and then notifying users. Another thing to try is coverage testing. Won't raise all possible exceptions in a given piece of code, but at least you can check if all lines get run once. David. -- http://mail.python.org/mailman/listinfo/python-list
image scaling in cairo, python
[also posted to: [EMAIL PROTECTED] hi all, i've heard cairo has become the image scling library for firefox3. is that true? wonderful, i want to do that in python. there's a python interface for cairo, right? i've used it before to do simple vector stuff. seems to work. however, i haven't been able to find relevant pointers via google. so do you have any pointers on how to resize a raster image with python using cairo? i've been jumping through hoops for a while now, and i believe it should be easier. cheers and ~flow ps. related (long) posts: http://groups.google.com/group/pyglet-users/browse_frm/thread/44253ad01d809da5/cd051e6bced271e1#cd051e6bced271e1 http://groups.google.com/group/comp.lang.python/browse_frm/thread/5df65d99cff0d7bb# -- http://mail.python.org/mailman/listinfo/python-list
SQLite import fails sometimes ?
hello, The import statement "import sqlite3" gives the error given below. In simple programs, the import statement (sometimes) succeed, and I can indeed access the database. So I guess there is some conflict with another part of my program, but as the program is rather large (and dynamic) it's not easy to isolate the problem. Does anyone has a clue how to trace this kind of problem ? thanks, Stef Traceback (most recent call last): File "bricks\brick.py", line 322, in Exec self.Generate_Output_Signals () File "bricks\brick_dBase.py", line 61, in Generate_Output_Signals import sqlite3 File "P:\Python\lib\sqlite3\__init__.py", line 24, in from dbapi2 import * File "P:\Python\lib\sqlite3\dbapi2.py", line 27, in from _sqlite3 import * ImportError: DLL load failed: Invalid access to memory location. -- http://mail.python.org/mailman/listinfo/python-list
Partial download with ftplib and retrbinary
I am breaking/interrupting my connection with the ftp server at present when doing a partial download of a file. I have a callback with retrbinary that raises an exception and ends the download. The problem is that the server is not notified and hangs. I cannot send any further commands and need to relogin to download further. Is there a way to still continue downloading without having to login again. My retrbinary function is: ftp.retrbinary('RETR '+file, handleDownload,1,bound[0]) where bound[0] is an integer specifying the start byte of the download. My callback is: def handleDownload(block): global count,localfile,number localfile.write(block) if count==number: raise(Exception) count=count+1 where number specifies the number of bytes to download. Help would be gratefully received. -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing objects in relational database
[EMAIL PROTECTED] pisze: I don't know if you'd label it 'elegant', but as far as I'm concerned, storing serialized objects as blobs in a relational database is mostly non-sense. If I use a relational database, it's because it is a *relational* database. If you want an OODB, then we have the ZODB, Durus and a couple others. It is sometimes convenient to store objects in mature relational database backend (reliability, stability, support, tools, replication, etc.). See latst efforts with RelStorage backend for ZODB (http://wiki.zope.org/ZODB/RelStorage) - it stores pickled Python objects in Oracle, PostgreSQL or MySQL) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On May 24, 1:56 am, cm_gui <[EMAIL PROTECTED]> wrote: > i'm not trying to 'troll' here. Maybe you're not trying, but you're succeeding. If you want to criticize be constructive about it, otherwise get out. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite import fails sometimes ?
Stef Mientki wrote: hello, The import statement "import sqlite3" gives the error given below. In simple programs, the import statement (sometimes) succeed, and I can indeed access the database. So I guess there is some conflict with another part of my program, but as the program is rather large (and dynamic) it's not easy to isolate the problem. Does anyone has a clue how to trace this kind of problem ? thanks, Stef Traceback (most recent call last): File "bricks\brick.py", line 322, in Exec self.Generate_Output_Signals () File "bricks\brick_dBase.py", line 61, in Generate_Output_Signals import sqlite3 File "P:\Python\lib\sqlite3\__init__.py", line 24, in Is P: a network drive? If not, what is it? I presume from the fact that the next part of the path is not \Python25\Lib that you have not performed a default installation; other than the changes to the path name, what else have you done? What version of Python are you using? What version of Windows? from dbapi2 import * File "P:\Python\lib\sqlite3\dbapi2.py", line 27, in from _sqlite3 import * ImportError: DLL load failed: Invalid access to memory location. Looks like the problem could be with your copy of _sqlite3.pyd (pyd == Python DLL) Try why I did below and tell us how far you got. Cheers, John === try this === C:\junk>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from _sqlite3 import * >>> import _sqlite3 >>> _sqlite3.__file__ 'c:\\python25\\DLLs\\_sqlite3.pyd' === end === -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
Carl Banks schrieb: p = myfunction() if p: print p (I recommend doing it this way in C, too.) This is okay for if-clauses, but sucks for while-loops: while (fgets(buf, sizeof(buf), f)) { printf("%s\n", buf); } is much shorter than char *tmp; tmp = fgets(buf, sizeof(buf), f); while (tmp) { printf("%s\n", buf); tmp = fgets(buf, sizeof(buf), f); } For the case where you want to do this in an elif-clause, look for the recent thread "C-like assignment expression?" which list some workarounds. Or just Google this newsgroup for "assignment expression". It's one of few minor irritating things in Python syntax. Alright, I will. Thanks. Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser können. Es reicht zu wissen, daß andere es besser können und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Fri, 23 May 2008 14:00:33 -0700 (PDT), "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: >On 23 mai, 10:42, "inhahe" <[EMAIL PROTECTED]> wrote: >> "Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in >> messagenews:[EMAIL PROTECTED] >> >> > Brad a écrit : >> >> cm_gui wrote: >> >>> Python is slow. >> >> >> It ain't C++, but it ain't a punch card either... somewhere in between. I >> >> find it suitable for lots of stuff. I use C++ when performance really >> >> matters tho... right tool for the job. Learn a good interpreted language >> >> (Pyhton) and a good compiled language (C or C++) >> >> > LordHaveMercy(tm). Could you guys please learn what you're talking about? >> >> > 1/ being interpreted or compiled (for whatever definition of these >> > terms) is not a property of a language, but a property of an >> > implementation of a language. >> >> That's like saying being spherical is not a property of planets, it's a >> property of an instanciation of a planet. > >I do definitively not have the required knowledge to say anything >about "being spherical" being part of the definition of what a >"planet" is or not. I wasn't going to mention this since it's really not relevant, but since you raise the question: Actually it was a bad analogy because being roughly spherical _is_ part of the definition of "planet". (Of course "spherical" must mean "roughly spherical" here, since no planet is exactly spherical.) A little while ago when Pluto got demoted so it's no longer officially a planet they came up with a definition - part of the definition is that the body is large enough that gravity causes it to assume a spherical shape. >>, and b) It's a far cry to >> imagine a planet coming into being that's not spherical > >Idem > >> (a language as >> dynamic as Python, or most other scripting languages, would be either >> extremely difficult or impossible to make a native compiler for). > >Now this I can tell is false. The problem is not that it's difficult >to "make a native compiler for" dynamic languages, the problem is that >it's difficult to write native compiler for dynamic languages that >generates code that beats the VM/byte-code interpreter/whatever you >name it to be wotrh the effort. > >> I guess I >> should also mention that Python isn't very practical (as in "suitable", >> "right tool for the job", and "perfomance", as mentioned in the above post) >> without an implementation. > >That is debatable. There are algorithm courses taught in "pseudo-code" >- that is, a language that doesn't have any known implementation. > >> So I don't think this distinction has any use >> other than to beat other people over the head with a bat. > >Ok, *you* know this - I mean, the distinction between a language and a >language's implementation(s). Are you sure everyone saying - or >reading - assertions such as "language XXX is slow" or "compiled >languages are faster" etc really know what they're talking about ? > >> > 2/ actually, all known Python implementations compile to byte-code. >> >> Which is then interpreted, but you're still technically right, because >> "compiled" can mean either compiled to bytecode or compiled to native code, >> despite what it actually did mean. Semantics FTW!! > >Yes, semantics. But a bit more than semantics - byte-code interpreters >are usually way faster than "pure" interpreter, and start to be fast >enough for quite a lot of practical use. > >Ok, I'll stop on this - once again, sorry for the noise, and please >bear with me, I tend to be a bit too much on the pedantic side >sometimes. But still, thanks to the pedantics peoples on usenet that >taught me so much so far and still teach me more and more... David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
George Sakkis schrieb: However, this "assignment and comparison" is not working. What's the "Python way" of doing this kind of thing? The most obvious and readable of course: use two statements, as one should do regardless of the language, instead of resorting to error- prone hacks. As I said in the reply to Carl, this might be okay for if-clauses, but is bothering me with while-loops. Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser können. Es reicht zu wissen, daß andere es besser können und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
TheSaint schrieb: On 06:59, sabato 24 maggio 2008 Johannes Bauer wrote: However, this "assignment and comparison" is not working. What's the "Python way" of doing this kind of thing? If you want speak a language that isn't understood mostly you'll face unexpected risults. When you got started with C/C++, were you writing plain english to do programs? Far away to be a flame, each language have its own grammar that some time it will need to be learnt. Therefore, even myself still bad to write english, since my mind thinking italian sentences. Well, I do not really see your point - of couse I'm aware (and admitted) that my Python skills are extremely amateurish. That's why I'm asking for help here... Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser können. Es reicht zu wissen, daß andere es besser können und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: Relationship between GUI and logic?
On 23 May 2008 18:23:04 +0100 (BST), Matthew Woodcraft <[EMAIL PROTECTED]> wrote: >John Salerno <[EMAIL PROTECTED]> wrote: >> Basically, the question is this: can you write the logic behind a >> program (whether it be a game, an email client, a text editor, etc.) >> without having any idea of how you will implement the GUI? > >You probably could, but it's best not to unless you're somehow forced >to. > >In practice, the interface that you want your 'logic' layer to provide >to the GUI is likely to depend on some of the details of how the GUI >works. > >If you did the lower levels first without having any idea at all of >what you were going to do with the GUI, it's quite likely that you'd >find you'd written a few functions which turned out not to be needed at >all, or that some functionality that the GUI needs to use very >frequently is rather slow to execute, or that some functionality that >you thought belonged to the 'logic' is really better done in the GUI >layer, and so on and so forth. > >For example, if you were writing the 'logic' for a chess program you >might choose a way of modelling the board that can't represent a >position with more than one black king. And then when you got round to >doing the GUI you might find out that your users would like to be able >to have this temporarily when setting up a position. What you say may be true, but this doesn't seem to me like a good example. Not that I see _why_ the player would want to have two kings temporarily, but if so I wouldn't have the view report this state to the model, I'd have the view wait until the player had decided on the final configuration betore saying anything to the model. The model should only deal with legal positions. (Could be that it's not until we start actually playing the game through the GUI that we find the model can't deal with two black queens. But that's not an example either, that would just mean the model is wrong, not allowing every legal position.) >-M- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: WXpython Question
On Fri, 23 May 2008 06:40:13 -0700 (PDT), Gandalf <[EMAIL PROTECTED]> wrote: >On May 23, 3:29 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote: >> On May 23, 8:24 am, Gandalf <[EMAIL PROTECTED]> wrote: >> >> > I try to reach a specific wx StaticText element's text and to change >> > it by clicking on a button >> >> > now let's say the this is my element: >> >> > wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE) >> >> > And this is my EVT_BUTTON bind function : >> >> > def OnClick(event): >> >> > which code shude i enter to change "hello" to "goodbay"? >> >> > thanks >> >> You're probably looking for SetLabel(). So if you do something like >> this to instantiate the StaticText: >> >> self.myText = wx.StaticText(panel, 15, "Hello" ,(30, 70) , >> style=wx.ALIGN_CENTRE) >> >> Then you can change your text by adding this to your OnClick event >> handler: >> >> self.myText.SetLabel("goodbye") >> >> Have fun! And remember, there's a great wxPython mailing list too: >> >> http://www.wxpython.org/maillist.php >> >> Mike > >Thanks! You should also note docs.wxwidgets.org (I tend to find that by googling "wxTreeCtrl" or whatever.) The descriptions of various components there are more complete than in the (excellent!) wxPython book - it's C++ but usually not hard to figure out what the corresponding wxPython should be. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
On Sat, 24 May 2008 13:12:13 +0200, Johannes Bauer wrote: > Carl Banks schrieb: > >> p = myfunction() >> if p: >> print p >> >> (I recommend doing it this way in C, too.) > > This is okay for if-clauses, but sucks for while-loops: > > while (fgets(buf, sizeof(buf), f)) { > printf("%s\n", buf); > } > > is much shorter than > > char *tmp; > tmp = fgets(buf, sizeof(buf), f); > while (tmp) { > printf("%s\n", buf); > tmp = fgets(buf, sizeof(buf), f); > } Can be written in Python as: from functools import partial # ... for buf in iter(partial(f.read, buf_size), ''): print '%s\n' % buf Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
On Sat, 24 May 2008 13:13:08 +0200, Johannes Bauer wrote: > George Sakkis schrieb: > >>> However, this "assignment and comparison" is not working. What's the >>> "Python way" of doing this kind of thing? >> >> The most obvious and readable of course: use two statements, as one >> should do regardless of the language, instead of resorting to error- >> prone hacks. > > As I said in the reply to Carl, this might be okay for if-clauses, but > is bothering me with while-loops. Then try to write the ``while`` loop as ``for`` loop and move the comparison into a generator function, or use the two argument variant of `iter()`, or `itertools.takewhile()`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: php vs python
Michael Fesser <[EMAIL PROTECTED]> writes: > you don't like PHP, that's perfectly OK. But you should accept that > it's only a tool and just as good as the one who uses it. For me and > many others it's a quite good language, we're able to write clean and > efficient code with it in a rather short time. I'm sure that anyone who is competent enough can write clean code in any language (in the case of PHP, I am only familiar with one significant example: I use and have written a few simple extensions for mediawiki, and I find it quite easy to understand and navigate the code). However, while I feel that most languages are quite neutral about this, I find that Python *encourages* me to write better code. In other words, Python is not only a tool, it's also a lovely language. Languages are a bit like shoes. You probably wouldn't want to wear the pair I'm most comfortable in! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with import / namespace
Hi Laszlo Thanks for your reply but it stil didnt work: i opened python shell, changed active directory to \\one and imported tmp1. now the correct file is loaded. now i deleted tmp1 i dir os.chdir(\\two) and imported tmp1 again. now the incorrect file is loaded (the same one as before). i did one more trial with sys.path insted of os.chdir() and it didnt work either (sys.path.append(\\one), import tmp1, del tmp1, sys.path.remove(\\one), sys.path.append(\\two), import tmp1) can you please try to do so and see for yourself that something is wrong here. The reason why i am not using other names is because i am triyng to build something that will execute external sw and for that i have no control of the names of the modules, but this is not important, because python must give us a way to clear previously imported module Thanks again Ohad On 5/21/08, Laszlo Nagy <[EMAIL PROTECTED]> wrote: > > ohad frand wrote > >> Hi >> Thanks for the answer. >> I probably didnt write the problem accurately but it is not as you >> described. >> (i already read before the section that you pointed and it didnt help me) >> the problem is that i dont want to import a file from different directory >> but only from the same directory. >> \\1\tmp2.py imports \\1\tmp1.py >> \\2\tmp2.py imports \\2\tmp2.py >> but when i execute the following script in the interpreter i get that the >> second tmp2.py file imports not the file from the same directory but the >> file that was already imported by the first executed tmp2.py file. >> > I think that using absolute names DOES solve the problem. > > import two.tmp2 # This will import tmp2.py in "two" folder for sure! > > >>> execfile("tmp2.py") <- here the executaion is OK >> >>> os.chdir("c:\\2") >> >>> execfile("tmp2.py") <- here the execution is not ok because tmp2.py >> file imports the tmp1.py file from c:\\1 which is not OK >> > Hmm looks like your tmp2.py file is not a module but a whole program. No > wonder I could not understand you - I thought that "tmp2.py" is a module, > not a program. > > The answer in this case: if tmp2.py is a program then you should either > manipulate sys.path or chdir to the containing dir, as I told in my former > post. ( os.split(os.abspath(__file...))) -> then chdir or > sys.path.insert(0,mydir) ) > > in between those two execfile commands i tried to do a lot of things but >> every time python imported the incorrect file for the second execution. (i >> am not building a package and those names are just examples for the problem, >> i am not really using 1 and 2 names as dirs) >> > Why do you need execfile? > > Laszlo > > -- http://mail.python.org/mailman/listinfo/python-list
Popen: NameError: name 'PIPE' is not defined
Hi I import subprocess and use Popen, but PIPE is not defined. I used 2.5.1, 2.5.2, Python 2.6a3+ (trunk:63576, May 24 2008, 12:13:40), it's always the same. What am I missing ? Thanks Mathieu -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite import fails sometimes ?
John Machin wrote: Stef Mientki wrote: hello, The import statement "import sqlite3" gives the error given below. In simple programs, the import statement (sometimes) succeed, and I can indeed access the database. So I guess there is some conflict with another part of my program, but as the program is rather large (and dynamic) it's not easy to isolate the problem. Does anyone has a clue how to trace this kind of problem ? thanks, Stef Traceback (most recent call last): File "bricks\brick.py", line 322, in Exec self.Generate_Output_Signals () File "bricks\brick_dBase.py", line 61, in Generate_Output_Signals import sqlite3 File "P:\Python\lib\sqlite3\__init__.py", line 24, in Is P: a network drive? If not, what is it? P is just a normal local drive, I presume from the fact that the next part of the path is not \Python25\Lib that you have not performed a default installation; other than the changes to the path name, what else have you done? Indeed, the only thing I've changed is the pathname. I also installed * install python 2.5.2 msi * install numpy 1.0.4 * install scipy 0.6.0 * install wxPython + docs-demo 2.8.7.1 unicode * install MatPlotLib 0.91.2 * install Pygame + docs 1.8.0 * install SendKeys 0.3 * install PyScripter 1.7.2 , updated to 1.9.9.1 !!! * install Rpyc 3.0 * install ConfigObj 4.5.2 , unpack in sitelibs and run "python setup.py install" I don't know if this matters, but I also use sqlite3 from other than Python programs. What version of Python are you using? What version of Windows? Windows-XP - sp2 from dbapi2 import * File "P:\Python\lib\sqlite3\dbapi2.py", line 27, in from _sqlite3 import * ImportError: DLL load failed: Invalid access to memory location. Looks like the problem could be with your copy of _sqlite3.pyd (pyd == Python DLL) Try why I did below and tell us how far you got. Cheers, John === try this === C:\junk>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from _sqlite3 import * >>> import _sqlite3 >>> _sqlite3.__file__ 'c:\\python25\\DLLs\\_sqlite3.pyd' === end === looks identical to me C:\Documents and Settings\Administrator>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from _sqlite3 import * >>> import _sqlite3 >>> _sqlite3.__file__ 'P:\\Python\\DLLs\\_sqlite3.pyd' end = Any other suggestions ? thanks, Stef -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
Johannes Bauer pisze: > I'm just starting with Python and am extremely unexperienced with it so > far. Having a strong C/C++ background, I wish to do something like > > if (q = getchar()) { > printf("%d\n", q); > } > > or translated to Python: > > if (p = myfunction()): > print p > > However, this "assignment and comparison" is not working. What's the > "Python way" of doing this kind of thing? Assignment operation (or, as we prefer calling: "binding value to name") has no boolean value, because it succeeds always. While call to myfunction can return any value, binding it to name p has no value at all. Tell us your objective, so we could show you "proper way" (tm). ;) -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters -- http://mail.python.org/mailman/listinfo/python-list
Re: Reloading function obtained via 'from xxx import yyy'
On Fri, May 23, 2008 at 3:40 PM, Joel Koltner <[EMAIL PROTECTED]> wrote: > How do I get Python to correctly re-load this function definition? > > In test.py: > > def testFunc(): >print 'My testFunc!' > > I execute... > > >>> from test import testFunc > >>> testFunc() > My testFunc! > > Fine... now I change test.py to: > > def testFunc(): >print 'Modified testFunc!' > > ...and I'd like to reload testFunc. How do I do so? 'from test import > testFunc' keeps the old definition around, and 'reload test' of course > doesn't > work becayse I didn't use 'import test' in the first place. > "Namespaces are one honking great idea -- let's do more of those!" If you don't want to have to type out the full name every time just do "import test as t". That makes it only 2 extra characters to type. If you don't put everything in the same namespace, you don't have to worry about clashing. > > Thanks for the help, > ---Joel > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Code correctness, and testing strategies
Hi list. What strategies do you use to ensure correctness of new code? Specifically, if you've just written 100 new lines of Python code, then: 1) How do you test the new code? 2) How do you ensure that the code will work correctly in the future? Short version: For (1) I thoroughly (manually) test code as I write it, before checking in to version control. For (2) I code defensively. Long version: For (2), I have a lot of error checks, similar to contracts (post & pre-conditions, invariants). I've read about Python libs which help formalize this[1][2], but I don't see a great advantage over using regular ifs and asserts (and a few disadvantages, like additional complexity). Simple ifs are good enough for Python built-in libs :-) [1] PEP 316: http://www.python.org/dev/peps/pep-0316/ [2] An implementation: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/436834 An aside: What is the correct situation in which to use assert statements in Python? I'd like to use them for enforcing 'contracts' because they're quick to type, but from the docs: "Assert statements are a convenient way to insert debugging assertions into a program:" So to me it sounds like 'assert' statements are only useful while debugging, and not when an app is live, where you would also (especially!) want it to enforce contracts. Also, asserts can be removed with -O, and you only ever get AssertionError, where ValueError and the like might be more appropriate. As for point 1 (how do you test the new code?): I like the idea of automated unit tests. However, in practice I find they take a long time to write and test, especially if you want to have good coverage (not just lines, but also possible logic branches). So instead, I prefer to thoroughly test new code manually, and only then check in to version control. I feel that if you are disciplined, then unit tests are mainly useful for: 1) Maintenance of legacy code 2) More than 1 person working on a project One recent personal example: My workstation is a Debian Unstable box. I like to upgrade regularly and try out new library & app versions. Usually this doesn't cause major problems. One exception is sqlalchemy. It's API seems to change every few months, causing warnings and breakage in code which used the old API. This happened regularly enough that for one project I spent a day adding unit tests for the ORM-using code, and getting the unit tests up to 100% coverage. These tests should allow me to quickly catch and fix all sqlalchemy API breakages in my app in the future. The breakages also make me want to stop using ORM entirely, but it would take longer to switch to SQL-only code than to keep the unit tests up to date :-) My 'test code thoroughly before checkin' methodology is as follows: 1) Add "raise 'UNTESTED'" lines to the top of every function 2) Run the script 3) Look where the script terminated 4) Add print lines just before the exception to check the variable values 5) Re-run and check that the values have expected values. 6) Remove the print and 'raise "UNTESTED"' lines 7) Add liberal 'raise "UNTESTED"' lines to the body of the function. 8.1) For short funcs, before every line (if it seems necessary) 8.2) For longer funcs, before and after each logic entry/exit point (blocks, exits, returns, throws, etc): eg, before: if A(): B() C() D() E() after: raise 'UNTESTED' if A(): raise 'UNTESTED' B() C() D() raise 'UNTESTED' raise 'UNTESTED' E() 8.2.1) Later I add "raise 'UNTESTED'" lines before each line in the blocks also, if it seems necessary. 9) Repeat steps 2 to 8 until the script stops throwing exceptions 10) Check for 'raise "UNTESTED"' lines still in the script 11) Cause those sections of code to be run also (sometimes I need to temporarily set vars to impossible values inside the script, since the logic will never run otherwise) And here is one of my biggest problem with unit tests. How do you unit test code which almost never runs? The only easy way I can think of is for the code to have 'if or lines'. I know I'm meant to make 'fake' testing classes which return erroneous values, and then pass these objects to the code being tested. But this can take a long time and even then isn't guaranteed to reach all your error-handling code. The above methodology works well for me. It goes fairly quickly, and is much faster than writing and testing elaborate unit tests. So finally, my main questions: 1) Are there any obvious problems with my 'correctness' strategies? 2) Should I (regardless of time it takes initially) still be adding unit tests for everything? I'd like to hear what XP/agile programming advocates have to say on the subject. 3) Are there easy and fast ways to do write and test (complete) unit tests? 4) Any other comments? Thanks for your time. David. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTMLParser error
On May 22, 8:20 pm, alex23 <[EMAIL PROTECTED]> wrote: > On May 23, 5:06 am, [EMAIL PROTECTED] wrote: > > > Nope, this is my first experience with object oriented programming, > > only been learning python for a few weeks but it seemed simple enough > > to inspire me to be a bit ambitious. If you could hook me up with some > > good docs that would be great. I was about to but a book on python, > > specifically OO based, but il look at these docs first. I understand > > most of the concepts of inheritance, just not ever used them before. > > Ah, okay, I'm really sorry, if I'd known I would've tried to explain > things a little differently :) > > Mark Pilgrim's Dive Into Python is a really good place to > start:http://www.diveintopython.org/toc/index.html > > For a quick overview of object oriented programming in Python, > try:http://www.freenetpages.co.uk/hp/alan.gauld/ > Specifically:http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm > > But don't hesitate to ask questions here or even contact me privately > if you'd prefer. Thanks for the help, sorry for the delayed reply, flew out to detroit yesterday and the wifi here is rubbish. Will definitely get reading Dive into Python, and the other article cleared a lot up for me. Hopefully I wont have these errors any more, if I keep getting them il get in touch. Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: Popen: NameError: name 'PIPE' is not defined
Mathieu Prevot schrieb: Hi I import subprocess and use Popen, but PIPE is not defined. I used 2.5.1, 2.5.2, Python 2.6a3+ (trunk:63576, May 24 2008, 12:13:40), it's always the same. What am I missing ? Without showing code, it's hard to know. A guess is: if you use import subprocess then use subprocess.PIPE Or if using from subprocess import Popen make sure to do from subprocess import Popen, PIPE Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Popen: NameError: name 'PIPE' is not defined
On Sat, 24 May 2008 14:09:07 +0200,Mathieu Prevot wrote: > Hi > > I import subprocess and use Popen, but PIPE is not defined. I used > 2.5.1, 2.5.2, Python 2.6a3+ (trunk:63576, May 24 2008, 12:13:40), it's > always the same. What am I missing ? > > Thanks > Mathieu Try subprocess.PIPE. -- http://mail.python.org/mailman/listinfo/python-list
Re: Popen: NameError: name 'PIPE' is not defined
2008/5/24 Diez B. Roggisch <[EMAIL PROTECTED]>: > Mathieu Prevot schrieb: >> >> Hi >> >> I import subprocess and use Popen, but PIPE is not defined. I used >> 2.5.1, 2.5.2, Python 2.6a3+ (trunk:63576, May 24 2008, 12:13:40), it's >> always the same. What am I missing ? > > Without showing code, it's hard to know. A guess is: if you use > > import subprocess > > > then use > > > subprocess.PIPE > > Or if using > > from subprocess import Popen > > make sure to do > > from subprocess import Popen, PIPE > > Diez Indeed... thank you ! Mathieu -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Fri, 23 May 2008 22:56:57 -0700, cm_gui wrote: > i am not comparing Python with C or C++ which are of course compiled > languages. > > if there is any consolation to Python lovers here, Python is still > faster than Microsoft ASP/ASPX. > > i'm not trying to 'troll' here. it's not just me. many have complained > that python is slow. python websites are slow. > > if python is such a good programming/scripting language, why can't they > build a faster interpreter/compiler engine? and beat php and zend. > to the python team, rebuild your interpreter! > > > torontolife.com is slow. > > okay, maybe Python is only slightly slower than PHP, but it APPEARS to > be much slower. > there is a distinct waiting time whenever you access a python web page > before the page starts loading. but once it loads, it is fast. php page > starts loading immediately once you access it, but you can see the page > slowly loading. because you see the page starts loading immediately, you > feel it is fast. It's only your feelings based on prejudice. Please look at the real benchmarks: http://www.alrond.com/en/2007/jan/25/performance-test-of-6-leading- frameworks/ PHP is the slowest. Python/Django is the fastest. 2x-35x times faster then PHP. Give us the real benchmarks or stop trolling. Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
In article <[EMAIL PROTECTED]>, John Roth <[EMAIL PROTECTED]> wrote: > > Does the following patch has a chance of being introduced in the > > standard python distribution? > > I certainly hope not! I think you're being overly negative here. Antoon went to the trouble to read the sources and post a diff. At the very least, he deserves a more polite response. But, more than that, I think Antoon's idea has some merit. I understand that the mantra in unit testing is that the tests should be able to be run in any order. Still, it's the job of a library package to make it easy to do things, not to enforce policy. If somebody (for whatever reason) has a need to run their tests in a certain order, why is it our job to make it hard for them to do that? In fact, unittest.defaultTestLoader *already* sorts the tests into alphabetical order by their name. So, if somebody wanted to get the tests run in order, they could just name their tests "test0001", "test0002", etc. In fact, I've done that in the past when I had some (long forgotten) reason why I wanted to run a bunch of things in order. Allowing the tests to be sorted by line number order instead of by name just makes it a little easier to do the same thing. If somebody wants that functionality, and is willing to put in the effort to write the code to do it, and contribute that back to the community, I don't see any reason why it shouldn't be considered. It would have to be done in a way that doesn't change the current behavior (perhaps by shipping a subclass of TestLoader which users could use instead of the default). I'm not saying that we *need* to include it, just that it's not such a bad idea that it deserves responses like "I certainly hope not!" -- http://mail.python.org/mailman/listinfo/python-list
PIPE stderr
Hi again, I don't have the same ouptput between 1) and 2) ... what's happening ? 1) wget http://www.youtube.com/v/A8bwZf3vXjg -O /dev/null 2> file 2) k = Popen (["wget", "http://www.youtube.com/v/A8bwZf3vXjg";, "-O", "/dev/null"], stderr=PIPE) print k.stderr In the case 2) I got: open file '', mode 'rb' at 0x5a608> and I want what I get in file from 1) ... how to do this ? Mathieu -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
On May 24, 10:12 am, Roy Smith <[EMAIL PROTECTED]> wrote: > In article > <[EMAIL PROTECTED]>, > John Roth <[EMAIL PROTECTED]> wrote: > > > > Does the following patch has a chance of being introduced in the > > > standard python distribution? > > > I certainly hope not! > > I think you're being overly negative here. Antoon went to the trouble to > read the sources and post a diff. At the very least, he deserves a more > polite response. > > But, more than that, I think Antoon's idea has some merit. I understand > that the mantra in unit testing is that the tests should be able to be run > in any order. Still, it's the job of a library package to make it easy to > do things, not to enforce policy. If somebody (for whatever reason) has a > need to run their tests in a certain order, why is it our job to make it > hard for them to do that? > > In fact, unittest.defaultTestLoader *already* sorts the tests into > alphabetical order by their name. So, if somebody wanted to get the tests > run in order, they could just name their tests "test0001", "test0002", etc. > In fact, I've done that in the past when I had some (long forgotten) reason > why I wanted to run a bunch of things in order. Allowing the tests to be > sorted by line number order instead of by name just makes it a little > easier to do the same thing. > > If somebody wants that functionality, and is willing to put in the effort > to write the code to do it, and contribute that back to the community, I > don't see any reason why it shouldn't be considered. It would have to be > done in a way that doesn't change the current behavior (perhaps by shipping > a subclass of TestLoader which users could use instead of the default). > I'm not saying that we *need* to include it, just that it's not such a bad > idea that it deserves responses like "I certainly hope not!" I totally agree. I can't relate to anyone that want to oppose a change that would give more freedom to a programmer. André -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
On May 23, 10:36 am, Antoon Pardon <[EMAIL PROTECTED]> wrote: > Some time ago I asked whether is would be possible that unittest would > perform the test in order of appearence in the file. > > The answers seemed to be negative. Since I really would like this > behaviour I took the trouble of looking throught the source and > I think I found a minor way to get this behaviour. > > Now my questions are: > > Are other people interrested in this behaviour? > Does the following patch has a chance of being introduced in the > standard python distribution? > > *** /usr/lib/python2.5/unittest.py 2008-04-17 16:26:37.0 +0200 > --- unittest.py 2008-05-23 11:19:57.0 +0200 > *** > *** 570,575 > --- 570,577 > """ > def isTestMethod(attrname, testCaseClass=testCaseClass, > prefix=self.testMethodPrefix): > return attrname.startswith(prefix) and > callable(getattr(testCaseClass, attrname)) > + def getlinenr(name): > + return getattr(testCaseClass, > name).im_func.func_code.co_firstlineno > testFnNames = filter(isTestMethod, dir(testCaseClass)) > for baseclass in testCaseClass.__bases__: > for testFnName in self.getTestCaseNames(baseclass): > *** > *** 577,582 > --- 579,586 > testFnNames.append(testFnName) > if self.sortTestMethodsUsing: > testFnNames.sort(self.sortTestMethodsUsing) > + else: > + testFnNames.sort(key=getlinenr) > return testFnNames I second Roy's appreciation with you going to the trouble to post a patch. There is another problem with your code though, it is dependent on the CPython implementation. Currently unittest works *great* with IronPython, which your code wouldn't. Also, like others, I have had wonderful experiences of trying to track down test failures that depend on the order that tests run in. Having interdependencies between tests is a recipe for madness... Michael Foord http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list
need some help in serving static files inside a wsgi apps
Hi, Until now, I was running my own static site with Python, but I'm in need of dynamism. After reading some cgi tutorials, I saw Joe Gregorio's old article "Why so many Python web frameworks?" about wsgi apps [http:// bitworking.org/news/Why_so_many_Python_web_frameworks] and have a question about it. The code he gave works like a charm (I had to make a little change because SQLAlchemy has changed since), but how the hell can I serve static files (css, js, images, etc.) within an wsgi app, ie inside a '/static' directory ?! Sorry if my question is a stupid one, but I cannot find an easy way to do this. Each tutorial I'm reading out there does not talk about them at all. All of my python books didn't mention wsgi either. I know I could use web.py, web2py, Cherrypy, Django, Pylons, etc. but I'm trying to understand basics of web dev. from their roots. thanks in advance for any advice , Kib. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
In article <[EMAIL PROTECTED]>, David <[EMAIL PROTECTED]> wrote: > Hi list. > > What strategies do you use to ensure correctness of new code? > > Specifically, if you've just written 100 new lines of Python code, then: > > 1) How do you test the new code? > 2) How do you ensure that the code will work correctly in the future? There's various philosophies about this (and none of them are specific to Python), but I like a process called Test Driven Development (TDD). In TDD, you invert the order you describe above. First write the test, then write the code to make the tests pass. What I usually do is write the documentation first, then write some tests that assert things the documentation says, then write the code. Python has several testing modules; unittest and doctest come with the system, and there's a couple of other third-party modules that have sprung up. I find unittest works well for me and stick with that. I work in small increments, writing one test at a time, then some code, then another test, then some more code, etc. In fact, I take this to what many people might call an extreme. When I sit down to write a class, the first test I write is one that just instantiates an instance of that class with no arguments. Then a write the stub class: class foo: pass and see that the test works. If I'm feeling really expansive, I'll write a more sophisticated version: class foo: def __init__(self): pass and use that to satisfy my initial test. Then it's just later, rinse, repeat until the class is done, fully documented, and fully tested. > For (1) I thoroughly (manually) test code as I write it, before > checking in to version control. I agree with the idea that it's fully tested before checking it in, but not with the manual testing. In my mind, any test that's not fully automated might as well not exist. -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite import fails sometimes ?
Stef Mientki wrote: I don't know if this matters, but I also use sqlite3 from other than Python programs. You have an instance of sqlite3.dll in P:\Python\DLLs for use with Python, and (I guess) you have another instance of sqlite3.dll somewhere else, for use "from other than Python programs". Are they the same version? If not, this may be the problem. Start up your other application, then try to import sqlite3 from Python. If this is the problem, and you must be able to run both apps simultaneously, you will probably need to update one or the other. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Unhandled exceptions checking
Yosifov Pavel wrote: Does somebody know existent tool for checking unhandled exceptions? Like in Java when method throws exception but in code using this method, try...catch is missed. May be something like PyChecker? I've seen this a number of places. Apparently there are a number of programmers who find exceptions to be a problem to suppressed, rather than an indicator of a deeper bug. Your goal should be to handle anticipatable problems where you can, and reveal the others, not to make sure you cannot raise an exception. Exceptions are valuable in that they reveal "thinko"s, embrace what they tell you, and don't look for mechanical ways to avoid them; test them out. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Why does python not have a mechanism for data hiding?
Hi, first, python is one of my fav languages, and i'll definitely keep developing with it. But, there's 1 one thing what I -really- miss: data hiding. I know member vars are private when you prefix them with 2 underscores, but I hate prefixing my vars, I'd rather add a keyword before it. Python advertises himself as a full OOP language, but why does it miss one of the basic principles of OOP? Will it ever be added to python? Thanks in advance, Lucas -- http://mail.python.org/mailman/listinfo/python-list
Re: C-like assignment expression?
On May 21, 4:38 am, [EMAIL PROTECTED] wrote: > Hello, > > I have an if-elif chain in which I'd like to match a string against > several regular expressions. Also I'd like to use the match groups > within the respective elif... block. The C-like idiom that I would > like to use is this: > > if (match = my_re1.match(line): > # use match > elsif (match = my_re2.match(line)): > # use match > elsif (match = my_re3.match(line)) > # use match > > ...buy this is illegal in python. The other way is to open up an else: > block in each level, do the assignment and then the test. This > unneccessarily leads to deeper and deeper nesting levels which I find > ugly. Just as ugly as first testing against the RE in the elif: clause > and then, if it matches, to re-evaluate the RE to access the match > groups. > > Thanks, > robert Try this. -- Paul class TestValue(object): """Class to support assignment and test in single operation""" def __init__(self,v=None): self.value = v """Add support for quasi-assignment syntax using '<<' in place of '='.""" def __lshift__(self,other): self.value = other return bool(self.value) import re tv = TestValue() integer = re.compile(r"[-+]?\d+") real = re.compile(r"[-+]?\d*\.\d+") word = re.compile(r"\w+") for inputValue in ("123 abc 3.1".split()): if (tv << real.match(inputValue)): print "Real", float(tv.value.group()) elif (tv << integer.match(inputValue)): print "Integer", int(tv.value.group()) elif (tv << word.match(inputValue)): print "Word", tv.value.group() Prints: Integer 123 Word abc Real 3.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
In article <[EMAIL PROTECTED]>, Fuzzyman <[EMAIL PROTECTED]> wrote: > Also, like others, I have had wonderful experiences of trying to track > down test failures that depend on the order that tests run in. Having > interdependencies between tests is a recipe for madness... I agree that tests should not depend on each other, but sometimes it's still useful to have the tests run in a certain order for reporting purposes. If you're doing requirements tracking, it's nice to have the tests execute in the same order as the requirements are listed. It makes interpreting the output easier. Sure, you could give the test cases names like "test_fr17.3a" and write your own getTestCaseNames(), but just putting them into the file in the order you want them to run is easier. And making things easy is what this is all about. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
David <[EMAIL PROTECTED]> writes: > What strategies do you use to ensure correctness of new code? Behaviour Driven Development http://behaviour-driven.org/>. * Start with an automated unit test suite that passes. * Describe, as formally or informally as you like, but *not* in code, the new or altered behaviour that the code should exhibit. * Assert some simple aspect of that behaviour in an automated unit test that asserts one single true/false statement. This forces you to be absolutely specific about the new behaviour you're about to implement, at exactly the point where you need that specification. It also forces you to think about the code from the perspective of an external user of the code, *before* implementing it. This leads over time to much better-designed APIs, without large up-front planning. * Run the entire unit test suite; watch the new test fail with an explanation of why it failed. At this point you know your unit test suite will fail, with a good explanatory message, in any future failure of the code to implement the specified behaviour. * Alter the application in the simplest possible way to make the entire unit test suite pass. Don't be clever, don't optimise anything (yet); be lazy. Do the simplest thing that could possibly work. This ensures you don't have any code that isn't necessary to implement your specified requirements. Since you designed an implemented a test that will use this code first, you should have a much better idea of the simplest code that will satisfy it, and won't have to go down so many wasteful dead-ends. * Run the entire unit test suite. Fix any failing tests. The existing tests in the unit test suite will show any regressions you introduced. You might need to re-evaluate the relevance of old tests as you specify and implement new behaviour. * Only once the entire unit test suite passes again, refactor any code that now exhibits redundancies or inelegancies. This doesn't permit you to change behaviour or API; "refactor" means changing the structure of the code without changing its behaviour. * Run the entire unit test suite. Fix any failing tests. You have now designed, specified, implemented, and tested the new behaviour. Check your code into your VCS with an appropriate message saying what you implemented and why. * Repeat from the top. > Specifically, if you've just written 100 new lines of Python code, > then: > > 1) How do you test the new code? Write the tests first, and make sure you aren't writing so much new code between tests. > 2) How do you ensure that the code will work correctly in the future? Always run your complete automated unit test suite between changes to the code. If possible, arrange for the unit test suite to be run automatically every time you change your working copy of the code and/or tests. That way you only have to look at the output when you want to know what effect you just had on the pass/fail status. Treat any bug as "desired change to the behaviour of the code", and begin by implementing a new unit test that fails because of the bug. Then your unit test suite will catch any regression of the bug. -- \ “In case you haven't noticed, [the USA] are now almost as | `\ feared and hated all over the world as the Nazis were.” | _o__) —Kurt Vonnegut, 2004 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Scipy+SQLite crashes... , was: Re: SQLite import fails sometimes ?
John Machin wrote: Stef Mientki wrote: I don't know if this matters, but I also use sqlite3 from other than Python programs. You have an instance of sqlite3.dll in P:\Python\DLLs for use with Python, and (I guess) you have another instance of sqlite3.dll somewhere else, for use "from other than Python programs". Are they the same version? If not, this may be the problem. Start up your other application, then try to import sqlite3 from Python. If this is the problem, and you must be able to run both apps simultaneously, you will probably need to update one or the other. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list thanks John, I think I hit the problem, ;-) but I don't have a solution yet :-( After creating the simplest program that did work : import sqlite3 I started adding every import statement used in my program, until the program crashed, and here is the simplest program that crashes: from scipy import * import sqlite3 Traceback (most recent call last): File "D:\Data_Python\P24_PyLab_Works\module1.py", line 2, in import sqlite3 File "P:\Python\lib\sqlite3\__init__.py", line 24, in from dbapi2 import * File "P:\Python\lib\sqlite3\dbapi2.py", line 27, in from _sqlite3 import * ImportError: DLL load failed: Invalid access to memory location. Any solutions ? (btw I need to do the *-import, because I create an easy user environment to do math and physics) thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: C-like assignment expression?
This version is a bit better, since it follows the convention that '<<' should return self. class TestValue(object): """Class to support assignment and test in single operation""" def __init__(self,v=None): self.value = v """Add support for quasi-assignment syntax using '<<' in place of '='.""" def __lshift__(self,other): self.value = other return self def __bool__(self): return bool(self.value) __nonzero__ = __bool__ -- Paul -- http://mail.python.org/mailman/listinfo/python-list
About events
As i said before I work with the WX library on a windows XP operation system. Now i wont to create an application which ran at the background and wait till the user double click on a text word OF any other python or none python application which ran on the desktop, and when this event append i wont my application to pup up a translation of this word. I figured that I need to understand how can i select text automaticlly and copy it to the clipbord for doing that if someone know how to do it, or know whether this WX library capable of doing it (and if not which library can...) i would be very thankful Have a nice day -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Sh4wn <[EMAIL PROTECTED]> writes: > first, python is one of my fav languages, and i'll definitely keep > developing with it. But, there's 1 one thing what I -really- miss: > data hiding. I know member vars are private when you prefix them with > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > before it. >From whom are you trying to hide your attributes? In Python, the philosophy "we're all consenting adults here" applies. You shouldn't pretend to know, at the time you write it, all the uses to which your code will be put. Barriers such as enforced "private" attributes will only cause resentment when people, despite your anticipations, *need* to access them and are then forced to hack their way around them. If you want the users of your code to know that an attribute should not be used as a public API for the code, use the convention of naming the attribute with a single leading underscore. This is a string signal that the attribute is part of the implementation, not the interface. The reader is then on notice that they should not rely on that attribute; but they are not *prohibited* from using it if necessary to their ends. > Python advertises himself as a full OOP language, but why does it > miss one of the basic principles of OOP? Who taught you that enforced restrictions on attribute access was a "basic principle" of OO? Perhaps you're confusing the "encapsulation" and "abstraction" principles for enforced access restrictions; they're not. > Will it ever be added to python? I hope not. -- \"Why was I with her? She reminds me of you. In fact, she | `\ reminds me more of you than you do!" -- Groucho Marx | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
On May 24, 6:12 am, Johannes Bauer <[EMAIL PROTECTED]> wrote: > Carl Banks schrieb: > > > p = myfunction() > > if p: > > print p > > > (I recommend doing it this way in C, too.) > > This is okay for if-clauses, but sucks for while-loops: > > while (fgets(buf, sizeof(buf), f)) { > printf("%s\n", buf); > > } > > is much shorter than > > char *tmp; > tmp = fgets(buf, sizeof(buf), f); > while (tmp) { > printf("%s\n", buf); > tmp = fgets(buf, sizeof(buf), f); > > } > > For the case where you want to do this in an elif-clause, look for the > > recent thread "C-like assignment expression?" which list some > > workarounds. Or just Google this newsgroup for "assignment > > expression". It's one of few minor irritating things in Python > > syntax. > > Alright, I will. Thanks. > > Regards, > Johannes > > -- > "Wer etwas kritisiert muss es noch lange nicht selber besser können. Es > reicht zu wissen, daß andere es besser können und andere es auch > besser machen um einen Vergleich zu bringen." - Wolfgang Gerber > in de.sci.electronics <[EMAIL PROTECTED]> I posted this to the other thread, but I'm afraid it might get buried over there. See if this works for you. class TestValue(object): """Class to support assignment and test in single operation""" def __init__(self,v=None): self.value = v """Add support for quasi-assignment syntax using '<<' in place of '='.""" def __lshift__(self,other): self.value = other return self def __bool__(self): return bool(self.value) __nonzero__ = __bool__ import re tv = TestValue() integer = re.compile(r"[-+]?\d+") real = re.compile(r"[-+]?\d*\.\d+") word = re.compile(r"\w+") for inputValue in ("123 abc -3.1".split()): if (tv << real.match(inputValue)): print "Real", float(tv.value.group()) elif (tv << integer.match(inputValue)): print "Integer", int(tv.value.group()) elif (tv << word.match(inputValue)): print "Word", tv.value.group() Prints: Integer 123 Word abc Real -3.1 In your examples, this could look like: tv = TestValue() while (tv << fgets(buf, sizeof(buf), f)) { printf("%s\n", tv.value); or: if (tv << myfunction()): What do you think? Is '<<' close enough to '=' for you? -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Ben Finney <[EMAIL PROTECTED]> writes: > If you want the users of your code to know that an attribute should > not be used as a public API for the code, use the convention of > naming the attribute with a single leading underscore. This is a > string signal that the attribute is part of the implementation, not > the interface. Quite apart from whether it's a string signal, I meant to write that it's a *strong* signal. -- \"Some people, when confronted with a problem, think 'I know, | `\ I'll use regular expressions'. Now they have two problems." | _o__) —Jamie Zawinski, in alt.religion.emacs | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
raising an exception when multiple inheritance involves same base
Hello, I have a class factory that supports single inheritance but it is an error if the base appears twice. e.g class Foo(hclass(h.Vector), hclass(h.List)): should raise an exception since h.Vector and h.List are really the same extension class, HocObject. So far I have only been able to do this by iterating over __mro__ during creation of an object as in: def hclass(c): class hc(hoc.HocObject): def __new__(cls, *args, **kwds): m = False for x in cls.__mro__: if (type(x) == type(hc)): if m == True: raise HocError, 'Multiple inheritance...' m = True kwds.update({'hocbase':cls.htype}) return hoc.HocObject.__new__(cls, *args, **kwds) setattr(hc, 'htype', c) return hc Is there a way to do the test earlier (e.g during creation of the Foo class when hclass is called the second time instead of during creation of a Foo object). Just before the return hc, print hc.__mro__ yields for the second call: (, , ) wheras in the __new__, print cls.__mro__ yields: (, , , , ) Thanks, Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
> if python is such a good programming/scripting language, why can't they > build a faster interpreter/compiler engine? and beat php and zend. > to the python team, rebuild your interpreter! while this is just a boring troll.. it does bring me to a more interesting point... it would be cool if the interpreter were multi-threaded to make better use of smp systems. While you can do threading, if you really want to drive more than one cpu some forking is in order. -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
On May 24, 2:44 pm, Roy Smith <[EMAIL PROTECTED]> wrote: > In article > <[EMAIL PROTECTED]>, > > Fuzzyman <[EMAIL PROTECTED]> wrote: > > Also, like others, I have had wonderful experiences of trying to track > > down test failures that depend on the order that tests run in. Having > > interdependencies between tests is a recipe for madness... > > I agree that tests should not depend on each other, but sometimes it's > still useful to have the tests run in a certain order for reporting > purposes. > > If you're doing requirements tracking, it's nice to have the tests execute > in the same order as the requirements are listed. It makes interpreting > the output easier. Sure, you could give the test cases names like > "test_fr17.3a" and write your own getTestCaseNames(), but just putting them > into the file in the order you want them to run is easier. And making > things easy is what this is all about. Whilst I understand your point, I think the danger is that you end up with hidden dependencies on the test order - which you're not aware of and that the tests never expose. Certainly layout your tests in a logical order within the file, but I think you risk potential problems by controlling the order they are run in. Other frameworks specifically provide test order randomizers for this very reason. A worthwhile question for the OP - your patch seems fairly simple. Is it easy for you to extend unittest for your own testing needs by subclassing? Unittest should definitely be easy for people who *want* this to add it to their own testing environment. All the best, Michael Foord http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On May 24, 2:58 pm, Ben Finney <[EMAIL PROTECTED]> wrote: > Sh4wn <[EMAIL PROTECTED]> writes: > > first, python is one of my fav languages, and i'll definitely keep > > developing with it. But, there's 1 one thing what I -really- miss: > > data hiding. I know member vars are private when you prefix them with > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > before it. > > From whom are you trying to hide your attributes? Actually, 'data hiding', although vastly overused by the static crowd can be a reasonable thing to want. For example, at Resolver Systems we expose the spreadsheet object model to our users. It hasa public, documented, API - plus a host of undocumented internally used methods. We would really *much* rather hide these, because anything our customers start using (whether documented or not) we will probably have to continue supporting and maintaining. The 'we told you not to use that' approach, when applied to paying customers doesn't really work... all they see is that you broke their spreadsheet code by changing your API. You can make members truly private by proxying, but it is a bit ungainly. Michael Foord http://www.ironpythoninaction.com/ > > In Python, the philosophy "we're all consenting adults here" applies. > You shouldn't pretend to know, at the time you write it, all the uses > to which your code will be put. Barriers such as enforced "private" > attributes will only cause resentment when people, despite your > anticipations, *need* to access them and are then forced to hack their > way around them. > > If you want the users of your code to know that an attribute should > not be used as a public API for the code, use the convention of naming > the attribute with a single leading underscore. This is a string > signal that the attribute is part of the implementation, not the > interface. The reader is then on notice that they should not rely on > that attribute; but they are not *prohibited* from using it if > necessary to their ends. > > > Python advertises himself as a full OOP language, but why does it > > miss one of the basic principles of OOP? > > Who taught you that enforced restrictions on attribute access was a > "basic principle" of OO? > > Perhaps you're confusing the "encapsulation" and "abstraction" > principles for enforced access restrictions; they're not. > > > Will it ever be added to python? > > I hope not. > > -- > \"Why was I with her? She reminds me of you. In fact, she | > `\ reminds me more of you than you do!" -- Groucho Marx | > _o__) | > Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: need some help in serving static files inside a wsgi apps
Tool69 schrieb: Hi, Until now, I was running my own static site with Python, but I'm in need of dynamism. After reading some cgi tutorials, I saw Joe Gregorio's old article "Why so many Python web frameworks?" about wsgi apps [http:// bitworking.org/news/Why_so_many_Python_web_frameworks] and have a question about it. The code he gave works like a charm (I had to make a little change because SQLAlchemy has changed since), but how the hell can I serve static files (css, js, images, etc.) within an wsgi app, ie inside a '/static' directory ?! There is a wsgi-app out there that is called "static". Use that. And it's the first hit on google "wsgi static"... :) http://lukearno.com/projects/static/ Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
David wrote: Specifically, if you've just written 100 new lines of Python code, then: 1) How do you test the new code? 2) How do you ensure that the code will work correctly in the future? Short version: For (1) I thoroughly (manually) test code as I write it, before checking in to version control. For (2) I code defensively. ... As for point 1 (how do you test the new code?): I like the idea of automated unit tests. However, in practice I find they take a long time to write and test, especially if you want to have good coverage (not just lines, but also possible logic branches). This is why I have reluctantly come to accept the XP people's view: if you you write the tests _as_ you develop (that is as far as I go w/o re-enforcement; they would have you write them _before_), you will have a body of tests that work to demonstrate the correctness or deficiencies of your code based on what it _should_ do. If you write tests after you've written the code, you will write tests that are based on what your code _actually_does_. You don't want the latter; the tests are brittle. The tests don't match needs, rather they match implementations. Therefore you'll need to discard more tests at every local rewrite. 1) Add "raise 'UNTESTED'" lines to the top of every function String exceptions are deprecated. Just raise UNTESTED (and let the access to undefined global error be the issue). .. 11) Cause those sections of code to be run also (sometimes I need to temporarily set vars to impossible values inside the script, since the logic will never run otherwise) And here is one of my biggest problem with unit tests. How do you unit test code which almost never runs? The only easy way I can think of is for the code to have 'if or lines'. I know I'm meant to make 'fake' testing classes which return erroneous values, and then pass these objects to the code being tested. But this can take a long time and even then isn't guaranteed to reach all your error-handling code. Ah, but now you tests are "brittle"; they only work for the code you have now. If you want to make sure you have code coverage with your test, the XP way is: Write a test for behavior you need. Watch it fail. Fix the code so all tests pass. Lather, rinse, repeat. You should not have untested code, because there was no test that made you write it. If you want to do code coverage, find a code coverage tool and count your code while runnign your unit tests. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
>I can't relate to anyone that want to oppose a change that would give >more freedom to a programmer. While in general I agree with this.. I think in the case of python part of it's base philosophy seems to be a tendency to encourage a single way of doing things, and create a path of least resistance to the "best" way. "best" in this case being one or a handful of peoples opinion. I'm really ok with this, personally. I think it's working well. So.. I'll post this because I'm sure at least one person hasn't seen it: >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! -- http://mail.python.org/mailman/listinfo/python-list
Re: need some help in serving static files inside a wsgi apps
Diez B. Roggisch a écrit : Tool69 schrieb: Hi, Until now, I was running my own static site with Python, but I'm in need of dynamism. After reading some cgi tutorials, I saw Joe Gregorio's old article "Why so many Python web frameworks?" about wsgi apps [http:// bitworking.org/news/Why_so_many_Python_web_frameworks] and have a question about it. The code he gave works like a charm (I had to make a little change because SQLAlchemy has changed since), but how the hell can I serve static files (css, js, images, etc.) within an wsgi app, ie inside a '/static' directory ?! There is a wsgi-app out there that is called "static". Use that. And it's the first hit on google "wsgi static"... :) http://lukearno.com/projects/static/ Diez Hi Diez, and thanks for yout help. In fact I already found it but never managed to get it work because the static doc says : from wsgiref.simple_server import make_server import static make_server('localhost', , static.Cling('/var/www')).serve_forever() and inside J.Gregorio's tutorial it is: from wsgiref.simple_server import WSGIServer, WSGIRequestHandler httpd = WSGIServer(('localhost', 8080), WSGIRequestHandler) httpd.set_app(urls.urls) It does not use 'make_server()' so how can I adapt it ? I finally managed to work with static files with a little hack, but it's ugly because I'm reading each static file per request. Kib. -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
In article <[EMAIL PROTECTED]>, Fuzzyman <[EMAIL PROTECTED]> wrote: > Whilst I understand your point, I think the danger is that you end up > with hidden dependencies on the test order - which you're not aware of > and that the tests never expose. Well, yes. But, this is no worse than the current situation, where the tests are run in alphabetical order by default. You could still have hidden dependencies and not realize it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
In article <[EMAIL PROTECTED]>, Fuzzyman <[EMAIL PROTECTED]> wrote: > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke their > spreadsheet code by changing your API. I hear what you're saying, friend, and I feel your pain! Life gets so much more complicated when you've got paying customers. It's especially complicated when your customers have a market cap an order of magnitude greater than your own :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: raising an exception when multiple inheritance involves same base
Michael Hines <[EMAIL PROTECTED]> writes: > Hello, > I have a class factory that supports single inheritance but it is > an error if the base appears twice. e.g > class Foo(hclass(h.Vector), hclass(h.List)): > should raise an exception since h.Vector and h.List are really the same > extension class, HocObject. > > So far I have only been able to do this by iterating over __mro__ during > creation of an object as in: > > def hclass(c): > class hc(hoc.HocObject): > def __new__(cls, *args, **kwds): > m = False > for x in cls.__mro__: > if (type(x) == type(hc)): > if m == True: > raise HocError, 'Multiple inheritance...' > m = True > kwds.update({'hocbase':cls.htype}) > return hoc.HocObject.__new__(cls, *args, **kwds) > setattr(hc, 'htype', c) > return hc > > Is there a way to do the test earlier (e.g during creation of the Foo > class when hclass is called the second time > instead of during creation of a Foo object). Yes, by giving hoc.HocObject a custom metaclass: class MetaHocObject(type): def __new__(cls, name, bases, attrs): if len(bases) > 1: raise Exception("Only single inheritance allowed") return type.__new__(cls, name, bases, attrs) class HocObject(object): __metaclass__ = MetaHocObject That'll forbid descendants of MetaHocObject having several bases: >> class A(HocObject): pass ... >>> class B(HocObject): pass ... >>> class C(A, B): pass ... Traceback (most recent call last): File "", line 1, in File "", line 4, in __new__ Exception: Only single inheritance allowed >>> HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
> I work in small increments, writing one test at a time, then some code, > then another test, then some more code, etc. In fact, I take this to what > many people might call an extreme. Thanks for the replies. I've read about the TDD (and similar) approaches. Maybe I need to try it and get used to it, but there are a few things I don't like about it on a gut level. I'll try to enumerate my concerns here. Problem 1: You can only code against tests Basically, with TDD you write the tests first, then the code which passes/fails the tests as appropriate. However, as you're writing the code you will also think of a lot of corner cases you should also handle. The natural way to do this is to add them to the code first. But with TDD you have to first write a test for the corner case, even if setting up test code for it is very complicated. So, you have these options: - Take as much time as needed to put a complicated test case in place. - Don't add corner case to your code because you can't (don't have time to) write a test for it. - Add the corner case handling to the code first, and try to add a test later if you have time for it. Problem 2: Slows down prototyping In order to get a new system working, it's nice to be able to throw together a set of modules quickly, and if that doesn't work, scrap it and try something else. There's a rule (forget where) that your first system will always be a prototype, regardless of intent. With TDD, you have to first write the tests for the first version. Then when that first version doesn't work out, you end up scrapping the tests and the code. The time spent writing the tests was wasted. Problem 3: Slows down development in general Having to write tests for all code takes time. Instead of eg: 10 hours coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours writing all the tests, and 10 on the code. Problem 4: Can make refactoring difficult. If you have very complete & detailed tests for your project, but one day you need to change the logic fundamentally (maybe change it from single-threaded to multi-threaded, or from running on 1 server to distributed), then you need to do a large amount of test refactoring also. The more tests you have (usually a good thing), the longer it will take to update all the tests, write new ones, etc. It's worse if you have to do all this first before you can start updating the code. Problem 5: Tests are more important than code You need to justify the extra time spent on writing test code. Tests are nice, and good to have for code maintainability, but they aren't an essential feature (unless you're writing critical software for life support, etc). Clients, deadlines, etc require actual software, not tests for software (that couldn't be completed on time because you spent too much time writing tests first ;-)). Problems like the above sum up why I'm not comfortable with the idea of TDD. I think that automated tests can be very valuable for maintainability, making sure that you or other devs don't break something down the line. But these benefits must be worth the time (and general inconvenience) spent on adding/maintaining the tests. If I did start doing some kind of TDD, it would be more of the 'smoke test' variety. Call all of the functions with various parameters, test some common scenarios, all the 'low hanging fruit'. But don't spend a lot of time trying to test all possible scenarios and corner cases, 100% coverage, etc, unless I have enough time for it. I'm going to read more on the subject (thanks to Ben for the link). Maybe I have some misconceptions. David. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Fuzzyman <[EMAIL PROTECTED]> writes: > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke > their spreadsheet code by changing your API. And the customer point of view is quite reasonable - they have a job to do, and a limited timeframe; sometimes accessing privates directly is much better than waiting for updates from vendor. Bad designs (as far as choosing publics goes) happen. Even if their softare breaks on upgrade, you can quite clearly point out that they used an internal api - and they will keep on using the old version until they solve the problem. Everybody wins. Perhaps a lint-like validation tool would be optimal for this problem... -- http://mail.python.org/mailman/listinfo/python-list
ero magazines
http://ero-mag.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
On 2008-05-23, Johannes Bauer <[EMAIL PROTECTED]> wrote: > I'm just starting with Python and am extremely unexperienced with it so > far. Having a strong C/C++ background, I wish to do something like > > if (q = getchar()) { > printf("%d\n", q); > } > > or translated to Python: > > if (p = myfunction()): > print p > > However, this "assignment and comparison" is not working. What's the > "Python way" of doing this kind of thing? p = myfunction() if p: print p In Python, assignment isn't an operator, it's a statement. The condition in an if/while has to be an expression, not a statement. -- Grant -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
In article <[EMAIL PROTECTED]>, David <[EMAIL PROTECTED]> wrote: >> I work in small increments, writing one test at a time, then some code, >> then another test, then some more code, etc. In fact, I take this to what >> many people might call an extreme. > >Thanks for the replies. > >I've read about the TDD (and similar) approaches. Maybe I need to try >it and get used to it, but there are a few things I don't like about >it on a gut level. I'll try to enumerate my concerns here. > >Problem 1: You can only code against tests > >Basically, with TDD you write the tests first, then the code which >passes/fails the tests as appropriate. However, as you're writing the >code you will also think of a lot of corner cases you should also >handle. The natural way to do this is to add them to the code first. >But with TDD you have to first write a test for the corner case, even >if setting up test code for it is very complicated. So, you have these >options: > >- Take as much time as needed to put a complicated test case in place. >- Don't add corner case to your code because you can't (don't have >time to) write a test for it. >- Add the corner case handling to the code first, and try to add a >test later if you have time for it. As you come up with the corner case, write a test for it and leave the implementation for later. The hard part of coding is always defining your problem. Once it is defined (by a test) the solution is just a matter of tidy work. >Problem 2: Slows down prototyping > >In order to get a new system working, it's nice to be able to throw >together a set of modules quickly, and if that doesn't work, scrap it >and try something else. There's a rule (forget where) that your first >system will always be a prototype, regardless of intent. > >With TDD, you have to first write the tests for the first version. >Then when that first version doesn't work out, you end up scrapping >the tests and the code. The time spent writing the tests was wasted. > Agreed. There is no good way of reusing your prototype code in TDD. You end up having to throw your propotype away in order to have a proper tested implementation in the end. Takes more time up front, but less time over the lifecycle of the program you are building. >Problem 3: Slows down development in general > >Having to write tests for all code takes time. Instead of eg: 10 hours >coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours >writing all the tests, and 10 on the code. This is incorrect. It speeds up development in general. The debugging phase of development becomes much shorter because the bugs are fewer and the ones you have a much shallower. There are so many tests that reduce the scope in which you have to search for the bug that it usually becomes trivial to find. I have direct experience from this, getting my company to change to TDD about 10 months ago. Productivity has improved enormously. I'd say that we have cut between 25 and 50% in development time. >Problem 4: Can make refactoring difficult. > >If you have very complete & detailed tests for your project, but one >day you need to change the logic fundamentally (maybe change it from >single-threaded to multi-threaded, or from running on 1 server to >distributed), then you need to do a large amount of test refactoring >also. The more tests you have (usually a good thing), the longer it >will take to update all the tests, write new ones, etc. It's worse if >you have to do all this first before you can start updating the code. No, this is a total misunderstanding. It makes refactoring much easier. It takes a bit of time to refactor the affected tests for the module, but you gain so much by having tests that show that your refactoring is not breaking code that should be unaffected that it saves the extra time spent many times over. Introducing bugs because you missed some aspect in a refactoring is one of the most common problems in non-TDD code and it is a really nasty quality concern. > >Problem 5: Tests are more important than code > >You need to justify the extra time spent on writing test code. Tests >are nice, and good to have for code maintainability, but they aren't >an essential feature (unless you're writing critical software for life >support, etc). Clients, deadlines, etc require actual software, not >tests for software (that couldn't be completed on time because you >spent too much time writing tests first ;-)). > The tests are as important as the code. As a customer, I don't think I'd buy software today unless I know that it has been built using TDD. Certainly I am ahead of the curve in this, but it won't be long before this will be required by skilled organisations buying software and sooner or later the rest of the world will follow. Getting into a TDD mindset is hard work, but those who succeed produce better software with less effort. Jacob Hallén -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial download with ftplib and retrbinary
On May 24, 11:53 am, [EMAIL PROTECTED] wrote: > I am breaking/interrupting my connection with the ftp server at > present when doing a partial download of a file. I have a callback > with retrbinary that raises an exception and ends the download. The > problem is that the server is not notified and hangs. I cannot send > any further commands and need to relogin to download further. Is there > a way to still continue downloading without having to login again. > > My retrbinary function is: > > ftp.retrbinary('RETR '+file, handleDownload,1,bound[0]) > > where bound[0] is an integer specifying the start byte of the > download. > > My callback is: > > def handleDownload(block): > global count,localfile,number > localfile.write(block) > if count==number: > raise(Exception) > count=count+1 > > where number specifies the number of bytes to download. > > Help would be gratefully received. Have you tried ftp.abort()? The docs say "Abort a file transfer that is in progress. Using this does not always work, but it's worth a try.". I'd also suggest that you download more than 1 byte at a time, perhaps 1024 (fewer if you're on dial-up). -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On May 24, 4:56 pm, [EMAIL PROTECTED] (Ville M. Vainio) wrote: > Fuzzyman <[EMAIL PROTECTED]> writes: > > The 'we told you not to use that' approach, when applied to paying > > customers doesn't really work... all they see is that you broke > > their spreadsheet code by changing your API. > > And the customer point of view is quite reasonable - they have a job > to do, and a limited timeframe; sometimes accessing privates directly > is much better than waiting for updates from vendor. Bad designs (as > far as choosing publics goes) happen. They will use whatever they find, whether it is the best way to achieve a goal or not. Once they start using it they will expect us to maintain it - and us telling them it wasn't intended to be used by them in the first place won't cut it. > > Even if their softare breaks on upgrade, you can quite clearly point > out that they used an internal api - and they will keep on using the > old version until they solve the problem. Everybody wins. > Not if they are waiting for a fix or new feature in the upgrade - and we can't refactor because they are relying on APIs that we want to remove. We very much lose. > Perhaps a lint-like validation tool would be optimal for this > problem... So we can refuse to execute their code if they use private APIs? Proxying so that we can really hide our internal APIs is a better solution. This hasn't happened to us yet (our application has only been in commercial use since January), but it is one of the reasons that Microsoft's COM APIs grew so wide and wild, and caused them very real problems in trying to improve them. We are keen to avoid the same situation. Michael Foord http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Calling tests in liner number order
On May 24, 3:57 pm, Roy Smith <[EMAIL PROTECTED]> wrote: > In article > <[EMAIL PROTECTED]>, > > Fuzzyman <[EMAIL PROTECTED]> wrote: > > Whilst I understand your point, I think the danger is that you end up > > with hidden dependencies on the test order - which you're not aware of > > and that the tests never expose. > > Well, yes. But, this is no worse than the current situation, where the > tests are run in alphabetical order by default. You could still have > hidden dependencies and not realize it. Fair point. I'd still be -1 on the addition of this patch, but +1 on the addition of a randomizer. Michael Foord http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Ben Finney: >In Python, the philosophy "we're all consenting adults here" applies.< Michael Foord: > They will use whatever they find, whether it is the best way to > achieve a goal or not. Once they start using it they will expect us to > maintain it - and us telling them it wasn't intended to be used by > them in the first place won't cut it. So they will use the methods with one or two underscores too. And imply that you want to document them too. They don't seem adult enough, then ;-) Internal API hiding seems quite less useful if you don't need to let customers manage your code. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: need some help in serving static files inside a wsgi apps
kib schrieb: Diez B. Roggisch a écrit : Tool69 schrieb: Hi, Until now, I was running my own static site with Python, but I'm in need of dynamism. After reading some cgi tutorials, I saw Joe Gregorio's old article "Why so many Python web frameworks?" about wsgi apps [http:// bitworking.org/news/Why_so_many_Python_web_frameworks] and have a question about it. The code he gave works like a charm (I had to make a little change because SQLAlchemy has changed since), but how the hell can I serve static files (css, js, images, etc.) within an wsgi app, ie inside a '/static' directory ?! There is a wsgi-app out there that is called "static". Use that. And it's the first hit on google "wsgi static"... :) http://lukearno.com/projects/static/ Diez Hi Diez, and thanks for yout help. In fact I already found it but never managed to get it work because the static doc says : from wsgiref.simple_server import make_server import static make_server('localhost', , static.Cling('/var/www')).serve_forever() and inside J.Gregorio's tutorial it is: from wsgiref.simple_server import WSGIServer, WSGIRequestHandler httpd = WSGIServer(('localhost', 8080), WSGIRequestHandler) httpd.set_app(urls.urls) It does not use 'make_server()' so how can I adapt it ? static.Cling is a wsgi-app. The other code just makes a specific wsgi-implementation based server out of it. I finally managed to work with static files with a little hack, but it's ugly because I'm reading each static file per request. How else should that work? Apache does that the same way. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
David <[EMAIL PROTECTED]> wrote: > Problem 2: Slows down prototyping > > In order to get a new system working, it's nice to be able to throw > together a set of modules quickly, and if that doesn't work, scrap it > and try something else. There's a rule (forget where) that your first > system will always be a prototype, regardless of intent. That's fine. It's alright to prototype without tests. The only rule is that you cannot then use any of that code in production. > Problem 3: Slows down development in general > > Having to write tests for all code takes time. Instead of eg: 10 hours > coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours > writing all the tests, and 10 on the code. > You are either a very slow coder or a very poor tester: there should be a lot more than 1/2 hour testing for 10 hours coding. I would say the comparison might be 10 hours coding, 10 hours testing, then about a week tracking down the bugs which escaped testing and got out to the customers. With proper unit tests you will reduce all 3 of these numbers but especially the last one. Any bug which gets away from the programmer and is only caught further downstream costs vastly more than bugs caught during development, and not just for the programmer but everyone else who affected. You seem to think that people are suggesting you write all the tests up front: what you should be doing is interleaving design+testing+coding all together. That makes it impossible to account for test time separately as the test time is tightly mixed with other coding, what you can be sure though is that after an initial slowdown while you get used to the process your overall productivity will be higher. The first time you make a change to some code and a test which is apparently completely unrelated to the change you made breaks is the point when you realise that you have just saved yourself hours of debugging when that bug would have surfaced weeks later. > Clients, deadlines, etc require actual software, not > tests for software (that couldn't be completed on time because you > spent too much time writing tests first ;-)). Clients generally require *working* software. Unfortunately it is all too easy to ship something broken because then you can claim you completed the coding on time and any slippage gets lost in the next 5 years of maintenance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On May 24, 6:18 pm, [EMAIL PROTECTED] wrote: > Ben Finney: > > >In Python, the philosophy "we're all consenting adults here" applies.< > > Michael Foord: > > > They will use whatever they find, whether it is the best way to > > achieve a goal or not. Once they start using it they will expect us to > > maintain it - and us telling them it wasn't intended to be used by > > them in the first place won't cut it. > > So they will use the methods with one or two underscores too. And > imply that you want to document them too. > They don't seem adult enough, then ;-) Great! We'll just tell them that... Michael > Internal API hiding seems quite less useful if you don't need to let > customers manage your code. > > Bye, > bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On 24 mei, 15:58, Ben Finney <[EMAIL PROTECTED]> wrote: > Sh4wn <[EMAIL PROTECTED]> writes: > > first, python is one of my fav languages, and i'll definitely keep > > developing with it. But, there's 1 one thing what I -really- miss: > > data hiding. I know member vars are private when you prefix them with > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > before it. > > From whom are you trying to hide your attributes? > > In Python, the philosophy "we're all consenting adults here" applies. > You shouldn't pretend to know, at the time you write it, all the uses > to which your code will be put. Barriers such as enforced "private" > attributes will only cause resentment when people, despite your > anticipations, *need* to access them and are then forced to hack their > way around them. > > If you want the users of your code to know that an attribute should > not be used as a public API for the code, use the convention of naming > the attribute with a single leading underscore. This is a string > signal that the attribute is part of the implementation, not the > interface. The reader is then on notice that they should not rely on > that attribute; but they are not *prohibited* from using it if > necessary to their ends. > > > Python advertises himself as a full OOP language, but why does it > > miss one of the basic principles of OOP? > > Who taught you that enforced restrictions on attribute access was a > "basic principle" of OO? > > Perhaps you're confusing the "encapsulation" and "abstraction" > principles for enforced access restrictions; they're not. > > > Will it ever be added to python? > > I hope not. > > -- > \ "Why was I with her? She reminds me of you. In fact, she | > `\ reminds me more of you than you do!" -- Groucho Marx | > _o__) | > Ben Finney Well for me, it the ideal way to make sure it contains so 'wrong' data. You can create getter/setters, and in some cases only a getter and validate the value given by the user. Then you'll not have to worry about the data in the rest of your class, which makes life a lot easier IMO. -- http://mail.python.org/mailman/listinfo/python-list
Re: csv iterator question
Thanks, Ethan. that was a great solution. i just tested it. On Fri, May 23, 2008 at 7:08 PM, Ethan Furman <[EMAIL PROTECTED]> wrote: > davidj411 wrote: > > When you save an open file to a variable, you can re-use that variable >> for membership checking. >> it does not seem to be that way with the csv.reader function, even >> when set to a variable name. >> >> what is the best way to store the open CSV file in memory or do i need >> to open the file each time? >> >> example of open method on file object: >> fhandle=open(filename).readelines() >> >> > >>> fhandle = open('c:/temp/08-02024.csv').readlines() > >>> type(fhandle) > > >>> len(fhandle) > 381 > > fhandle is a list containing the contents of the file, not a file handle -- > that's why you can easily re-use it. > > example of csv.reader method: >> reader = csv.reader(open(csvfilename)) >> >> > Try this instead: > >>>reader = csv.reader(open('c:/temp/08-02024.csv')) > >>> contents = [line for line in reader] > >>> type(contents) > > >>> len(contents) > 381 > > You still get a list that you can easily use, that has gone through the csv > routines. > > Hope this helps. > -- > Ethan > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Relationship between GUI and logic?
David C. Ullrich <[EMAIL PROTECTED]> wrote: > Matthew Woodcraft <[EMAIL PROTECTED]> wrote: >> For example, if you were writing the 'logic' for a chess program you >> might choose a way of modelling the board that can't represent a >> position with more than one black king. And then when you got round >> to doing the GUI you might find out that your users would like to be >> able to have this temporarily when setting up a position. > What you say may be true, but this doesn't seem to me like a good > example. Not that I see _why_ the player would want to have two kings > temporarily, but if so I wouldn't have the view report this state to > the model, I'd have the view wait until the player had decided on the > final configuration betore saying anything to the model. The model > should only deal with legal positions. Then you end up implementing a second model of the board state in the UI layer. And if it turns out that you want to support things like 'save current position' and 'clone current position to a new window' during setup, you might well find yourself putting so much logic in the UI layer that some of what you already wrote in the 'logic' layer ends up unused. As for why you might want illegal positions during setup, imagine a UI where you can click on a square repeatedly and it cycles through the possible pieces (dunno whether this would be good in practice, but I do know that guessing whether a UI is good without trying it is rather unreliable). -M- -- http://mail.python.org/mailman/listinfo/python-list
for some reason the actual tries figure is not right
can someone explain why the tries displays the wrong number thanks orginally i started off with tries = 0 but it was off by 2 # Word Jumble # # The computer picks a random word # The player has to guess the original word can give hint import random tries = 1 # create a sequence of words to choose from word = ("python", "jumble", "xylophone", "difficult", "answer") # pick one word randomly from the sequence word = random.choice(word) # create a variable to use later to see if the guess is correct correct = word # start the game print \ """ Welcome to Word Jumble! (Press the enter key at the prompt to quit.) """ if word == "python": hint = 'snake' if word == "jumble": hint = 'mess' if word == "difficult": hint = 'hard' if word == "answer": hint = 'correct' if word == "xylophone": hint = 'music' guess = raw_input("\nYour guess: ") guess = guess.lower() while (guess != correct) and (guess != ""): print "Sorry, that's not it." + hint guess = raw_input("Your guess: ") guess = guess.lower() if guess != correct: print hint tries += 1 if guess == correct: print "That's it! You guessed it!\n" print "Thanks for playing." print tries raw_input("\n\nPress the enter key to exit.") -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
Hi again list. > > As you come up with the corner case, write a test for it and leave the > implementation > for later. The hard part of coding is always defining your problem. Once it is > defined (by a test) the solution is just a matter of tidy work. > Is it considered to be cheating if you make a test case which always fails with a "TODO: Make a proper test case" message? While it is possible to describe all problems in docs, it can be very hard to write actual test code. For example: sanity tests. Functions can have tests for situations that can never occur, or are very hard to reproduce. How do you unit test for those? A few examples off the top of my head: * Code which checks for hardware defects (pentium floating point, memory or disk errors, etc). * Code that checks that a file is less than 1 TB large (but you only have 320 GB harddrives in your testing environment). * Code which checks if the machine was rebooted over a year ago. And so on. These I would manually test by temporarily changing variables in the code, then changing them back. To unit test these you would need to write mock functions and arrange for the tested code to call them instead of the python built-ins. Also, there are places where mock objects can't be used that easily. eg 1: A complicated function, which needs to check the consistency of it's local variables at various points. It *is* possible to unit test those consistency checks, but you may have to do a lot of re-organization to enable unit testing. In other cases it might not be appropriate to unit test, because it makes your tests brittle (as mentioned by another poster). eg: You call function MyFunc with argument X, and expect to get result Y. MyFunc calls __private_func1, and __private_func2. You can check in your unit test that MyFunc returns result Y, but you shouldn't check __private_func1 and __private_func2 directly, even if they really should be tested (maybe they sometimes have unwanted side effects unrelated to MyFunc's return value). eg: Resource usage. How do you unit test how much memory, cpu, temporary disk space, etc a function uses? eg: Platforms for which unit tests are hard to setup/run. - embedded programming. You would need to load your test harness into the device, and watch LED patterns or feedback over serial. Assuming it has enough memory and resources :-) - mobile devices (probably the same issues as above) eg: race conditions in multithreaded code: You can't unit test effectively for these. And so on. > > Agreed. There is no good way of reusing your prototype code in TDD. You end > up having to throw your propotype away in order to have a proper tested > implementation in the end. Takes more time up front, but less time over the > lifecycle of the program you are building. > Sounds like you are talking about cases where you have to throw away the prototype *because* you couldn't unit test it properly? (but it was otherwise functioning perfectly well). >>Problem 3: Slows down development in general >> >>Having to write tests for all code takes time. Instead of eg: 10 hours >>coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours >>writing all the tests, and 10 on the code. > > This is incorrect. It speeds up development in general. The debugging phase of > development becomes much shorter because the bugs are fewer and the ones you > have a much shallower. There are so many tests that reduce the scope in which > you have to search for the bug that it usually becomes trivial to find. Depends on the type of bug. If it's a bug which breaks the unit tests, then it can be found quickly. Unit tests won't help with bugs they don't explicitly cover. eg off-by-one, memory leaks, CPU load, side-effects (outside what the unit tests test), and so on. That's another reason why I don't think that unit tests are a silver bullet. You can have code that's totally wrong, but still succeeds in the tests (even if they're very detailed). eg: hardcoding return values expected by the tests, and returning garbage the rest of the time. But once you track down problems like the above you can write more unit tests to catch those exact bugs in the future. This is one case where I do favour unit tests. I guess you could compare unit tests to blacklists or anitivirus software. All of them only catch cases that have been explicitely coded into them. > > I have direct experience from this, getting my company to change to TDD about > 10 months ago. Productivity has improved enormously. I'd say that we have cut > between 25 and 50% in development time. > Going by your figures and other cases I've read on the web, there are definitely cases where TDD is beneficial and can save a lot of time. What I'm not sure of (probably inexperience on my part) is when you should and shouldn't use TDD, and to what extent. I'm sure that factors like this have to come in to play when deciding if and how to use TDD in a given project: - size and age o
Re: need some help in serving static files inside a wsgi apps
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 [ Diez B. Roggisch <[EMAIL PROTECTED]> ] >> I finally managed to work with static files with a little hack, but it's >> ugly because I'm reading each static file per request. > > How else should that work? Apache does that the same way. I guess, Apache does some kind of memory caching for files, which are often requested and small enough to fit into the system memory. May be, that's what the OP is referring to ... - -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkg4a1QACgkQn3IEGILecb5ibACgoYyLaOc+q51D0g+SuudnqHab dYYAnjH3E0/e2y0owJ1PuWMk13i9YVA/ =7C8x -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Scipy+SQLite crashes... , was: Re: SQLite import fails sometimes ?
hello, through the scipy group I found a solution (no explanation yet), import sqlite3 from scipy import * solves the problem. cheers, Stef Stef Mientki wrote: John Machin wrote: Stef Mientki wrote: I don't know if this matters, but I also use sqlite3 from other than Python programs. You have an instance of sqlite3.dll in P:\Python\DLLs for use with Python, and (I guess) you have another instance of sqlite3.dll somewhere else, for use "from other than Python programs". Are they the same version? If not, this may be the problem. Start up your other application, then try to import sqlite3 from Python. If this is the problem, and you must be able to run both apps simultaneously, you will probably need to update one or the other. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list thanks John, I think I hit the problem, ;-) but I don't have a solution yet :-( After creating the simplest program that did work : import sqlite3 I started adding every import statement used in my program, until the program crashed, and here is the simplest program that crashes: from scipy import * import sqlite3 Traceback (most recent call last): File "D:\Data_Python\P24_PyLab_Works\module1.py", line 2, in import sqlite3 File "P:\Python\lib\sqlite3\__init__.py", line 24, in from dbapi2 import * File "P:\Python\lib\sqlite3\dbapi2.py", line 27, in from _sqlite3 import * ImportError: DLL load failed: Invalid access to memory location. Any solutions ? (btw I need to do the *-import, because I create an easy user environment to do math and physics) thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, Daemons and D-Bus
[ PurpleServerMonkey <[EMAIL PROTECTED]> ] > Would you use D-Bus or a more traditional IPC method such as sockets? > Although D-Bus is relatively new it looks interesting, just not sure > it would work well in this kind of project. DBus is not really intended for private communication between processes of the same application, but more for intercommunication between different applications. If the IPC interface of your backend daemons is intended to be used by other applications, DBus is the right choice, otherwise I would choose something different. The reason is, that DBus doesn't know about applications. It exposes all objects registered on the bus to every DBus client on the system and so makes you application-private API available to the public (and spams the bus with lots of generally useless objects ;) ). In case your IPC interface is application private, a custom IPC protocol (probably using XML RPC over unix sockets) is better suited. Moreover you should make your choice dependent on the type of data you transmit. Both DBus and XML-RPC wrap calls into XML messages, which is terribly inefficient for large binary data. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading __getitem__
En Thu, 22 May 2008 20:38:39 -0300, Andreas Matthias <[EMAIL PROTECTED]> escribió: > [EMAIL PROTECTED] wrote: > >> actually i ddin't think about the fact that you're overloading dict, which >> can already take multiple values in getitem > > Oh, I didn't know that. I totally misinterpreted the error message. > > >> so how about >> >> class crazy: pass >> >> and then in your dict class: >> >> def __getitem__(*args): > > Apparently, args already is a tuple, so this should be: > > def __getitem__(self, args): > > Is this documented somewhere? I couldn't find it anywhere. No, that's not correct. First, there is nothing special with the arguments to dict.__getitem__ -- except that the syntax obj[index] provides a delimiter and it allows for obj[a,b] as a shortcut for obj[(a,b)] -> obj.__getitem__((a,b)) You may use the *args notation in any function; it is always a tuple (a singleton, when you call the function with only one argument) py> def foo(*args): print args ... py> foo(1) (1,) py> foo(1,2) (1, 2) py> foo((1,2)) ((1, 2),) Compare with: py> def bar(arg): print arg ... py> bar(1) 1 py> bar(1,2) Traceback (most recent call last): File "", line 1, in TypeError: bar() takes exactly 1 argument (2 given) py> bar((1,2)) (1, 2) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: persistent deque version 4
En Thu, 22 May 2008 12:20:56 -0300, inhahe <[EMAIL PROTECTED]> escribió: > I thought about the fact that a decorator is merely syntactic sugar, so it > shouldn't have any closure magic that I can't make myself, and I realized > that I could have done it the following way: > > def makefunc(func): > def func2(instance, *args): > result = func(instance, *args) > instance.save() > return result > return func2 Using functools.wraps is better because it helps to preserve the function name and signature: def makefunc(func): @wraps(func) def wrapper(self, *args, **kwds): result = func(self, *args, **kwds) self.save() return result return wrapper -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
>> In order to get a new system working, it's nice to be able to throw >> together a set of modules quickly, and if that doesn't work, scrap it >> and try something else. There's a rule (forget where) that your first >> system will always be a prototype, regardless of intent. > > That's fine. It's alright to prototype without tests. The only rule is that > you cannot then use any of that code in production. > So, at what point do you start writing unit tests? Do you decide: "Version 1 I am going to definitely throw away and not put it into production, but version 2 will definitely go into production, so I will start it with TDD?". Where this doesn't work so well is if version 2 is a refactored and incrementally-improved version of version 1. At some point you need to decide "this is close to the version that will be in production, so let's go back and write unit tests for all the existing code". >> Problem 3: Slows down development in general >> >> Having to write tests for all code takes time. Instead of eg: 10 hours >> coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours >> writing all the tests, and 10 on the code. >> > You are either a very slow coder or a very poor tester: there should be a > lot more than 1/2 hour testing for 10 hours coding. I would say the > comparison might be 10 hours coding, 10 hours testing, then about a week > tracking down the bugs which escaped testing and got out to the customers. > With proper unit tests you will reduce all 3 of these numbers but > especially the last one. Any bug which gets away from the programmer and is > only caught further downstream costs vastly more than bugs caught during > development, and not just for the programmer but everyone else who > affected. Seriously, 10 hours of testing for code developed in 10 hours? What kind of environment do you write code for? This may be practical for large companies with hordes of full-time testing & QA staff, but not for small companies with just a handful of developers (and where you need to borrow somone from their regular job to do non-developer testing). In a small company, programmers do the lions share of testing. For programmers to spend 2 weeks on a project, and then another 2 weeks testing it is not very practical when they have more than one project. As for your other points - agreed, bugs getting to the customer is not a good thing. But depending on various factors, it may not be the end of the world if they do. eg: There are many thousands of bugs in open source bug trackers, but people still use open source for important things. Sometimes it is better to have software with a few bugs, than no software (or very expensive, or very long time in development). See "Worse is Better": http://en.wikipedia.org/wiki/Worse_is_better. See also: Microsoft ;-) > > You seem to think that people are suggesting you write all the tests up > front: what you should be doing is interleaving design+testing+coding all > together. That makes it impossible to account for test time separately as > the test time is tightly mixed with other coding, what you can be sure > though is that after an initial slowdown while you get used to the process > your overall productivity will be higher. Sounds like you are suggesting that I obfuscate my development process so noone can tell how much time I spent doing what :-) I think that moderate amounts of unit tests can be beneficial and not slow down development significantly (similar to a bit more time spent using version control vs not using it at all). Regression tests is a good example. But going to the TDD extreme of always coding tests before *any* code, for *all* projects, does not sit well with me (bad analogy: similar to wasting time checking in each line into version control separately, with a paragraph of comments). > > The first time you make a change to some code and a test which is > apparently completely unrelated to the change you made breaks is the point > when you realise that you have just saved yourself hours of debugging when > that bug would have surfaced weeks later. > The next time your project is running late, your manager and the customer will be upset if you spend time updating your unit tests rather than finishing off the project (and handing it over to QA etc) and adding the unit tests when there's actually time for it. >> Clients, deadlines, etc require actual software, not >> tests for software (that couldn't be completed on time because you >> spent too much time writing tests first ;-)). > > Clients generally require *working* software. Unfortunately it is all too > easy to ship something broken because then you can claim you completed the > coding on time and any slippage gets lost in the next 5 years of > maintenance. That's why you have human testing & QA. Unit tests can help, but they are a poor substitute. If the customer is happy with the first version, you can improve it, fix bugs, and add more unit tests later. David PS
Re: Code correctness, and testing strategies
On Sat, 24 May 2008 17:51:23 +0200 David <[EMAIL PROTECTED]> wrote: > Basically, with TDD you write the tests first, then the code which > passes/fails the tests as appropriate. However, as you're writing the > code you will also think of a lot of corner cases you should also > handle. The natural way to do this is to add them to the code first. > But with TDD you have to first write a test for the corner case, even > if setting up test code for it is very complicated. So, you have these > options: > > - Take as much time as needed to put a complicated test case in place. Absolutely. You may think that it is slowing you down but I can assure you that in the long run you are saving yourself time. > - Don't add corner case to your code because you can't (don't have > time to) write a test for it. If you don't have time to write complete, working, tested code then you have a problem with your boss/client, not your methodology. > - Add the corner case handling to the code first, and try to add a > test later if you have time for it. Never! It won't happen. > Having to write tests for all code takes time. Instead of eg: 10 hours > coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours > writing all the tests, and 10 on the code. In conventional development, 10 hours of code requires 90 hours of testing, debugging and maintenance. Under TDD (and agile in general) you spend 20 hours testing and coding. That's the real economics if you want to deliver a good product. > I think that automated tests can be very valuable for maintainability, > making sure that you or other devs don't break something down the > line. But these benefits must be worth the time (and general > inconvenience) spent on adding/maintaining the tests. I can assure you from experience that it always is worth the time. > If I did start doing some kind of TDD, it would be more of the 'smoke > test' variety. Call all of the functions with various parameters, test > some common scenarios, all the 'low hanging fruit'. But don't spend a > lot of time trying to test all possible scenarios and corner cases, > 100% coverage, etc, unless I have enough time for it. Penny wise, pound foolish. Spend the time now or spend the time later after your client complains. > I'm going to read more on the subject (thanks to Ben for the link). > Maybe I have some misconceptions. Perhaps just lack of experience. Read up on actual case studies. -- D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
I can see both sides of this argument, and I think TDD is great in some cases and not so great in others. I have used it before, but don't use it often, as the programs I write are very difficult to automatically test. (Games, which many of the bugs have to do with whether an optimization produces a visual artifact or not etc. Not possible to test that!) As far as time spent testing, it obviously various per project, person, and methodology. But I think you have some misconceptions about coding time. With TDD, you cannot measure test writing and code separately. Here's why. When you write code and then write a test for it, you spend a lot of time thinking about how the code is going to look while you are writing the code. You plan what the code is going to look like, what arguments are going to be passed to a function, how the code might be used by other code, etc. This is thinking time, with no code written. This is also interleaved with the actual time spent writing the code. (You are thinking of the plan while you are typing the actual code). Then you will likely do some sort of debugging at least, if not writing a test. This doesn't take much thought as you have already front loaded the thought. "Well I should print here to make sure this line is correct." >From a TDD perspective, most of the actual time is fairly the same, just shifted around. The thought process that I mentioned, of how code is going to be used or how it fits the system, instead of being hinged on the code, is now hinged on writing the test. This makes the thought process more formal than in the other methodology. Instead of thinking of one thing (how a function may be used) while doing something else (writing an if statement within some logic), you are actually writing code based on the system instead of the internal logic. Then, you write some code that makes it work. In many cases, (and in my experience) the actual code is easier to write in TDD, because it is more focused and directed. I am not writing one thing and keeping in mind other things. You think, plan, and then write to spec. It is most certainly a more formal process, and can be hard to get used to. And it doesn't work in all situations of course. But timewise it seems like all the processes are the same. Without tdd, you might, instead of writing a test per say, still spend that time writing a doc string, or just looking at where a function will be used to see what the code should look like etc. I think though that test-first streamlines things a bit. By itself I don't think it makes the process faster, and that front work of writing the tests can definitely feel slower. Further on is where you have the most benefit of having tests. And with practice you can get faster at it too. Most programmers have their own methodology that they have used for a while, so they are fast at it. Any change in that is going to be extremely sluggish until you are used to it. You should try TDD at least once for a small or medium project and go all the way through with it just to get a feel for it. If you can afford to of course :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
On Sat, 24 May 2008 21:14:36 +0200 David <[EMAIL PROTECTED]> wrote: > Is it considered to be cheating if you make a test case which always > fails with a "TODO: Make a proper test case" message? Yes. It's better to have the daily reminder that some code needs to be finished. > While it is possible to describe all problems in docs, it can be very > hard to write actual test code. It may be hard to start but once you have your framework in place it becomes very easy. > For example: sanity tests. Functions can have tests for situations > that can never occur, or are very hard to reproduce. How do you unit > test for those? Believe me, thousands of people reading this are remembering situations where something that couldn't possibly happen happened. > A few examples off the top of my head: > > * Code which checks for hardware defects (pentium floating point, > memory or disk errors, etc). > > * Code that checks that a file is less than 1 TB large (but you only > have 320 GB harddrives in your testing environment). > > * Code which checks if the machine was rebooted over a year ago. > > And so on. These I would manually test by temporarily changing > variables in the code, then changing them back. To unit test these you > would need to write mock functions and arrange for the tested code to > call them instead of the python built-ins. Yes but the mock functions can be wrappers around the real functions which only change the results that you are testing for. > eg: You call function MyFunc with argument X, and expect to get result Y. > > MyFunc calls __private_func1, and __private_func2. > > You can check in your unit test that MyFunc returns result Y, but you > shouldn't check __private_func1 and __private_func2 directly, even if > they really should be tested (maybe they sometimes have unwanted side > effects unrelated to MyFunc's return value). It isn't your job to test __private_func1 and __private_func2 unless you are writing MyFunc. > Depends on the type of bug. If it's a bug which breaks the unit tests, > then it can be found quickly. Unit tests won't help with bugs they > don't explicitly cover. eg off-by-one, memory leaks, CPU load, > side-effects (outside what the unit tests test), and so on. No but when you find that your code breaks due to these problems that's when you write new unit tests. > But once you track down problems like the above you can write more > unit tests to catch those exact bugs in the future. This is one case > where I do favour unit tests. Yes! One of the biggest advantages to unit testing is that you never ever deliver the same bug to the client twice. Delivering software with a bug is bad but delivering it with the same bug after it was reported and fixed is calamitous. -- D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On Sat, May 24, 2008 at 10:14 AM, Fuzzyman <[EMAIL PROTECTED]> wrote: > On May 24, 2:58 pm, Ben Finney <[EMAIL PROTECTED]<[EMAIL PROTECTED]> > > > wrote: > > Sh4wn <[EMAIL PROTECTED]> writes: > > > first, python is one of my fav languages, and i'll definitely keep > > > developing with it. But, there's 1 one thing what I -really- miss: > > > data hiding. I know member vars are private when you prefix them with > > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > > before it. > > > > From whom are you trying to hide your attributes? > > Actually, 'data hiding', although vastly overused by the static crowd > can be a reasonable thing to want. > > For example, at Resolver Systems we expose the spreadsheet object > model to our users. It hasa public, documented, API - plus a host of > undocumented internally used methods. > > We would really *much* rather hide these, because anything our > customers start using (whether documented or not) we will probably > have to continue supporting and maintaining. > > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke their > spreadsheet code by changing your API. > It apparently works for Sun Microsystems. They do that with a whole bunch of packages in Java, and Java does allow data hiding. http://java.sun.com/products/jdk/faq/faq-sun-packages.html > > You can make members truly private by proxying, but it is a bit > ungainly. > > Michael Foord > http://www.ironpythoninaction.com/ > > > > > > In Python, the philosophy "we're all consenting adults here" applies. > > You shouldn't pretend to know, at the time you write it, all the uses > > to which your code will be put. Barriers such as enforced "private" > > attributes will only cause resentment when people, despite your > > anticipations, *need* to access them and are then forced to hack their > > way around them. > > > > If you want the users of your code to know that an attribute should > > not be used as a public API for the code, use the convention of naming > > the attribute with a single leading underscore. This is a string > > signal that the attribute is part of the implementation, not the > > interface. The reader is then on notice that they should not rely on > > that attribute; but they are not *prohibited* from using it if > > necessary to their ends. > > > > > Python advertises himself as a full OOP language, but why does it > > > miss one of the basic principles of OOP? > > > > Who taught you that enforced restrictions on attribute access was a > > "basic principle" of OO? > > > > Perhaps you're confusing the "encapsulation" and "abstraction" > > principles for enforced access restrictions; they're not. > > > > > Will it ever be added to python? > > > > I hope not. > > > > -- > > \"Why was I with her? She reminds me of you. In fact, she | > > `\ reminds me more of you than you do!" -- Groucho Marx | > > _o__) | > > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
David <[EMAIL PROTECTED]> wrote: > So, at what point do you start writing unit tests? Do you decide: > "Version 1 I am going to definitely throw away and not put it into > production, but version 2 will definitely go into production, so I > will start it with TDD?". If you are going to prototype something without tests then you decide that up-front and throw the code away afterwards. It never is version 1 nor 2. > > Where this doesn't work so well is if version 2 is a refactored and > incrementally-improved version of version 1. At some point you need to > decide "this is close to the version that will be in production, so > let's go back and write unit tests for all the existing code". No you've gone beyond prototyping at that point. Prototypes are for throwing away. > Seriously, 10 hours of testing for code developed in 10 hours? What > kind of environment do you write code for? This may be practical for > large companies with hordes of full-time testing & QA staff, but not > for small companies with just a handful of developers (and where you > need to borrow somone from their regular job to do non-developer > testing). In a small company, programmers do the lions share of > testing. For programmers to spend 2 weeks on a project, and then > another 2 weeks testing it is not very practical when they have more > than one project. I've done plenty of projects using conventional methods in small companies. If anything test time equal to development time is a vast underestimate. > > As for your other points - agreed, bugs getting to the customer is not > a good thing. But depending on various factors, it may not be the end > of the world if they do. eg: There are many thousands of bugs in open > source bug trackers, but people still use open source for important > things. Sometimes it is better to have software with a few bugs, than > no software (or very expensive, or very long time in development). See > "Worse is Better": http://en.wikipedia.org/wiki/Worse_is_better. See > also: Microsoft ;-) > I'm not saying it is the end of the world. What it is though is expensive. If as the developer you spot a problem and fix it then all the time is yours. If it is caught in QA then it involves bug reporting, assigning priority, fixing and then the code has to be re-tested. If the customer finds the problem then customer support has to report it, someone has to assign it a priority, someone has to figure out how to replicate it, then someone has to figure out the problem, then you have to fix it, then the code has to be re-tested. Every level out from the initial developer you increase the number of people and number of steps involved. The other reason is that if your unit test breaks after you've just written 5 lines of code then you know which 5 lines of code are the problem. Probably you can see the problem instantly. At worst you just hit undo in your editor and try again. If a bug report comes back months later you have no idea where look in thousands of lines of code. > > The next time your project is running late, your manager and the > customer will be upset if you spend time updating your unit tests > rather than finishing off the project (and handing it over to QA etc) > and adding the unit tests when there's actually time for it. But you aren't updating unit tests. What you are doing is coding: the tests are an integral part of that, or rather the tests are part of the final design rather than coding. > >>> Clients, deadlines, etc require actual software, not >>> tests for software (that couldn't be completed on time because you >>> spent too much time writing tests first ;-)). >> >> Clients generally require *working* software. Unfortunately it is all >> too easy to ship something broken because then you can claim you >> completed the coding on time and any slippage gets lost in the next 5 >> years of maintenance. > > That's why you have human testing & QA. Unit tests can help, but they > are a poor substitute. If the customer is happy with the first > version, you can improve it, fix bugs, and add more unit tests later. No, they aren't a substitute at all. You still need human testing and QA, the difference is that with a good set of unit tests you reduce the number of times code comes back from QA before it can be passed and make it more likely that the customer will be happy with the first version. -- http://mail.python.org/mailman/listinfo/python-list
Newbie Question: How to use a .pth file on a Macintosh
Hello All, Hopefully this is an easy question: I'd like to use a .pth file on my Macintosh so that I can easily import modules that I've created in my own working directory. I've created a file called Robbie.pth. It includes a single line: /Robbie/PythonWork I can't seem to figure out where to put this file so that Python will recognize it when I start it up. I know that the path is correct because if I do the command sys.path.append('/Robbie/PythonWork') then everything works as expected. I just don't want to have to execute this command every time I start Python. I've looked at what's in sys.path, and have tried putting the file in various of the directories listed, to no avail. I've also tried putting it in the same directory where IDLE is (/Applications/ MacPython 2.5) and that doesn't work either. What am I missing? FYI I'm running MaxOS 10.4.8 and Python 2.5, Thank you in advance for the help. -Robbie -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
> Seriously, 10 hours of testing for code developed in 10 hours? What > > kind of environment do you write code for? This may be practical for > > large companies with hordes of full-time testing & QA staff, but not > > for small companies with just a handful of developers (and where you > > need to borrow somone from their regular job to do non-developer > > testing). > > I've done plenty of projects using conventional methods in small companies. > If anything test time equal to development time is a vast underestimate. > > Frederick Brooks general rule in Mythical Man Month is a project should estiamte1/6 coding and1/2 test time. In other words, 1 hour of coding time should have 3 hours of testing time. *"In examining conventionally scheduled projects, I have found that few allowed one-half of the projected schedule for testing, but that most did indeed spend half of the actual schedule for that purpose. Many of these were on schedule until and except in system testing." -MMM * -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
David <[EMAIL PROTECTED]> wrote: > Problem 1: You can only code against tests Yup. That's the flavor of Kool-Aide being served at a convenient TDD outlet near you. > Basically, with TDD you write the tests first, then the code which > passes/fails the tests as appropriate. However, as you're writing the > code you will also think of a lot of corner cases you should also > handle. The natural way to do this is to add them to the code first. That's only the natural way if you're haven't drunk the Kool-Aide :-) It takes a while to get used to, but once you get the hang of it, doing it this way becomes very natural. Sure, I think of corner cases when I'm writing code. But, what I do with them is write a test for them first, then write the code which implements it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
David <[EMAIL PROTECTED]> wrote: > While it is possible to describe all problems in docs, it can be very > hard to write actual test code. > > For example: sanity tests. Functions can have tests for situations > that can never occur, or are very hard to reproduce. How do you unit > test for those? In some cases, you can use mock objects to mimic the "can never happen" situations. But, you are right, there are certainly cases which are difficult or impossible to test for. TDD is a very powerful tool, but it's just that: a tool. It's not a magic wand. My suggestion is to make using TDD a habit, but don't turn it into a religion. You will undoubtedly find places where it's just the wrong tool. Don't let the fact that it can't do everything keep you from using it when it makes sense. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On May 24, 3:14 pm, Fuzzyman <[EMAIL PROTECTED]> wrote: > On May 24, 2:58 pm, Ben Finney <[EMAIL PROTECTED]> > wrote: > > > Sh4wn <[EMAIL PROTECTED]> writes: > > > first, python is one of my fav languages, and i'll definitely keep > > > developing with it. But, there's 1 one thing what I -really- miss: > > > data hiding. I know member vars are private when you prefix them with > > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > > before it. > > > From whom are you trying to hide your attributes? > > Actually, 'data hiding', although vastly overused by the static crowd > can be a reasonable thing to want. > > For example, at Resolver Systems we expose the spreadsheet object > model to our users. It hasa public, documented, API - plus a host of > undocumented internally used methods. > > We would really *much* rather hide these, because anything our > customers start using (whether documented or not) we will probably > have to continue supporting and maintaining. > > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke their > spreadsheet code by changing your API. "We told you not to use it in the API Docs" "Those names with leading undoerscores means _DO_NOT_USE_IT" "THose methods whose docstrings say DO NOT USE EXTERNALLY" And if they still use them, then they'd be problematic no matter what language was used. Customers ey? Can't live without 'em... ... Actually that's customers Sir! :-) - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: module import problem
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 [ Milos Prudek <[EMAIL PROTECTED]> ] > If I cd into /usr/share/python-support/python-gnupginterface and launch > Python I can "import GnuPGInterface". But when I run > DistUpgradeFetcherCore.py in that folder it always fails with No module > named GnuPGInterface. > > I do not know much about setting python path. Reinstall the package "python-gnupginterface" with "sudo aptitude reinstall python-gnupginterface". This should fix the problem, unless your package management is broken. - -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkg4mb0ACgkQn3IEGILecb6jpACfc80saFQz/Q6F5lYbuCUQxJt2 Z+8AoKkB+5hqm0tMmK/d1s1IjsSSCqAz =Z6/t -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
module import problem
I have a Kubuntu upgrade script that fails to run: File "/tmp/kde-root//DistUpgradeFetcherCore.py", line 34, in import GnuPGInterface ImportError No module named GnuPGInterface I got a folder /usr/share/python-support/python-gnupginterface with a "GnuPGInterface.py" but no __init__.py. In python command line, print sys.path shows that /usr/share/python-support/ is not among python paths. If I cd into /usr/share/python-support/python-gnupginterface and launch Python I can "import GnuPGInterface". But when I run DistUpgradeFetcherCore.py in that folder it always fails with No module named GnuPGInterface. I do not know much about setting python path. -- Milos Prudek -- http://mail.python.org/mailman/listinfo/python-list
Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding?
Hi, how to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to "\xED\x6F\x3C\x01" in python coding? When I take 'ED6F3C01' as a string and insert '\x' into it, I just got the error information : invalid \x escape. Thanks. ouyang -- http://mail.python.org/mailman/listinfo/python-list
Re: Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 [ zxo102 <[EMAIL PROTECTED]> ] >how to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to > "\xED\x6F\x3C\x01" in python coding? > When I take 'ED6F3C01' as a string and insert '\x' into it, I just got > the error information : invalid \x escape. [1]--> 'ED6F3C01'.decode('hex') Out[1]: '\xedo<\x01' - -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkg4mtEACgkQn3IEGILecb7W6ACeNwr/vavkaXluvc0zeSa4cy1N YFIAoJjMsrRcLhqAPRxKktUqt7miMTrs =jxll -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: for some reason the actual tries figure is not right
En Sat, 24 May 2008 15:32:56 -0300, garywood <[EMAIL PROTECTED]> escribió: > can someone explain why the tries displays the wrong number > thanks > orginally i started off with tries = 0 but it was off by 2 How would you count that if you were playing the game "for real"? I'd say that you start (mentally) at 0 and count one more each time the other player says a word. In your code, there are *two* places where the player inputs his guess. A common idiom is to rearrange the code this way: tries = 0 ... while True: guess = raw_input("Your guess: ") tries += 1 # break out of the loop when player guesses if guess==correct: break print "Sorry..." print "You guessed it in", tries, "tries." ... (instead of all those if/else, try to use a dictionary to hold the "hint" corresponding to each word - you might even store several hints, as a tuple) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list