Luminescence v. 0.3 released
Luminescence release 0.3 http://code.google.com/p/luminescence/ Luminescence is an application for generating HTML presentations from Markdown sources. It allows one to create simple presentations quickly. An small example of what it can do is here: http://dl.dropbox.com/u/1823095/luminescence/tutorial.html New in this release: support for UTF-8 files and fade-in/out effects. Installing: easy_install luminescence -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Re: If/then style question
On Thu, 16 Dec 2010 20:32:29 -0800, Carl Banks wrote: Even without the cleanup issue, sometimes you want to edit a function to affect all return values somehow. If you have a single exit point you just make the change there; if you have mulitple you have to hunt them down and change all of them--if you remember to. I just got bit by that one. If your function has so many exit points that you can miss some of them while editing, your function is too big, does too much, or both. Refactor and simplify. Or wrap the function in a decorator: def affect_all_return_values(func): @functools.wraps(func) def inner(*args, **kwargs): result = func(*args, **kwargs) do_something_to(result) return result return inner @affect_all_return_values def my_big_complicated_function(args): do_something_with_many_exit_points() -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question about importing modules.
cronoklee cronok...@gmail.com wrote: I'm starting my first python project but I'm having trouble getting off the ground. I've read all I can find about relative and absolute import paths but it's just not making sense to me... There seems to be around ten different ways to import a script. That's not really true. I need my project to be portable so I can copy the whole folder to run on any PC that has python installed. Is it always possible to simply include modules in the project directory and reference them without installing into the main python directory? Absolutely. I've managed this with small classes through trial and error but when I try it with anything larger (like PIL module for example) I get errors. Do I need to actually install anything or is it enough just to include the relevant scripts? PIL requires DLLs as well as other Python files. You can't just copy the top-level PIL files to your own private directory. All the modules I've found come with tonnes of files and subdirectories. Do I need all these files or should I just choose the scripts/folders I need? If you are delivering a program to clients, then you should look at something like py2exe, which will examine your code and produce a zip file that includes all of the files your application will need. If you are delivering a script for someone that will definitely have Python installed, then you just need to identify the dependencies. Let that person install PIL. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Read / Write OpenOffice SpreadSheet ?
Hello, There is no package needed to read or write the new open document files. The files are merely a jar archive containing XML files. You can open and update them using jar as a subprocess and manipulate the XML files using your favorite XML libraries DOM/SAX/XPath/Etree/etc. thanks for your hint. I was aware of that, OO files are a bunch of zipped XML files. But, i searh for something more comfortable/highlevel that lets me just do things like doc.Cell(1, 3) = 'abc' or so. If that doesn't suit you, you can manipulate them using OO.org through its UNO interface; but, I find that much more involved then simply accessing the files directly. Thanks, i read about it but as i understood it, UNO needs Python 2.3.x and i'd like to base on something actual. Best regards, Torsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question about importing modules.
On Dec 17, 4:42 pm, cronoklee cronok...@gmail.com wrote: Hi I'm starting my first python project but I'm having trouble getting off the ground. I've read all I can find about relative and absolute import paths but it's just not making sense to me... There seems to be around ten different ways to import a script. I need my project to be portable so I can copy the whole folder to run on any PC that has python installed. Is it always possible to simply include modules in the project directory and reference them without installing into the main python directory? I've managed this with small classes through trial and error but when I try it with anything larger (like PIL module for example) I get errors. Do I need to actually install anything or is it enough just to include the relevant scripts? All the modules I've found come with tonnes of files and subdirectories. Do I need all these files or should I just choose the scripts/folders I need? Thanks, cronoklee You may find this useful as an overview of importing ... http://effbot.org/zone/import-confusion.htm ... also this ... http://diveintopython.org/object_oriented_framework/importing_modules.html I may be stating the obvious but here's an example of using the Image object offered by PIL ... from PIL import Image ... as documented here ... http://www.pythonware.com/library/pil/handbook/image.htm Regarding bundling PIL with an app I'd second what Tim Roberts has to say regarding py2Exe regards Richard. -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
John Gordon wrote: (This is mostly a style question, and perhaps one that has already been discussed elsewhere. If so, a pointer to that discussion will be appreciated!) When I started learning Python, I wrote a lot of methods that looked like this: def myMethod(self, arg1, arg2): if some_good_condition: if some_other_good_condition: if yet_another_good_condition: do_some_useful_stuff() exitCode = good1 else: exitCode = bad3 else: exitCode = bad2 else: exitCode = bad1 return exitCode But lately I've been preferring this style: def myMethod(self, arg1, arg2): if some_bad_condition: return bad1 elif some_other_bad_condition: return bad2 elif yet_another_bad_condition: return bad3 do_some_useful_stuff() return good1 I like this style more, mostly because it eliminates a lot of indentation. However I recall one of my college CS courses stating that one entry, one exit was a good way to write code, and this style has lots of exits. Are there any concrete advantages of one style over the other? Thanks. What about, def myMethod(): for condition, exitCode in [ (cond1, 'error1'), (cond2, 'very bad error'), ]: if not condition: break else: do_some_usefull_stuff() # executed only if the we never hit the break statement. exitCode = good1 return exitCode This version uses the 'for ... else' statement. You can easily add conditions by simply adding a line in the list, that's it. Note that this code uses a shadow declaration of exitCode in the for loop. If you're not comfortable with that, you'll have to use a properly 'declared' variable retCode and write retCode = exitCode before breaking. Actually I would advise to do so. JM -- http://mail.python.org/mailman/listinfo/python-list
RE: If/then style question
-Original Message- What about, def myMethod(): for condition, exitCode in [ (cond1, 'error1'), (cond2, 'very bad error'), ]: if not condition: break else: do_some_usefull_stuff() # executed only if the we never hit the break statement. exitCode = good1 return exitCode I reply - This is interesting, but I don't understand it (which speaks volumes about the level of my understanding of Python). First, just to clarify, I don't think the indentation I saw was what was originally posted. The else must be indented to match the if, and the two statements under else are in the else block. The return statement is indented at the same level as the for statement, so that it will be executed after the for loop exits. Correct? Now, the for loop will set condition to cond1 and exitCode to 'error1'. Then it checks the contents of the condition variable. But what does not variable_name by itself mean? I'm guessing that it checks that the variable refers to an object. So, the first time through, condition refers to cond1, the if condition is false, and the else block gets executed, and exitCode is changed to refer to good1. The next time through the loop, condition is set to refer to cond2 and exitCode is set to refer to 'very bad error'. Again, condition is refering to something, so the else block is executed and we do useful stuff again, which is probably not helpful and could well be harmful. exitCode is set to good1, we're finished with the loop, and we return exitCode. What happens if we try to do useful stuff, and we can't? Where does the error indication get set? And once it does get set, the only way we can exit the for loop is for condition to not refer to anything. How can that happen? Thank you very much for your explanation and your patience with one who only uses Python in very simplistic ways. RobR -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On Fri, 17 Dec 2010 09:09:49 -0500, Rob Richardson wrote: First, just to clarify, I don't think the indentation I saw was what was originally posted. The else must be indented to match the if, and the two statements under else are in the else block. The return statement is indented at the same level as the for statement, so that it will be executed after the for loop exits. Correct? I think that what you are missing is that for-loops can include an else clause too, like this: for x in (1,2,3): ... print(x) ... else: ... print(finished) ... 1 2 3 finished The else block runs after the for block, unless you exit the entire block by returning, raising an exception, or using break: for x in (1,2,3): ... print(x) ... if x == 3: break ... else: ... print(finished) ... 1 2 3 Does that clear up what is going on? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
Rob Richardson wrote: -Original Message- What about, def myMethod(): for condition, exitCode in [ (cond1, 'error1'), (cond2, 'very bad error'), ]: if not condition: break else: do_some_usefull_stuff() # executed only if the we never hit the break statement. exitCode = good1 return exitCode I reply - This is interesting, but I don't understand it (which speaks volumes about the level of my understanding of Python). First, just to clarify, I don't think the indentation I saw was what was originally posted. The else must be indented to match the if, and the two statements under else are in the else block. No, the else is indented to the for loop. for ... else is a python statement, the else block is executed only if the loop did never break. http://docs.python.org/reference/compound_stmts.html#for The return statement is indented at the same level as the for statement, so that it will be executed after the for loop exits. Correct? Now, the for loop will set condition to cond1 and exitCode to 'error1'. Then it checks the contents of the condition variable. But what does not variable_name by itself mean? condition is a bool value. if not condition is evaluated to True, if the condition is False. condition = False not condition = True condition = ('Foo' == 'Foo') not condition = False [snip] RobR My mail client could have messed up with the indentation. Here is the code: http://paste-it.net/public/t8a4acd/python/ JM -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On Thu, Dec 16, 2010 at 6:51 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: ... Functions always have one entry. The only way to have multiple entry points is if the language allows you to GOTO into the middle of a function, and Python sensibly does not allow this. The one entry, one exit rule comes from the days when people would routinely write spaghetti code, jumping into and out of blocks of code without using functions at all. Only 99.7% true. Fortran still allows the appalling ENTRY statement. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question about importing modules.
Hey thanks for the help fellas. The links were helpful and the pyExe program looks great. I might well end up using this. I'm still a little confused as to how the directory structure works. PIL (http://www.pythonware.com/products/pil/#pil117), for example comes packed in a folder called Imaging-1.1.7 which contains a bunch of other directories, one of which is PIL. Now, what I've done is move this subfolder PIL into the same directory as my python test script and used: from PIL import Image I assume this instructs python to look in the PIL folder for Image.py. Am I wrong? I feel like I'm wrong. If I need to put the whole Imaging-1.1.7 folder somewhere else, how do I reference the specific Image module that I need? Sorry for the stupidity - I'm coming from PHP where you just include path/to/script.php so this is a bit alien to me. Thanks a lot, cronoklee -- http://mail.python.org/mailman/listinfo/python-list
Re: How to pop the interpreter's stack?
On 12/16/10 6:33 PM, Steven D'Aprano wrote: On Thu, 16 Dec 2010 10:39:34 -0600, Robert Kern wrote: On 12/16/10 10:23 AM, Steven D'Aprano wrote: On Thu, 16 Dec 2010 07:29:25 -0800, Ethan Furman wrote: Tim Arnold wrote: Ethan Furmanet...@stoneleaf.us wrote in message news:mailman.4.1292379995.6505.python-l...@python.org... kj wrote: The one thing I don't like about this strategy is that the tracebacks of exceptions raised during the execution of __pre_spam include one unwanted stack level (namely, the one corresponding to __pre_spam itself). [...] A decorator was one of the items kj explicity didn't want. Also, while it would have a shallower traceback for exceptions raised during the __pre_spam portion, any exceptions raised during spam itself would then be one level deeper than desired... while that could be masked by catching and (re-?)raising the exception in the decorator, Steven had a very good point about why that is a bad idea -- namely, tracebacks shouldn't lie about where the error is. True, very true... but many hours later, it suddenly hit me that what KJ was asking for wasn't *necessarily* such a bad idea. My thought is, suppose you have a function spam(x) which raises an exception. If it's a *bug*, then absolutely you need to see exactly where the error occurred, without the traceback being mangled or changed in any way. But what if the exception is deliberate, part of the function's documented behaviour? Then you might want the exception to appear to come from the function spam even if it was actually generated inside some private sub-routine. Obfuscating the location that an exception gets raised prevents a lot of debugging (by inspection or by pdb), even if the exception is deliberately raised with an informative error message. Not least, the code that decides to raise that exception may be buggy. But even if the actual error is outside of the function (e.g. the caller is passing bad arguments), you want to at least see what tests the __pre_spam function is doing in order to decide to raise that exception. And how do you think you see that from the traceback? The traceback prints the line which actually raises the exception (and sometimes not even that!), which is likely to be a raise statement: import example example.func(42) Traceback (most recent call last): File stdin, line 1, inmodule File example.py, line 3, in func raise ValueError('bad value for x') ValueError: bad value for x The actual test is: def func(x): if x 10 and x%2 == 0: raise ValueError('bad value for x') but you can't get that information from the traceback. But I can get the line number and trivially go look it up. If we elide that stack frame, I have to go hunting and possibly make some guesses. Depending on the organization of the code, I may have to make some guesses anyways, but if I keep the decision to raise an exception close to the actual raising of the exception, it makes things a lot easier. Python's exception system has to handle two different situations: buggy code, and bad data. It's not even clear whether there is a general distinction to be made between the two, but even if there's not a general distinction, there's certainly a distinction which we can *sometimes* make. If a function contains a bug, we need all the information we can get, including the exact line that causes the fault. But if the function deliberately raises an exception due to bad input, we don't need any information regarding the internals of the function (assuming that the exception is sufficiently detailed, a big assumption I grant you!). If I re-wrote the above func() like this: def func(x): if !(x= 10): if x%2 != 0: pass else: raise ValueError('bad value for x') return I would have got the same traceback, except the location of the exception would have been different (line 6, in a nested if-block). To the caller, whether I had written the first version of func() or the second is irrelevant. If I had passed the input validation off to a second function, that too would be irrelevant. The caller doesn't care about tracebacks one way or the other, either. Only someone *viewing* the traceback cares as well as debuggers like pdb. Eliding the stack frame neither helps nor harms the caller, but it does substantially harm the developer viewing tracebacks or using a debugger. I don't expect Python to magically know whether an exception is a bug or not, but there's something to be said for the ability to turn Python functions into black boxes with their internals invisible, like C functions already are. If (say) math.atan2(y, x) raises an exception, you have no way of knowing whether atan2 is a single monolithic function, or whether it is split into multiple pieces. The location of the exception is invisible to the caller: all you can see is that atan2 raised an exception. And that has frustrated my debugging efforts
Re: Read / Write OpenOffice SpreadSheet ?
Torsten Mohr, 17.12.2010 02:07: i search for a possibility to access OpenOffoce SpreadSheets from Python with a reasonably new version of Python. Can anybody point me to a package that can do this? Have you looked through the relevant PyPI packages? http://pypi.python.org/pypi?%3Aaction=searchterm=openoffice Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On 12/17/2010 9:38 AM, Steven D'Aprano wrote: On Fri, 17 Dec 2010 09:09:49 -0500, Rob Richardson wrote: First, just to clarify, I don't think the indentation I saw was what was originally posted. The else must be indented to match the if, and the two statements under else are in the else block. The return statement is indented at the same level as the for statement, so that it will be executed after the for loop exits. Correct? I think that what you are missing is that for-loops can include an else clause too, like this: for x in (1,2,3): ... print(x) ... else: ... print(finished) ... 1 2 3 finished The else block runs after the for block, unless you exit the entire block by returning, raising an exception, or using break: for x in (1,2,3): ... print(x) ... if x == 3: break ... else: ... print(finished) ... 1 2 3 Does that clear up what is going on? This construct appears to be unpopular in actual use, and when it comes up in classes and seminars there is always interesting debate as people discuss potential uses and realise there are useful applications. I think the choice of keyword is probably not Guido's crowning language achievement, but then since the English keywords don't make natural sense to those who speak other languages it's at least fair that there should be one that isn't totally natural to English speakers. A small price to pay for all the other keywords not being Dutch. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon 2011 Atlanta March 9-17 http://us.pycon.org/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
PyUNO [Was: Read / Write OpenOffice SpreadSheet ?]
On Fri, 2010-12-17 at 10:19 +0100, Torsten Mohr wrote: Thanks, i read about it but as i understood it, UNO needs Python 2.3.x and i'd like to base on something actual. I do not *believe* this is true. http://pypi.python.org/pypi/cloudooo/1.0.9 for instance is Python 2.6 and uses PyUNO. I would strongly recommend against floundering about in OOo's very complex XML files - it is trivially easy to render a document unusable. -- http://mail.python.org/mailman/listinfo/python-list
RE: If/then style question
My thanks for pointing out the existence of the else: suite in the for statement. However, I remain confused. For reference, here's the original code: def myMethod(): for condition, exitCode in [ (cond1, 'error1'), (cond2, 'very bad error'), ]: if not condition: break else: do_some_usefull_stuff() # executed only if the we never hit the break statement. exitCode = good1 return exitCode What do we know about cond1 and cond2? Do they have to be assigned before this for statement is executed? The sample code doesn't show it. The loop is going to to execute once for condition = cond1 and exitCode = 'error1'. The only thing it's going to do is check to see what condition is. Since we can assume (I hope) that cond1 is not false, then the for loop continues. Now condition = cond2 and exitCode = 'very bad error'. The if condition is still false, so the loop continues. We've come to the end now, and the else: suite is executed. We finally do some useful stuff and exitCode = good1. (Should that have been in quotes, or doesn't it matter?) But now the for loop's job is done and we return the exitCode, which at this point is good1. But I still don't understand what happens if we can't do useful stuff. Where does an error code get set, and where is that error code checked? We don't have a chance to check it in the for loop, because once we're in the else: suite the loop condition is never rechecked. Or is it? Thanks again! RobR -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On 17/12/2010 15:53, Steve Holden wrote: [... snip example of for-else ...] This construct appears to be unpopular in actual use, and when it comes up in classes and seminars there is always interesting debate as people discuss potential uses and realise there are useful applications. I use this not infrequently, and I like it when it seems to be an elegant way to express the code path. But I still misremember from time to time and assume that the else clause fires when the for loop is empty. TJG -- http://mail.python.org/mailman/listinfo/python-list
ANN: Shed Skin 0.7
hi malcolm, Congratulations on your latest release! thanks! :D How well do python extension modules created with ShedSkin work with applications that expose a GUI, eg. Tkinter or wxPython apps? quite well I think, but there are some limitations you probably want to be aware of. these are described in the tutorial. Can ShedSkin code be run in a thread and communicate with the main interpreter thread through a Queue or Lock? (Or should one use the multiprocessing module?) I'm sure things are not thread safe, so you probably want to use the multiprocessing module. how to do this is also described in the tutorial (it's very simple). you probably don't want to use threading anyway for computationally intensive code (because of the GIL). several of the shedskin examples have a GUI, and the new 'pylot' example both has a GUI and uses the multiprocessing module in combination with a shedskin-generated extension module. thanks, mark. -- http://www.youtube.com/watch?v=E6LsfnBmdnk -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
Jean-Michel Pichavant jeanmic...@sequans.com writes: What about, def myMethod(): for condition, exitCode in [ (cond1, 'error1'), (cond2, 'very bad error'), ]: if not condition: break else: do_some_usefull_stuff() # executed only if the we never hit the break statement. exitCode = good1 return exitCode This version uses the 'for ... else' statement. For..else always has seemed ugly and confusing to me, as does that thing of using the captured loop indexes after the loop finishes. I'd prefer a more functional style (untested): def myMethod(): def success(): do_some_usefull_stuff() return good1 cond_table = [ (cond1, lambda: 'error1'), (cond2, lambda: 'very bad error'), (True, success) ] func = next(f for c,f in cond_table if c) return func() This uses the next() builtin from Python 2.6. You could make it more concise: def myMethod(): cond_table = [ (cond1, lambda: 'error1'), (cond2, lambda: 'very bad error'), (True, lambda: (do_some_usefull_stuff(), good1)[1]) ] return next(f for c,f in cond_table if c)() -- http://mail.python.org/mailman/listinfo/python-list
Re: PyUNO [Was: Read / Write OpenOffice SpreadSheet ?]
Adam Tauno Williams, 17.12.2010 17:02: On Fri, 2010-12-17 at 10:19 +0100, Torsten Mohr wrote: Thanks, i read about it but as i understood it, UNO needs Python 2.3.x and i'd like to base on something actual. I do not *believe* this is true. http://pypi.python.org/pypi/cloudooo/1.0.9 for instance is Python 2.6 and uses PyUNO. The Python installation can be replaced. Last I heard, many Linux distros used the platform Python, for example, instead of shipping an embedded one with OOo. I would strongly recommend against floundering about in OOo's very complex XML files - it is trivially easy to render a document unusable. True. It's not so much of a problem to read them, but writing a correct document can be tricky. What works relatively well is to write a template document in OOo and do programmatic replacements in it. But that's not guaranteed to work, either. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
Rob Richardson wrote: My thanks for pointing out the existence of the else: suite in the for statement. However, I remain confused. For reference, here's the original code: def myMethod(): for condition, exitCode in [ (cond1, 'error1'), (cond2, 'very bad error'), ]: if not condition: break else: do_some_usefull_stuff() # executed only if the we never hit the break statement. exitCode = good1 return exitCode What do we know about cond1 and cond2? Do they have to be assigned before this for statement is executed? The sample code doesn't show it. cond1 and cond2 should be expressions of some sort, e.g. check_files() or feedback (feedback being a variable of some sort). The loop is going to to execute once for condition = cond1 and exitCode = 'error1'. The only thing it's going to do is check to see what condition is. Since we can assume (I hope) that cond1 is not false, then the for loop continues. Now condition = cond2 and exitCode = 'very bad error'. The if condition is still false, so the loop continues. We've come to the end now, and the else: suite is executed. We finally do some useful stuff and exitCode = good1. (Should that have been in quotes, or doesn't it matter?) But now the for loop's job is done and we return the exitCode, which at this point is good1. But I still don't understand what happens if we can't do useful stuff. Where does an error code get set, and where is that error code checked? We don't have a chance to check it in the for loop, because once we're in the else: suite the loop condition is never rechecked. Or is it? You have outlined what happens when cond1 and cond2 both evaluate to True -- what happens if, say, cond2 evaluates to False? . . . . . if not cond2 becomes True, we hit the break, do not do do_some_usefull_stuff(), but proceed to return exitCode -- and exitCode was set in the for loop to 'very bad error' when condition was set to cond2. The exitCode no longer needs to be checked inside the function, because there is no chance of do_some_useful_stuff running if any of the conditions are False. Hope this helps. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On 12/17/2010 11:13 AM, Tim Golden wrote: On 17/12/2010 15:53, Steve Holden wrote: [... snip example of for-else ...] This construct appears to be unpopular in actual use, and when it comes up in classes and seminars there is always interesting debate as people discuss potential uses and realise there are useful applications. I use this not infrequently, and I like it when it seems to be an elegant way to express the code path. But I still misremember from time to time and assume that the else clause fires when the for loop is empty. Yes, that's a common misconception. The classical use is something like for item in possibilities: if item == target: break else: raise NotFound(Didn't find it) Though of course arguably that logic might be expressed in other ways, such as if target not in possibilities: raise NotFound(Didn't find it) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon 2011 Atlanta March 9-17 http://us.pycon.org/ See Python Video! http://python.mirocommunity.org/ Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
Steve Holden st...@holdenweb.com writes: I think the choice of keyword is probably not Guido's crowning language achievement, I remember the behaviour by considering a typical application: for thing in things: if shinyp(thing): break else: raise DullError, 'nothing shiny found' In this kind of search loop, `break' signifies a kind of successful completion: the `for' loop can be considered to be a test acting over an iterable, and `else' therefore denotes the action if the test fails. I don't know whether that's the official intuition, or even if there is an official intuition, but it works well enough for me. I'm quite fond of Python's extra `else' clauses in `for' and (particularly) `try'. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
Tim Golden m...@timgolden.me.uk writes: On 17/12/2010 15:53, Steve Holden wrote: [... snip example of for-else ...] This construct appears to be unpopular in actual use, and when it comes up in classes and seminars there is always interesting debate as people discuss potential uses and realise there are useful applications. I use this not infrequently, and I like it when it seems to be an elegant way to express the code path. But I still misremember from time to time and assume that the else clause fires when the for loop is empty. I use it from time to time, even though, like you, I used to always be unsure when the else: suite would be executed. I now remember this idiom as the break else construct: either the loop breaks, or the else: suite is executed. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
I now remember this idiom as the break else construct: either the loop breaks, or the else: suite is executed. A perfect description. Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On 2010-12-16, Stefan Sonnenberg-Carstens stefan.sonnenb...@pythonmeister.com wrote: The advantage in latter case is fewer operations, because you can skip the assignments, and it is more readable. The one entry, one exit is an advice. Not a law. Your code is OK. As long as it works ;-) Even that last bit isn't that important. Give me code that's easy-to-read and doesn't work rather code that works and can't be read any day. -- Grant Edwards grant.b.edwardsYow! What's the MATTER at Sid? ... Is your BEVERAGE gmail.comunsatisfactory? -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On 2010-12-16, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: On Thu, 16 Dec 2010 21:49:07 +, John Gordon wrote: (This is mostly a style question, and perhaps one that has already been discussed elsewhere. If so, a pointer to that discussion will be appreciated!) When I started learning Python, I wrote a lot of methods that looked like this: def myMethod(self, arg1, arg2): if some_good_condition: if some_other_good_condition: if yet_another_good_condition: do_some_useful_stuff() exitCode = good1 else: exitCode = bad3 else: exitCode = bad2 else: exitCode = bad1 return exitCode It doesn't look like you were learning Python. It looks like you were learning C with Python syntax :( Let's not blame C for bad program structure. No good C programmer would use that construct either. One choice in C would look like this: if (some_condition) return code1; if (other_condition) return code2; if (condition3) return code3; //do whatever work really needs to be done here. return successCode; Or, if there's cleanup that needs to be done, then you raise a an exception: if (condition1) { ret = code1; goto errexit; } if (condition2) { ret = code2; goto errexit; } if (condition3) { ret = code3; goto errexit; } // do the normal bit of work errexit: //cleanup return ret; -- Grant Edwards grant.b.edwardsYow! Awright, which one of at you hid my PENIS ENVY? gmail.com -- http://mail.python.org/mailman/listinfo/python-list
RE: If/then style question
-Original Message- You have outlined what happens when cond1 and cond2 both evaluate to True -- what happens if, say, cond2 evaluates to False? - I reply And the light goes on! (And palm strikes forehead.) I was thinking that the error we were processing was raised by the do_some_useful_stuff() function. But the whole purpose of this thread was to evaluate error conditions that might have been set before we do useful stuff! Which, of course, was what the original poster was asking. My thanks again for your patience. RobR -- http://mail.python.org/mailman/listinfo/python-list
Re: PyUNO [Was: Read / Write OpenOffice SpreadSheet ?]
On 2010-12-17, Adam Tauno Williams awill...@whitemice.org wrote: I would strongly recommend against floundering about in OOo's very complex XML files - it is trivially easy to render a document unusable. I do it all the time and have never had a problem. I don't generate the documents from scratch; I generate a template that contains everything that don't need to dynamically generate. Then I use one of two methods to to update the content.xml: 1. In the simplest cases, I only need to change a single data field. I replace the literal data in the content.xml file with: replace field=variable_name/ Then, using a DOM implementation, I can use getElementsByTagName() to get all of the replace tags and send the variable name to a distpach that generates the text used to replace the tag. 2. For collections of data (spreadsheet cells, table cells/rows, etc, I leave one piece of sample data in place. I then clone the DOM element that I can use as a template and delete the origional. Entering the data is then a simple matter of cloning the template element, updating the information that it contains, and adding it to the childNodes of the parent. Since tags all come from the file that OO.org/LibreOffice generated, the resulting markup will be valid. Once the content.xml file has been updated, I simply run jar as a subprocess to update the content.xml file in the ods/odt file. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyUNO [Was: Read / Write OpenOffice SpreadSheet ?]
On 17-12-2010 17:02, Adam Tauno Williams wrote: On Fri, 2010-12-17 at 10:19 +0100, Torsten Mohr wrote: Thanks, i read about it but as i understood it, UNO needs Python 2.3.x and i'd like to base on something actual. I do not *believe* this is true. http://pypi.python.org/pypi/cloudooo/1.0.9 for instance is Python 2.6 and uses PyUNO. I would strongly recommend against floundering about in OOo's very complex XML files - it is trivially easy to render a document unusable. looks great, but is there something alike for Windows ? thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On Thu, 16 Dec 2010 21:49:07 +, John Gordon wrote: (This is mostly a style question, and perhaps one that has already been discussed elsewhere. If so, a pointer to that discussion will be appreciated!) When I started learning Python, I wrote a lot of methods that looked like this: def myMethod(self, arg1, arg2): if some_good_condition: if some_other_good_condition: if yet_another_good_condition: do_some_useful_stuff() exitCode = good1 else: exitCode = bad3 else: exitCode = bad2 else: exitCode = bad1 return exitCode Another way to look at this is as question of object-oriented style, as you are using a method in your example... Arguably, rather than branching your code based on the arguments being passed to your method, you can embody the required behaviour in subclasses of your class, and at runtime just use an object that does the right thing. Of course, you end up writing the same branching in some factory object instead, but at least it isn't cluttering up your business logic any longer. Trying to write an OO-style program without using any if statements in the business logic can be an interesting exercise, albeit not a terribly realistic one. Apologies if your choice of a method for your example was entirely incidental to your question :) Kev -- http://mail.python.org/mailman/listinfo/python-list
Re: Added Python, WSGI to XAMPP
How-To: Add VirtualEnv and Pylons (WSGI framework) to XAMPP http://www.apachefriends.org/f/viewtopic.php?f=17t=42981 Maybe, if there's no Zope. Or we'll run away screaming... That is rather pathetically true... Ah well, each to their own... Chris What I really don't like right off is that Pyramid is contorting the MVC model just as Django did with their MTV model. They are both making the controller be the view and this confuses the hell out of people who come from true MVC based projects. The VIEW is the bits that stream out of the webserver back to the users browser. The CONTROLLER is the code that gathers all the pieces from the model and constructs the python code that is then fed to the engine that then creates the view. And just because the controller navigates the logic to dynamically contruct/render a view, that does not make 'it' the view. In turbogears that is exactly what happens. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Help with threading.local use in python-memcache module.
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Some time ago I accepted a patch to base the memcache client module on the threading.local class. Now I've got some reports of issues with this that I'm not sure what the best way to resolve is. Bug #530229: https://bugs.launchpad.net/python-memcached/+bug/530229 says: Client is derived from threading.local presumably at some misguided sense of working across multiple threads. However this doesn't work if the same Client is used across threads serially. For instance if I create a client in one thread and then call set_servers and then use the Client in another thread the set_servers call would have had no effect since the servers and buckets are per-thread due to threading.local. and that the set_servers call only impacts one thread rather than them all. I'm a bit reluctant to just remove threading.local, in case anyone is relying on it now that it's in there. But I'd like to offer a solution for the cases where it doesn't work. Any suggestions on the solution for this? Thanks, Sean -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.11 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org/ iD8DBQFNC9TixUhyMYEjVX0RAnOWAJwKZnmE/6cKR4I4tl4Km//gtkxo1QCgvK1Y ULmOdWnAViTzAS4sMts97ZA= =7qXJ -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: class inheritance
On Saturday, March 13, 2010 9:03:36 AM UTC-8, Jonathan Lundell wrote: I've got a subclass of fractions.Fraction called Value; it's a mostly trivial class, except that it overrides __eq__ to mean 'nearly equal'. However, since Fraction's operations result in a Fraction, not a Value, I end up with stuff like this: x = Value(1) + Value(2) where x is now a Fraction, not a Value, and x == y uses Fraction.__eq__ rather than Value.__eq__. This appears to be standard Python behavior (int does the same thing). I've worked around it by overriding __add__, etc, with functions that invoke Fraction but coerce the result. But that's tedious; there are a lot of methods to override. So I'm wondering: is there a more efficient way to accomplish what I'm after? I recently implemented a different approach to this. I've got: class Rational(fractions.Fraction): ... and some methods of my own, including my own __new__ and __str__ (which is one of the reasons I need the class). Then after (outside) the class definition, this code that was inspired by something similar I noticed in Python Cookbook. There are two things going on here. One is, of course, the automation at import time. The other is that the wrapper gets a Fraction instance and simply overrides __class__, rather than creating yet another Rational and unbinding the interim Fraction. Seems to work quite well. # create wrappers for Rational methods that return Rational (not Fraction) objects # def _wrap_method(method): wrap a Fraction method in Rational fraction_method = getattr(Fraction, method) def x(*args): call Fraction and change result to Rational v = fraction_method(*args) v.__class__ = Rational return v x.func_name = method setattr(Rational, method, x) for name in pos neg abs trunc.split(): _wrap_method(__%s__ % name) # wrap method, eg __pos__ for name in add sub mul div truediv floordiv mod pow.split(): _wrap_method(__%s__ % name) # wrap method, eg __add__ _wrap_method(__r%s__ % name) # wrap reversed-argument method, eg __radd__ del _wrap_method -- http://mail.python.org/mailman/listinfo/python-list
subprocess.Popen() and a .msi installer
Hey everyone, I'm working on a script which uses subprocess to launch a bunch of installers, but I'm getting problems with .msi installers although .exe ones work fine. The output I get is this: import subprocess p = subprocess.Popen('python.msi') Traceback (most recent call last): File pyshell#1, line 1, in module p = subprocess.Popen('python.msi') File C:\Python25\lib\subprocess.py, line 593, in __init__ errread, errwrite) File C:\Python25\lib\subprocess.py, line 793, in _execute_child startupinfo) WindowsError: [Error 8] %1 no es una aplicación Win32 válida Has this ever happen to any of you? The idea is to get this running, make it an exe (with py2exe) and use it whenever I need to install my whole development environment in the right order. Thanks in advance to all of you. Alonso Sebastian. -- http://mail.python.org/mailman/listinfo/python-list
Creating custom types from C code
Hello, I have an extension module for a 3rd party library in which I am wrapping some structures. My initial attempt worked okay on Windows but failed on Linux. I was doing it in two parts. The first part on the C side of things I was turning the entire structure into a char array. The second part in Python code I would unpack the structure. Anyway, I decided I should be doing things a little cleaner so I read up on Defining New Types http://docs.python.org/extending/newtypes.html I got it to work but I'm not sure how to create these new objects from C. My setup is almost exactly like the example on that page except instead of 2 strings and an integer I have 5 unsigned ints. I do not expect to ever be creating these objects in Python. They will only be created as return values from my wrapper functions to the 3rd party library. I could return a tuple from those functions but I want to use dot notation (e.g. somestruct.var1). So, question number 1: Is defining my own type like that overkill just to have an object to access using dots? I'll never create those objects from Python. Is there a shortcut to creating objects and setting attributes from within C? In any case, I was able to create my own custom object from C code like so... PyObject *foo(SomeCStruct bar){ PyObject *ret; ret = _PyObject_New(mymodule_SomeStructType); PyObject_SetAttrString(ret, var1 , Py_BuildValue(I, bar.var1 )); PyObject_SetAttrString(ret, var2 , Py_BuildValue(I, bar.var2 )); PyObject_SetAttrString(ret, var3 , Py_BuildValue(I, bar.var3 )); PyObject_SetAttrString(ret, var4 , Py_BuildValue(I, bar.var4 )); PyObject_SetAttrString(ret, var5 , Py_BuildValue(I, bar.var5 )); return ret; } When using _PyObject_New I notice that neither my new or init function are ever called. I verified that they are getting called when creating the object from Python (which I would never do anyway). Question number 2: Do I need to be calling PyObject_SetAttrString or is there a way to set the unsigned ints on the structure direcly? It seems overkill to create a Python object for an unsigned int just to set it as an attribute on a custom defined type. Question number 3: In the above code, is there a memory leak? Should I be Py_DECREF'ing the return value from Py_BuildValue after I'm done using it. -- http://mail.python.org/mailman/listinfo/python-list
Odd listcomp behaviour
Does anyone else consider this a bug? Python 2.6.2 (r262:71600, Jun 16 2009, 11:09:39) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type help, copyright, credits or license for more information. ---1--- skippedords = '1,2,3,4,5' ['10%s' % ii for ii in skippedords.split(',')] ['101', '102', '103', '104', '105'] ---2--- skippedords = '' ['10%s' % ii for ii in skippedords.split(',')] ['10'] ---3--- test = '' ['%s' % ii for ii in test.split() ] [] I got stung because I expected ---2--- to do what ---3--- did. Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd listcomp behaviour
On 12/17/2010 3:08 PM Emile van Sebille said... Does anyone else consider this a bug? Hmmm... looks like it's split that I've got the issue with... this is a test.split() ['this', 'is', 'a', 'test'] this is a test.split(' ') ['this', 'is', 'a', 'test'] .split(' ') [''] .split() [] Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd listcomp behaviour
Emile van Sebille wrote: Does anyone else consider this a bug? Python 2.6.2 (r262:71600, Jun 16 2009, 11:09:39) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type help, copyright, credits or license for more information. ---1--- skippedords = '1,2,3,4,5' ['10%s' % ii for ii in skippedords.split(',')] ['101', '102', '103', '104', '105'] ---2--- skippedords = '' ['10%s' % ii for ii in skippedords.split(',')] ['10'] ---3--- test = '' ['%s' % ii for ii in test.split() ] [] I got stung because I expected ---2--- to do what ---3--- did. It's stung me too (more times than I care to admit! ;), but it's not a bug. 2.5 docs: split( [sep [,maxsplit]]) Return a list of the words in the string, using sep as the delimiter string. ... Splitting an empty string with a specified separator returns ['']. If sep is not specified or is None, a different splitting algorithm is applied. ... Splitting an empty string or a string consisting of just whitespace returns an empty list. Note the bit in the second paragraph. Here's my code snippet: Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. -- test = '' -- test.split() [] -- test.split(' ') [''] -- test.split(',') [''] -- test.split(None) [] Hope this helps! ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd listcomp behaviour
On 12/17/2010 3:17 PM Emile van Sebille said... On 12/17/2010 3:08 PM Emile van Sebille said... Does anyone else consider this a bug? Hmmm... looks like it's split that I've got the issue with... Nevermind... if it's documented it's not a bug, right? Hrrmph. Emile str.split([sep[, maxsplit]])¶ Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '123'.split('') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns ['']. If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns []. For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 ']. -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen() and a .msi installer
On Fri, Dec 17, 2010 at 5:57 PM, Sebastian Alonso alon.sebast...@gmail.com wrote: Hey everyone, I'm working on a script which uses subprocess to launch a bunch of installers, but I'm getting problems with .msi installers although .exe ones work fine. The output I get is this: import subprocess p = subprocess.Popen('python.msi') Traceback (most recent call last): File pyshell#1, line 1, in module p = subprocess.Popen('python.msi') File C:\Python25\lib\subprocess.py, line 593, in __init__ errread, errwrite) File C:\Python25\lib\subprocess.py, line 793, in _execute_child startupinfo) WindowsError: [Error 8] %1 no es una aplicación Win32 válida Has this ever happen to any of you? The idea is to get this running, make it an exe (with py2exe) and use it whenever I need to install my whole development environment in the right order. Thanks in advance to all of you. Alonso Sebastian. msi files are not executables. You need to use msiexec to run them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd listcomp behaviour
On 17/12/2010 23:08, Emile van Sebille wrote: Does anyone else consider this a bug? Python 2.6.2 (r262:71600, Jun 16 2009, 11:09:39) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type help, copyright, credits or license for more information. ---1--- skippedords = '1,2,3,4,5' ['10%s' % ii for ii in skippedords.split(',')] ['101', '102', '103', '104', '105'] ---2--- skippedords = '' ['10%s' % ii for ii in skippedords.split(',')] ['10'] ---3--- test = '' ['%s' % ii for ii in test.split() ] [] I got stung because I expected ---2--- to do what ---3--- did. It's not a bug. The third example is the odd one out because it splits on a sequence of one or more (whitespace) characters and discards empty strings. For example: ',,1,,2,,'.split(',') ['', '', '1', '', '2', '', ''] ' 1 2 '.split(' ') ['', '', '1', '', '2', '', ''] # But... ' 1 2 '.split() ['1', '2'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Read / Write OpenOffice SpreadSheet ?
On 12/17/2010 4:19 AM, Torsten Mohr wrote: Hello, There is no package needed to read or write the new open document files. The files are merely a jar archive containing XML files. You can open and update them using jar as a subprocess and manipulate the XML files using your favorite XML libraries DOM/SAX/XPath/Etree/etc. thanks for your hint. I was aware of that, OO files are a bunch of zipped XML files. But, i searh for something more comfortable/highlevel that lets me just do things like doc.Cell(1, 3) = 'abc' or so. http://opendocumentfellowship.com/projects/odfpy -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Read / Write OpenOffice SpreadSheet ?
On Friday 17 December 2010, 02:07:07 Torsten Mohr wrote: Hi, i search for a possibility to access OpenOffoce SpreadSheets from Python with a reasonably new version of Python. Can anybody point me to a package that can do this? http://ooopy.sourceforge.net/ Pete -- http://mail.python.org/mailman/listinfo/python-list
PySide: Python for Qt version 1.0.0~beta2 Mineshaft gap released
The PySide team is happy to announce the second beta release of PySide: Python for Qt. New versions of some of the PySide toolchain components (API Extractor and Shiboken) have been released as well. This is a source code release only; we hope our community packagers will be providing provide binary packages shortly. To acquire the source code packages, refer to our download wiki page [1] or pull the relevant tagged versions from our git repositories [2]. Major changes since 1.0.0~beta1 === PySide now supports exposing list-like properties to QML using QDeclarativeListProperty. Documentation is still rather sparse, but refer to the example to see a how it works [3]. Other than the QML work, we have been working on fixing outstanding bugs. Since beta1, a total of 16 high-priority bugs have been fixed. See the list of fixed bugs at the end of this message. Note for Windows users == While preparing the release, we noticed at the last minute a regression that only occurs on Windows (bug 554) [4]. Due to insufficient time for fixing the bug, we decided to move forward with the release nevertheless. We will provide a separate patch for fixing the Windows regression within the next few days. Path towards 1.0 release There are still plenty of outstanding bugs in our Bugzilla [5]. To improve our quality in a controlled fashion, we plan to do probably a couple more beta releases after the current one. Due to the holiday season, the next release will be three weeks from now, but after that we'll return to two-week release cadence until 1.0. About PySide PySide is the Nokia-sponsored Python Qt bindings project, providing access to not only the complete Qt 4.7 framework but also Qt Mobility, as well as to generator tools for rapidly generating bindings for any Qt-based libraries. The PySide project is developed in the open, with all facilities you'd expect from any modern OSS project such as all code in a git repository [2], an open Bugzilla [5] for reporting bugs, and an open design process [6]. We welcome any contribution without requring a transfer of copyright. List of bugs fixed == 383 qelapsedtimer_wrapper.cpp: No such file or directory 415 phonon bindings does not build 468 Segfaults, segfaults and more segfaults 489 PySide.QtGui.QImage with string buffer argument 491 pyside doesn't respect BUILD_TESTS 500 If an instance of QPrintDialog is created a deadlock happens on shutdown. 505 CppObject was destroyed before __del__ be called 508 qmltopy1 crashes when setContextProperty is called twice without keeping a reference 512 QGridLayout::getItemPosition() is not available 513 Hardcoded bool return type for operator overloads 517 Documentation for QtDeclarative is not linked in contents.html, modules.html 518 The file genindex.html is not found (linked from contents.html) 524 Debugging errors during work of createpackage.js on windows is hard 527 Two different PySide Wikis 542 New style signals/slots + curried functions: unexpected argument during call 543 Regression: Signals with default values broken References == [1] http://developer.qt.nokia.com/wiki/PySideDownloads [2] http://qt.gitorious.org/pyside [3] http://qt.gitorious.org/pyside/pyside-examples/trees/master/examples/declarative/extending/chapter5-listproperties [4] http://bugs.openbossa.org/show_bug.cgi?id=554 [5] http://bugs.openbossa.org/ [6] http://www.pyside.org/docs/pseps/psep-0001.html -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On Fri, 17 Dec 2010 10:53:45 -0500, Steve Holden wrote about for...else: This construct appears to be unpopular in actual use, and when it comes up in classes and seminars there is always interesting debate as people discuss potential uses and realise there are useful applications. Yes, I find I don't need it often, but it is useful from time to time. I wonder whether it would have been more useful to reverse the sense of the else, and have it run only if the for loop *didn't* run to completion. That seemed more intuitive to me, and I've wanted to do this more than once. Here's a toy example: for x in sequence: if x == spam: print(exiting early) break elif x == ham: print(exiting early) break do_something(x) would become: for x in sequence: if x == spam: break elif x == ham: break do_something(x) else: print(exiting early) I think the choice of keyword is probably not Guido's crowning language achievement, but then since the English keywords don't make natural sense to those who speak other languages it's at least fair that there should be one that isn't totally natural to English speakers. A small price to pay for all the other keywords not being Dutch. Indeed :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On Fri, 17 Dec 2010 17:26:08 +, Grant Edwards wrote: Give me code that's easy-to-read and doesn't work rather code that works and can't be read any day. Well, in that case, you'll love my new operating system, written in 100% pure Python: [start code] print(this is an operating system) [end code] I expect it to rapidly make Windows, Linux and OS-X all obsolete. Bill Gates and Steve Jobs, look out! *grin* Surely your attitude towards usefulness vs. readability will depend strongly on whether you are intending to *use* the code, or *maintain* the code? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating custom types from C code
Eric Frederich, 17.12.2010 23:58: I have an extension module for a 3rd party library in which I am wrapping some structures. My initial attempt worked okay on Windows but failed on Linux. I was doing it in two parts. The first part on the C side of things I was turning the entire structure into a char array. The second part in Python code I would unpack the structure. Anyway, I decided I should be doing things a little cleaner so I read up on Defining New Types http://docs.python.org/extending/newtypes.html I got it to work but I'm not sure how to create these new objects from C. You may want to take a look at Cython. It makes writing C extensions easy. For one, it will do all sorts of type conversions for you, and do them efficiently and safely (you get an exception on overflow, for example). It's basically Python, so creating classes and instantiating them is trivial. Also note that it's generally not too much work to rewrite an existing C wrapper in Cython, but it's almost always worth it. You immediately get more maintainable code that's much easier to extend and work on. It's also often faster than hand written code. http://cython.org My setup is almost exactly like the example on that page except instead of 2 strings and an integer I have 5 unsigned ints. I do not expect to ever be creating these objects in Python. They will only be created as return values from my wrapper functions to the 3rd party library. In Cython 0.14, you can declare classes as final and internal using a decorator, meaning that they cannot be subtyped from Python and do not show up in the module dict. However, note that there is no way to prevent users from getting their hands at the type once you give them an instance. I could return a tuple from those functions but I want to use dot notation (e.g. somestruct.var1). Then __getattr__ or properties are your friend. So, question number 1: Is defining my own type like that overkill just to have an object to access using dots? Creating wrapper objects is totally normal. Also note that recent Python versions have named tuples, BTW. I'll never create those objects from Python. Is there a shortcut to creating objects and setting attributes from within C? The Cython code for instantiating classes is identical to Python. In any case, I was able to create my own custom object from C code like so... PyObject *foo(SomeCStruct bar){ PyObject *ret; ret = _PyObject_New(mymodule_SomeStructType); PyObject_SetAttrString(ret, var1 , Py_BuildValue(I, bar.var1 )); PyObject_SetAttrString(ret, var2 , Py_BuildValue(I, bar.var2 )); PyObject_SetAttrString(ret, var3 , Py_BuildValue(I, bar.var3 )); PyObject_SetAttrString(ret, var4 , Py_BuildValue(I, bar.var4 )); PyObject_SetAttrString(ret, var5 , Py_BuildValue(I, bar.var5 )); return ret; } When using _PyObject_New I notice that neither my new or init function are ever called. I verified that they are getting called when creating the object from Python Things often work a little different in Python and C. Directly calling _PyObject_New() is a lot less than what Python does internally. The canonical way is to PyObject_Call() the type (or to use one of the other call functions, depending on what your arguments are). (which I would never do anyway). Your users could do it, though, so you should make sure that won't crash the interpreter that way by leaving internal data fields uninitialised. Question number 2: Do I need to be calling PyObject_SetAttrString or is there a way to set the unsigned ints on the structure direcly? It seems overkill to create a Python object for an unsigned int just to set it as an attribute on a custom defined type. You will have to do it at some point, though, either at instantiation time or at Python access time. Depending on the expected usage, either of the two can be more wasteful. Question number 3: In the above code, is there a memory leak? Should I be Py_DECREF'ing the return value from Py_BuildValue after I'm done using it. You can look that up in the C-API docs. If a function doesn't say that it steals a reference, you still own the reference when it returns and have to manually decref it (again, a thing that you won't usually have to care about in Cython). So, yes, the above leaks one reference for each call to Py_BuildValue(). Stefan -- http://mail.python.org/mailman/listinfo/python-list
[issue10254] unicodedata.normalize('NFC', s) regression
Martin v. Löwis mar...@v.loewis.de added the comment: Am 17.12.2010 01:56, schrieb STINNER Victor: STINNER Victor victor.stin...@haypocalc.com added the comment: Ooops, sorry. I just applied the patch suggested by Marc-Andre Lemburg in msg22885 (#1054943). As the patch worked for the examples given in Unicode PRI 29 and the test suite passed, it was enough for me. I don't understand the normalization code, so I don't know how to fix it. So lacking a new patch, I think we should revert the existing change for now. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10254 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10254] unicodedata.normalize('NFC', s) regression
Martin v. Löwis mar...@v.loewis.de added the comment: So lacking a new patch, I think we should revert the existing change for now. Oops, I missed that Alexander has proposed a patch. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10254 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10254] unicodedata.normalize('NFC', s) regression
Martin v. Löwis mar...@v.loewis.de added the comment: The logic suggested by Martin in msg120018 looks right to me, but the whole code seems to be unnecessarily complex. (And comb1==comb may need to be changed to comb1=comb.) I don't understand why linear search through skipped array is needed. At the very least instead of adding their positions to the skipped list, used combining characters can be replaced by a non-character to be later skipped. The skipped array keeps track of what characters have been integrated into a base character, as they must not appear in the output. Assume you have a sequence B,C,N,C,N,B (B: base character, C: combined, N: not combined). You need to remember not to output C, whereas you still need to output N. I don't think replacing them with a non-character can work: which one would you chose (that cannot also appear in the input)? The worst case (wrt. cskipped) is the maximum number of characters that can get combined into a single base character. It used to be (and I hope still is) 20 (decomposition of U+FDFA). -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10254 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10254] unicodedata.normalize('NFC', s) regression
Martin v. Löwis mar...@v.loewis.de added the comment: Passing Part3 tests and not crashing on crash.py is probably good enough for a commit, but I don't have a proof that length 20 skipped buffer is always enough. I would agree with that. I still didn't have time to fully review the patch, but assuming it fixes the cases in msg119995, we should proceed with it. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10254 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10724] socket.close close telnet with RST
Charles-Francois Natali neolo...@free.fr added the comment: but sometimes socket.close will send TCP RST to disconnect the telnet and with wrong sequence number This is called a a half-duplex TCP close sequence. Your application is probably closing the socket while there are still data in the receive socket buffer (i.e. unread), so the TCP/IP stack sends a RST to inform the remote end that data has been lost. See RFC 1122 section 4.2.2.13. Note that in your sample capture, I don't see any invalid sequence/ack number. Your application should probably not close the connection at this time. This kind of RST will be considering as Network RST attack, and this packet will be dropped, the telnet connection will still established and cannot be closed. There you firewell is broken. Sending a RST in this context is perfectly valid. As far as I know, this issue is due to your application and firewall settings, and not to Python. Furthermore, Python just calls the underlying close(2) syscall, so even if there were an issue, it's an OS one, nothing Python could do about it. -- nosy: +neologix ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10724 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1195] Problems on Linux with Ctrl-D and Ctrl-C during raw_input
Changes by Finkregh finkr...@mafia-server.net: -- nosy: +Finkregh ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1195 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10725] Better cache instrumentation
New submission from Raymond Hettinger rhettin...@users.sourceforge.net: Nick, can you look at this? -- assignee: ncoghlan components: Library (Lib) files: sized_cache.diff keywords: patch messages: 124194 nosy: ncoghlan, rhettinger priority: normal severity: normal status: open title: Better cache instrumentation type: performance versions: Python 3.2 Added file: http://bugs.python.org/file20092/sized_cache.diff ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10725 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10716] Modernize pydoc to use CSS
Éric Araujo mer...@netwok.org added the comment: [Raymond] I'm looking for a deeper fix, all the in-line styling replaced by a stylesheet. Can you guys work together on bring this to fruition? When I talked about the CSS reset, I was referring to a precise part of the file proposed by Ron, so we’re already discussing together :-) I wonder how desirable it is to preserve the look and feel of the pages. We all agree on externalizing the CSS and add a way for the users to add their own stylesheet; why not take the opportunity to also improve the style? Huge blocks of colors are not that attractive to me :) Regarding workflow, I’d find easier to start from bare HTML that works nice (yes, I test with w3m) and then add style. Technically, I’d like to maintain the HTML as a small set of files (in pydoc_data) containing fragments of HTML with placeholders ({} or $): That’s easy to edit, to validate (a very simple script can put the fragments together) and to use. I agree that the CSS file should be as short as possible (in content), but not too short (in file size). For example, trailing commas in properties and brackets on their own line will allow nice diffs, just like Python. (I won’t have much time for Python in December, but we have a lot of time before 3.3b1 :) -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10716 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10726] pydoc: don’t display raw reST in key word help
New submission from Éric Araujo mer...@netwok.org: When one runs “pydoc with”, the output is a block of text marked up with reST. It would be more helpful to render it as text or HTML thanks to a minimal reST parser and transformer. In http://mail.python.org/pipermail/python-dev/2010-July/101563.html, Martin Geisler (Mercurial dev) said: “We're using light-weight ReST markup in the Mercurial help texts and transform it into straight text upon display in the terminal. We want no external dependencies for Mercurial, so I wrote a mini ReST parser in about 400 lines of code. It cheats a lot and can only handle simple constructs...” [A few messages later] “I would be happy to relicense it under the Python license.” So, proposed battle plan: 1) Agree this feature request is desirable. 2) Agree on the inclusion of mg’s minirst, which provides an reST parser and a plain text formatter. 3) Add an HTML formatter. 4) Wire minirst into pydoc. -- messages: 124196 nosy: eric.araujo priority: normal severity: normal status: open title: pydoc: don’t display raw reST in keyword help type: feature request versions: Python 3.3 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10726 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue2736] datetime needs an epoch method
Velko Ivanov viva...@ivanov-nest.com added the comment: I'm very disappointed by the outcome of this discussion. You are committing the biggest sin of modern times - instead of promoting the obtaining and usage of knowledge to solve things, you place restrictions to force the dumbheads into not doing mistakes. The big problem with that is that you can never foresee all usecases and all possible mistakes, thus you will always be sorrily bitten by dumbheads. What does that make of you? Let me present you a situation - I have a system that passes data via JSON, datetime object is not JSON serializable. For few other reasons, like the epoch and float secs since epoch being defacto standard, and the fact that I absolutely make sure at-the-source that my timestamps are UTC and lack zone awareness, and the fact that I'm not going to display those, but only use them for comparison, and that I'm not going to do historical things and calculations and I don't actually need nanosecond precision, just a tenth of the second, and I'm fine with always using the '' and '', not the '==', and the fact that 90% of the cases when use datetimes I have exactly the same requirements and it has always been working fine for me - I choose the lightweight float representation at the one side of the system. In the SQL DB I use tz unaware timestamps, not floats and my DB access layer returns datetime objects and I prefer them at this end of the system. So I only need to serialize the datetime object. Well, as a matter of fact I have a JSON object serialization already in place for some of my objects, but I do not need that for tz unaware datetimes. So I look for a method that makes a float from a datetime, which I'm used to in PHP, Java, .NET, C, SQL and you name it. And I'm 2 hours into reading about time, datetime and calendar modules and I still haven't even invented the obscure time.mktime(dt.timetuple())+dt.microseconds*1e-6 . And to even think that this creates a timetuple internally ? I hate it instantly and I dismiss the possibility that the API could be so wrong and I keep searching - on the internets - which brings me here where all my illusions are finally buried into the dust. 2 Hours for something, that only needs a few warning lines in the docs? Ok, the ultimately right thing is to actually serialize the datetime object and rework my other end of the system to use dt instead of float .. maybe .. but not now - now I'm only testing an idea for something completely different and I only need faithful and dutiful Python to give me a float from datetime so I can check something. I love Python for being simple, logical and consistent and for giving me the tools and not telling me what to do with them. Not today ... Today Python goes - 'Here is your hammer, but you can not use it to hit straight down. If you hit straight down, and you are using a forge, and you miss your object and hit the forge instead, the hammer could ricochet and hit you back on the forehead, so you can't use it that way. As a matter of fact, there is a gyroscopic sensor embedded in the handle of the hammer and if you try to hit with an angle that is close to 90 degrees, it will detach the head of the hammer from the handle and prevent you from eventually endangering yourself' and I'm like 'WTF??! I'm nailing a nail into a wooden plank!' Now I'm going to use the obscure one liner and hate it, because it is simply wrong and only someone that doesn't care of implementation detail might think it equal to a proper solution. The worst thing is, that I learned today, that if I ever need operations with tz aware dates and time intervals in Python, I should actually send an SQL query for that, because my DB has a clean, simple and COMPLETE date/time API that works seamlessly. Yours is a jungle and I see you being asked to include a ready made patch to output a float from a dt, to which you respond by adding a locatime() method 2 years later. You seriously think, that #9527 solves this? I don't even see a connection. With #9527 in the python library I would be exactly what I am now - overly frustrated and with the exactly same amount of time completely lost into studying a bunch of tools only to realize that I should avoid using them at all costs. I'm sorry if I offend somebody by posting this emotional message, I just try to give you another point of view - don't put restrictions and hide the reasoning. Instead, support the thing that is widespread and advise that in certain conditions there are better things to do. And if it doesn't work for some edge cases, or even for half the cases - place a well elaborated warning. Then if programmers still make the mistake - well, let them learn by it. 'Cause that's the way people learn .. they make mistakes. By preventing them from making the mistake, you actually rob them of learning. -- nosy: +vivanov ___ Python
[issue1449496] Python should use 3GB Address Space on Windows
Martin Gfeller Martin Gfeller g...@comit.ch added the comment: Martin, we're running with this for years and with many extensions modules, without an issue. What is 64-bit safe should be 32-bit safe, not only 31-bit safe. But you're right, this is not a proof, and we have switched to 64-bit ourselves. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1449496 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10724] socket.close close telnet with RST
R. David Murray rdmur...@bitdance.com added the comment: The source used to create _socket.pyd is in Modules/socketmodule.c in the source code tarball available from the python web site. As neologix says, it is a thin wrapper around the OS level socket library. -- nosy: +r.david.murray resolution: - invalid stage: - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10724 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1449496] Python should use 3GB Address Space on Windows
Amaury Forgeot d'Arc amaur...@gmail.com added the comment: What is 64-bit safe should be 32-bit safe, not only 31-bit safe Not here. Python uses signed size_t for various lengths and sizes. On win32 this only gives you 31 bits... -- nosy: +amaury.forgeotdarc ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1449496 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10726] pydoc: don’t display raw reST in key word help
R. David Murray rdmur...@bitdance.com added the comment: I'm not necessarily opposed to this, but an alternative is to modify pyspecific.py so that it generates text output from the ReST when it builds the pydoc topic index. -- components: +Demos and Tools nosy: +georg.brandl, r.david.murray ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10726 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10725] Better cache instrumentation
Antoine Pitrou pit...@free.fr added the comment: The _total_size thing looks like a wildly bad idea to me, since it's so poorly defined (and relying on a couple of special cases). Also, currsize is quite bizarre. Why not simply size? -- nosy: +pitrou ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10725 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue2736] datetime needs an epoch method
R. David Murray rdmur...@bitdance.com added the comment: Alexander, I agree with Velko in that it isn't obvious to me how the addition of localtime would answer the desire expressed in this issue. It addresses Antoine's complaint about aware datetimes, but I don't see that it does anything for the conversion to epoch based timestamp issue. That is at the very least a documentation issue, since IMO we should be providing our users with the tools they need to interoperate with the systems they need to interoperate with. Velko: on the other hand, given Victor's research, I don't see float seconds since an epoch appearing anywhere as a standard. Where do you see this being used as a standard? I also don't understand your complaint about the fact that the one-liner creates a timetuple. datetime stores the date and time information as discrete fields, so generating a timetuple is a natural conversion path. Obviously one could avoid the creation of a Python tuple by calling the C mktime directly in the C code, as has been proposed. I don't see, myself, what would be so bad about providing a 'to_crt_timestamp' method that would, in essence, be the kind of light wrapper around the system API that we provide in so many other places in Python. -- nosy: +r.david.murray ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue2736 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue2736] datetime needs an epoch method
Antoine Pitrou pit...@free.fr added the comment: Velko: on the other hand, given Victor's research, I don't see float seconds since an epoch appearing anywhere as a standard. Well, given that we already have fromtimestamp(), this sounds like a poor argument against a totimestamp() method (or whatever it gets called). -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue2736 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10726] pydoc: don’t display raw reST in key word help
Georg Brandl ge...@python.org added the comment: No need for any of that -- the output you see already is the text output from Sphinx. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10726 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10726] pydoc: don’t display raw reST in key word help
Changes by Georg Brandl ge...@python.org: -- resolution: - works for me status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10726 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9011] ast_for_factor unary minus optimization changes AST
Mark Dickinson dicki...@gmail.com added the comment: Yes, sorry; I'm not likely to find time to do anything with this. Unassigning, and downgrading priority. Is it worth leaving this open in case anyone wants to do something about it? -- assignee: mark.dickinson - priority: high - normal ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9011 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10726] pydoc: don’t display raw reST in key word help
R. David Murray rdmur...@bitdance.com added the comment: Well, in that case, can we change the text style for code and related markup to be something prettier? Normal single quotes, perhaps? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10726 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9011] ast_for_factor unary minus optimization changes AST
R. David Murray rdmur...@bitdance.com added the comment: Given the long projected lifetime of 2.7, I suppose it is. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9011 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10726] pydoc: don’t display raw reST in key word help
R. David Murray rdmur...@bitdance.com added the comment: s/prettier/more readable/ -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10726 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10726] pydoc: don’t display raw reST in key word help
Georg Brandl ge...@python.org added the comment: Sure, I can do that for the next version. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10726 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10155] Add fixups for encoding problems to wsgiref
Phillip J. Eby p...@telecommunity.com added the comment: So, do you have any suggestions for a specific change to the patch? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10155 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8754] ImportError: quote bad module name in message
Georg Brandl ge...@python.org added the comment: The change would be fine with me. What happens with the PyUnicode_FromString() usage in the patch if the string cannot be decoded? That should not lead to a UnicodeError being raised. Also, the __main__ changes look gratuitous to me. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8754 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10454] Clarify compileall command-line options
Georg Brandl ge...@python.org added the comment: +1 -- Didn't read through all of the diff, but in general I trust you enough to believe that the new version is better than the old :) -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10454 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10723] Undocumented built-in exceptions
Georg Brandl ge...@python.org added the comment: Basically fine, but the docs for indentation and tab error should document their inheritance more explicitly. -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10723 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9234] argparse: aliases for positional arguments (subparsers)
Steven Bethard steven.beth...@gmail.com added the comment: The patch looks basically okay to me, though this line makes me nervous: dest += ' (%s)' % ', '.join(aliases) Since this is just for help formatting, can't you just modify metavar instead? The dest is the attribute on the namespace where the result should be stored. The metavar is the value that should be displayed in help messages. As to where the aliases should be printed, I don't have a strong preference. The svn aliases show up when you do a generic svn help (but not if you do a svn help blame) and looks like: Available subcommands: add blame (praise, annotate, ann) ... The hg aliases show up when you do a hg help commit (but not if you do a hg help) and looks like: hg commit [OPTION]... [FILE]... aliases: ci I guess the patch makes it pretty easy to emulate the svn version. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9234 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9234] argparse: aliases for positional arguments (subparsers)
Georg Brandl ge...@python.org added the comment: I can see that this is really useful; approved for beta2 as soon as Steven's issue from the last message is handled. -- assignee: georg.brandl - bethard priority: normal - release blocker ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9234 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10559] NameError in tutorial/interpreter
Georg Brandl ge...@python.org added the comment: Use that list doesn't make me happy, what about access? -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10559 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10609] dbm documentation example doesn't work (iteritems())
Georg Brandl ge...@python.org added the comment: Why not replace it with an example that uses get() or setdefault() then? -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10609 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9938] Documentation for argparse interactive use
Steven Bethard steven.beth...@gmail.com added the comment: In the short term, just catch the SystemExit. In the slightly longer term, we could certainly provide a subclass, say, ErrorRaisingArgumentParser, that overrides .exit and .error to do nothing but raise an exception with the message they would have printed. We'd probably have to introduce a new Exception subclass though, maybe ArgumentParserExit or something like that. Anyway if you're interested in this, please file a new ticket (preferably with a patch). Regardless of whether we ever provide the subclass, we certainly need to patch the documentation to tell people how to override error and exit. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9938 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8753] Py_ReprEnter and Py_ReprLeave are undocumented
Georg Brandl ge...@python.org added the comment: Yep, looks good, please commit. -- assignee: d...@python - eric.araujo nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8753 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9264] trace.py documentation is incomplete
Georg Brandl ge...@python.org added the comment: Yes, it's the new recommended style. (Please add to documenting/ when convenient :) -- nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9264 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10559] NameError in tutorial/interpreter
R. David Murray rdmur...@bitdance.com added the comment: Attached diff provides another suggested rewording that I think is clearer. -- nosy: +r.david.murray Added file: http://bugs.python.org/file20093/tut_argv.diff ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10559 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10559] NameError in tutorial/interpreter
Georg Brandl ge...@python.org added the comment: +1. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10559 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10559] NameError in tutorial/interpreter
Changes by R. David Murray rdmur...@bitdance.com: Removed file: http://bugs.python.org/file20093/tut_argv.diff ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10559 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10559] NameError in tutorial/interpreter
Changes by R. David Murray rdmur...@bitdance.com: Added file: http://bugs.python.org/file20094/tut_argv.diff ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10559 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10559] NameError in tutorial/interpreter
R. David Murray rdmur...@bitdance.com added the comment: Committed in r87337. -- resolution: - fixed stage: patch review - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10559 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue2736] datetime needs an epoch method
Velko Ivanov viva...@ivanov-nest.com added the comment: on the other hand, given Victor's research, I don't see float seconds since an epoch appearing anywhere as a standard. Where do you see this being used as a standard? Yes, I didn't mean standard as in RFCed and recommended and dominant, sorry if it sounded that way. I meant just that it is quite common in many places, big and small. I also don't understand your complaint about the fact that the one-liner creates a timetuple. datetime stores the date and time information as discrete fields, so generating a timetuple is a natural conversion path. Well, the timetuple is not a tuple, but an object filled with attributes. It contains a few more than are required for this conversion and it doesn't contain one that is required. Therefore I really see that as an inelegant and ineffective way to do the conversion. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue2736 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8154] os.execlp('true') crashes the interpreter on 2.x
R. David Murray rdmur...@bitdance.com added the comment: OK, this went in to 2.7 without the OS conditional, and there has been no great hue and cry, so I guess it was safe enough :) As for the difference in error message between execlp and execlpe, I think that's fine. The execlpe index error message is accurate: execlpe requires an 'env' arg, and it was missing. -- resolution: - accepted stage: needs patch - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8154 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10454] Clarify compileall command-line options
R. David Murray rdmur...@bitdance.com added the comment: Committed in r87338. Backporting the relevant bits will be a bit of a pain, anyone who feels like doing it is welcome to. I may or may not get to it myself. -- resolution: - fixed stage: patch review - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10454 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8753] Py_ReprEnter and Py_ReprLeave are undocumented
Daniel Stutzbach stutzb...@google.com added the comment: Committed in r87339. Thanks everyone for the feedback! -- assignee: eric.araujo - stutzbach keywords: -needs review resolution: - accepted stage: patch review - committed/rejected status: open - closed versions: -Python 2.7 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8753 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10155] Add fixups for encoding problems to wsgiref
And Clover a...@doxdesk.com added the comment: No, not specifically. My patch is conservative about what variables it recodes, yours more liberal, but it's difficult to say which is the better approach, or what PEP requires. If you're happy with the current patch, go ahead, let's have it for 3.2; I don't foresee significant problems with it. It's unlikely anyone is going to be re-using the SSL_ or REDIRECT_ variable names for something other than what Apache uses them for. There might be some confusion from IIS users over what encoding REMOTE_USER should be in, but I can't see any consistent resolution for that issue, and we'll certainly be in a better position than we are now. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10155 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue2736] datetime needs an epoch method
Alexander Belopolsky alexander.belopol...@gmail.com added the comment: On Fri, Dec 17, 2010 at 9:18 AM, R. David Murray rep...@bugs.python.org wrote: R. David Murray rdmur...@bitdance.com added the comment: Alexander, I agree with Velko in that it isn't obvious to me how the addition of localtime would answer the desire expressed in this issue. Conversion of UTC datetime to time stamp is trivial: EPOCH = datetime(1970, 1, 1) def timestamp(t): return (t - EPOCH).total_seconds() There are several reasons not to include this one-liner in stdlib (other than it being a one-liner). 1. Different application may need different epoch and retained precision depends on the choice of the epoch. 2. The code above works only on naive datetime objects assumed to be in UTC. Passing say a result of datetime.now() to it is likely to result in a hard to find bug. 3. While it is not hard to extend the timestamp(t) code to cover aware datetime objects that use fixed offset tzinfo such as those with tzinfo set to a datetime.timezone instance, it is not well defined for the smart tzinfo implementations that do automatic DST adjustment. This is where the localtime (#9527) issue comes into play. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue2736 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue2736] datetime needs an epoch method
Antoine Pitrou pit...@free.fr added the comment: 1. Different application may need different epoch and retained precision depends on the choice of the epoch. But then why does fromtimestamp() exist? And returning a (seconds, microseconds) tuple does retain the precision. 2. The code above works only on naive datetime objects assumed to be in UTC. So, if the trivial code doesn't work, you can't bring it up as an argument against shipping this functionality, right? 3. While it is not hard to extend the timestamp(t) code to cover aware datetime objects that use fixed offset tzinfo such as those with tzinfo set to a datetime.timezone instance, it is not well defined for the smart tzinfo implementations that do automatic DST adjustment. Still, fromtimestamp() exists and apparently fulfills people's expectations. So why can't the same strategy be used for totimestamp() as well? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue2736 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue4188] Lib/threading.py causes infinite recursion when running as verbose
R. David Murray rdmur...@bitdance.com added the comment: I can confirm that the patch fixes the recursion problem if threading._VERBOSE is set to true, but the test Antoine mentioned hangs when the test suite is run. _VERBOSE is an internal, undocumented facility, so perhaps the priority on this isn't really high. On the other hand, Antoine's patch takes things from non-functional to at least partially functional, so perhaps it is worth applying as is, pending someone figuring out where the test hang is coming from. I looked in to this briefly, but I have no clue how to trigger this in a unit test, since it seems to happen when regrtest imports logging which imports threading, and appears to my threading-ignorant eyes to be tied to conditions that only exist at initial module import. -- nosy: +r.david.murray versions: -Python 2.6 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue4188 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10254] unicodedata.normalize('NFC', s) regression
Alexander Belopolsky belopol...@users.sourceforge.net added the comment: On Fri, Dec 17, 2010 at 3:47 AM, Martin v. Löwis rep...@bugs.python.org wrote: .. The worst case (wrt. cskipped) is the maximum number of characters that can get combined into a single base character. It used to be (and I hope still is) 20 (decomposition of U+FDFA). The C forms (NFC and NFKC) do canonical composition and U+FDFA is a compatibility composite. (BTW, makeunicodedata.py checks that maximum decomposed length of a character is 19, but it would be better if it would compute and define a named constant, say MAXDLENGTH, to be used instead of literal 20.) As far as I (and a two-line script) can tell the maximum length of a canonical decomposition of a character is 4. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10254 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10711] Rip out HTTP 0.9 client support
Antoine Pitrou pit...@free.fr added the comment: Patch committed in r87340. -- resolution: - fixed stage: patch review - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10711 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue4188] test_threading hang when running as verbose
Antoine Pitrou pit...@free.fr added the comment: Ok, I committed the patch in r87341 (3.2), r87342 (3.1) and r87343 (2.7). -- priority: high - normal stage: patch review - needs patch title: Lib/threading.py causes infinite recursion when running as verbose - test_threading hang when running as verbose ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue4188 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10725] Better cache instrumentation
Raymond Hettinger rhettin...@users.sourceforge.net added the comment: Updated to use ABCs but still relies on user objects implementing __sizeof__. So it is accurate whenever sys.getsizeof() is accurate. -- Added file: http://bugs.python.org/file20095/sized_cache2.diff ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10725 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com