Re: What c.l.py's opinions about Soft Exception?
On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote: > On 9 Mrz., 06:30, Steven D'Aprano <[EMAIL PROTECTED] > cybersource.com.au> wrote: > >> Hard Exceptions: terminate the program unless explicitly silenced Soft >> Exceptions: pass silently unless explicitly caught >> >> In this case, I agree with the Zen of Python ("import this"): >> >> Errors should never pass silently. >> Unless explicitly silenced. > > Exceptions in Python don't necessarily signal errors. Just think about > StopIteration. I know that. That's why I said that exceptions were used for signaling exceptional events. > Note also that the common practice of letting *possible* errors passed > silently is to return None instead of raising an exception. "Common"? Who does that? I know re.search() etc. return None in the event the regex doesn't match. That's not an error. > Moreove people create boilerplate like this > > try: >k = lst.index(elem) >... > except IndexError: >pass > > instead of > > with lst.index(elem) as k: > ... Possibly because the with keyword is quite new and many people don't know it, and much code was written before it even existed, or they have to support Python 2.4 or older. > It would be interesting to think about SoftException semantics for such > clauses: lst.index would neither raises a HardException nor does it > return None but leads to skipping the with-block. > > Is it really so exotic that it requires the demand for more use cases? Are the existing solutions really so incomplete that we need yet another solution? What problem are you trying to solve with SoftExceptions? How would changing lst.index() to raise a soft exception help here? pos = lst.index('foo') lst[pos] = 'bar' What is that code going to do if 'foo' isn't found in lst and it raises a silent, unhandled SoftException? Do you expect Python to be context sensitive, and raise HardExceptions in some places and SoftExceptions in others? Who controls that? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Mar 9, 12:05 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: > On 9 Mrz., 04:51, Lie <[EMAIL PROTECTED]> wrote: > > > A more through implementation would start from the raiser inspecting > > the execution stack and finding whether there are any try block above > > it, if no try block exist it pass silently and if one exist it will > > check whether it have a matching except clause. This also circumvents > > a problem that simple implementation have, as described below. > > This will not be easy in particular in the presence of inheritance and > dynamism. There is no way to statically decide whether an exception > BException has the type AException and will be caught by the except > clause in > > try: > BLOCK > except AException, e: > print "SoftException %s caught"%e > A feasible solution was to invert the try...except statement and > creating a continuation. > > catch AException, a: >print "SoftException A: %s"%a > catch BException , b: >print "SoftException B: %s"%b > ... > in: >BLOCK > > Here each SoftException is raised initially when a catch clause is > entered and a continuation is created that returns to the catch block > of the raised SoftException if required. When a SoftException is > raised within BLOCK a lookup will be made and if a corresponding > SoftException was found that was raised by a catch-clause the current > control flow will be suspended and the continuation is called. I'd rather want to avoid any syntax changes, as I wished that Soft Exception can be added to the language silently[1] so that new programmers doesn't _need_ to know about it (although knowing it could change the way they write codes to be more structured and simple). [1] Definition of silently: Codes that aren't aware of this functionality shouldn't break. Adding new syntax usually means adding keywords, making possible break in current program. On Mar 9, 12:30 pm, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > On Sat, 08 Mar 2008 19:51:24 -0800, Lie wrote: > > Soft Exception > > What is "Soft Exception"? > > Soft Exception is an exception that if is unhandled, pass silently as if > > nothing happened. For example, if a variable turns into NoneType, it'll > > raise Soft Exception that it have become NoneException, programmers that > > wants to handle it can handle it with a try...except block while > > programmers that doesn't care about it (or know it won't be a problem to > > his code) can just leave the code as it is. > > > Soft Exception differs from Hard Exceptions (the regular Exception) in a > > way that Hard Exception must be handled at all cost or the program will > > be terminated while Soft Exception allow programmers not to handle it if > > they don't want to. > > I don't think that there are very many cases where exceptions can be > ignored safely. There are two main reasons for using exceptions: > > (1) Signaling an exceptional event. In that case, programmers might decide whether to raise Soft or Hard Exception. Hard Exception is much preferred. > (2) An error occurred. Which must always be handled with Hard Exception. Adding another thing (3) Informing codes above it about what's currently happening inside, the thing is just a mundane report that might be useful to codes above Which might be a useful place to use SoftExceptions > I can't think of many cases where you would wish to ignore either, and > just continue processing. The only examples I can think of are in loops, > where you are doing the same thing over and over again with just a little > change, and you wish to skip any problematic data, e.g.: > > def plot_graph(func, domain): > for x in domain: > plot(x, func(x)) > > If an error occurs in plot() for one particular x value, you would want > to ignore it and go on to the next point. But that's easy enough to do > with a regular try...except block. No, you're misunderstanding the purpose of Soft Exception, it's not for silencing errors and not so much for exceptional cases. It's for the more mundane tasks such as: from __future__ import division class SomeNumeric(object): def __div__(a, b): if b == 0: raise ZeroDivisionError ## Hard Exception, don't ignore me! if a == 0: raise ZeroNumerator ## Soft Exception f = a / b i = a // b if f == float(i): raise IntegerDivision ## Soft Exception return a // b else: raise FloatDivision## Soft Exception return a / b Most people can ignore the ZeroNumerator, IntegerDivision, and FloatDivision exceptions (warnings) because they're excessive and unnecessary, but some people might want to catch them and do something else (especially ZeroNumerator). Practicle example, far below. The example is actually quite bad at demonstrating the purpose of Soft Exception as it is very simple while Soft Exception is generally more useful in complex operations. But I want to avoid giving complex examp
Trac - Does it make sense to keep http://trac.edgewall.org/ticket/4315 open?
Response to message [1] on trac.devel (as I cannot write there, due to an informally applied censorship) Mr. Boos: "I left that ticket open simply to avoid having someone to reopen it over and over..." (note to reader: this someone is me) Mr. Boos, the ticket status should reflect reality. So, if reality says "the ticket is open", no one can (should" close it. The essens of the ticket is, that you should trust you own results. You should use your development version, in order to obtain feedback. Of course I understand (seeing the terrible processes of the team), that you distrust your own results, prefering to let user do the dirty work of development-version-usage. Your inability to follow even the most rational suggestions subjecting development-processes, e.g. this one: http://trac.edgewall.org/ticket/6614#comment:36 will lead (together with the terrible quality of the trac source-code base) soon to an even more stucked development progress. Be assured that users see this (although they don't say much, like me). Do you actually realize that you're working since over a year on 0.11? Nothing is more fun that to watch the trac project running into one after another problem during development. At least you give other teams a good example of "how to ruine a good open-source product". http://case.lazaridis.com/wiki/TracAudit - To readers: The project hunts since months a memory-leak - without success. I'm wondering that python makes so much trouble in finding it. Seems to be another very fundamental reason to leave this "joke of a language" (python). - [1] http://groups.google.com/group/trac-dev/msg/1cbcaf2b5fdc8abe From: Christian Boos <[EMAIL PROTECTED]> Jeroen Ruigrok van der Werven wrote: > Does it make sense to keep http://trac.edgewall.org/ticket/4315 open? I left that ticket open simply to avoid having someone to reopen it over and over... That ticket is a bit useless in that it has anyway always been the policy of the project to run the latest stable release. And that works quite well in practice. I imagine t.e.o would already be running 0.11b1 now, if we didn't have those memory issues. As for documenting the blocker issues, doing that directly on the milestone page is more effective anyway. So I'd say let's just not make a fuss about this one and we'll close it once t.e.o gets upgraded to 0.11. -- Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Regarding coding style
On Mar 9, 3:27 am, [EMAIL PROTECTED] wrote: > To Lie: > > > Personally I preferred a code that has chosen good names but have > > little or no comments compared to codes that makes bad names and have > > Personally I don't. Show me a good one. Until you do, it's not that > I won't like it, it's that I can't. You know, in linguistics, there's > what's called 'code switching', which is switching between two > languages you know midstream. People can understand 'hear' a language > but not speak it. If you speak it, . If comments aren't > the 'short version', then patience is the problem. There's not one > word for lots and lots of things. Examples on backorder. But I much prefer it that the code has good names AND concise comments, not too short and not too long that it becomes obscure. If the code is complex, that it's hard to explain in a few sentences, it might be a good idea to refactor it. If I have to choose between bad names + twenty pages of documentation and good names + a paragraph of short documentation, I chose the latter. -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On 9 Mrz., 09:30, Lie <[EMAIL PROTECTED]> wrote: > On Mar 9, 12:05 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: > > > On 9 Mrz., 04:51, Lie <[EMAIL PROTECTED]> wrote: > > > > A more through implementation would start from the raiser inspecting > > > the execution stack and finding whether there are any try block above > > > it, if no try block exist it pass silently and if one exist it will > > > check whether it have a matching except clause. This also circumvents > > > a problem that simple implementation have, as described below. > > > This will not be easy in particular in the presence of inheritance and > > dynamism. There is no way to statically decide whether an exception > > BException has the type AException and will be caught by the except > > clause in > > > try: > > BLOCK > > except AException, e: > > print "SoftException %s caught"%e > > A feasible solution was to invert the try...except statement and > > creating a continuation. > > > catch AException, a: > >print "SoftException A: %s"%a > > catch BException , b: > >print "SoftException B: %s"%b > > ... > > in: > >BLOCK > > > Here each SoftException is raised initially when a catch clause is > > entered and a continuation is created that returns to the catch block > > of the raised SoftException if required. When a SoftException is > > raised within BLOCK a lookup will be made and if a corresponding > > SoftException was found that was raised by a catch-clause the current > > control flow will be suspended and the continuation is called. > > I'd rather want to avoid any syntax changes, as I wished that Soft > Exception can be added to the language silently[1] so that new > programmers doesn't _need_ to know about it (although knowing it could > change the way they write codes to be more structured and simple). I just tried to save your proposal from being unimplementable. Maybe you can comment on it? I know of course that syntax is Pythons holy cow but I'm not Guidos mouthpiece and have a different perspective on some aspects of the system for obvious reasons [1]. I appreciate when people in the Python community talk about what is useful for them and not what the imaginary Pythonista superego thinks about them and how it will be standardized in the end - if anyhow. I'd like to know if SoftExceptions would make programs more reliable in the end because people won't use them sparingly but for all kinds of events that are somewhat "irregular" ( i.e. warnings ) not just for obvious errors. It's an interesting idea to have an advanced warning system that is more responsive than just this kind of logging which is currently implemented. And I'd surely discriminate them from the current exception handling at least in the design phase. Later language changes could still be "dissolved". [1] http://www.fiber-space.de/EasyExtend/doc/EE.html -- http://mail.python.org/mailman/listinfo/python-list
gc question
I keep seeing destructor calls in wx for ad hoc dialogs and wonder if this is required, and if so, why would normal gc flow not be good? def GetDir(self,Caption,DefaultDir): dlg = wx.DirDialog(None,Caption,style = 1,defaultPath = DefaultDir,pos = (10,10)) res = dlg.ShowModal() pck = dialog.GetPath() dlg.Destroy() if res == wx.ID_OK: return pck else: return '' I'd like to write it as: def GetDir(self,Caption,DefaultDir): dlg = wx.DirDialog(None,Caption,style = 1,defaultPath = DefaultDir,pos = (10,10)) if dlg.ShowModal() == wx.ID_OK: return dialog.GetPath() else: return '' # probably implied; del 2 more lines? ...and gc takes care of things once scope is exited? Or is wx more tricksome than that? -- http://mail.python.org/mailman/listinfo/python-list
Re: gc question
On Mar 9, 1:51 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > On Sun, 09 Mar 2008 01:42:01 -0800, vpalexander wrote: > > I keep seeing destructor calls in wx for ad hoc dialogs and wonder if > > this is required, and if so, why would normal gc flow not be good? > > Because there is no guarantee when `__del__()` is called or if it is > called *at all*. > > Ciao, > Marc 'BlackJack' Rintsch Well, that suits me. The most unnatural thing about Python was adapting to the idea of just letting unreleased resources go jogging off wherever. :) "Where's the f.close?" "You don't need it!" Hmmm! -- http://mail.python.org/mailman/listinfo/python-list
Re: gc question
On Sun, 09 Mar 2008 01:42:01 -0800, vpalexander wrote: > I keep seeing destructor calls in wx for ad hoc dialogs and wonder if > this is required, and if so, why would normal gc flow not be good? Because there is no guarantee when `__del__()` is called or if it is called *at all*. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Arbitrary precision integer arithmetic: ceiling?
Thanks, all - you've been most helpful. By the way, what does // do? I haven't yet run down its definition in the manual. -A. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help xxx.py Program Recognition problem
On Mar 8, 9:48 am, [EMAIL PROTECTED] wrote: > Hi... > > I was using Python 2.4 and installed 2.5...I copied all my .py files > from the Python24\ root directory to the Python25\ root > directory...when I try to run them by double clicking I get: > "X.py is not a valid Win32 application"... > > Also, the files do not appear to be associated with python...? > > I can run them from IDLE...but that is it... > > How do I fix this...? > > Thanks.. > > Dave It sounds like you just want the dbl-click Explorer association ... that it should establish by default ... you can use Explorer -> Tools - > Folder Options -> File Types to indicate that you want Idle to launch .py files. Also, probably a silly question, but did you verify the download was the right Win OS version? -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
Lie wrote: [ ... ] > Soft Exception > What is "Soft Exception"? > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. For example, if a variable turns into NoneType, > it'll raise Soft Exception that it have become NoneException, > programmers that wants to handle it can handle it with a try...except > block while programmers that doesn't care about it (or know it won't > be a problem to his code) can just leave the code as it is. > > Soft Exception differs from Hard Exceptions (the regular Exception) in > a way that Hard Exception must be handled at all cost or the program > will be terminated while Soft Exception allow programmers not to > handle it if they don't want to. [ ... ] > Ideology Base: > - EAAP: Easier to apologize than to ask permission. Sort of like a COME FROM statement. Drastic effects on program execution: a `raise SoftException` in the middle of a loop would break the loop if a catcher existed, or leave the loop running if not. It would really need the ability to resume after catching an exception. You can't really talk about 'apologize' around something that's so irreparable. I'd try for this effect by creating a class of objects with well-defined callbacks. Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: Green's Function
On Mar 8, 9:46 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > "olusina eric" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > | I am new to Python and trying to solve the Hamiltonian of a linear chair > of atoms using green's function. > | Does anyone know any pre-existing library functions and literature that > could be helpful? > > Did you try searching for "Python Green's function"? I did try serching for Python "Green's function" and useful hit. Also searched on scipy with no reasonable result too. EOF -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
Lie wrote: [...] > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. [...] > Implementation: > Simple implementation might be done by catching all exceptions at the > highest level, then filtering which exceptions would be stopped (Soft > Exception) and which exceptions will be reraised and terminate the > program (Hard Exception). This is simple and can be easily implemented > but is inefficient as that means all soft exceptions must bubble > through its way to the top to find out if it is Soft or Hard. If I'm following what you want, that "simple implementation" does not work. If a function, possibly deep in a call stack, raises a soft exception that no caller above catches, what executes next? Correct me if I'm misunderstanding your idea: You want raising an un-caught soft exception to be equivalent to a 'pass'; execution continues as if the 'raise' never happened. Catching everything at a high level does nothing like that. The exception causes execution to leave the function invoking the raise statement, and abolishes the stack state from the point of the raise to the point of the catch. As Python exceptions currently work, "catching all exceptions at the highest level" is either what Python already does, or ill-defined nonsense. When an exception is uncaught, there is no useful "highest level", other than the level at which the program simply fails. Python *must* terminate execution upon an unhanded exception, because the program defined no state from which executions could correctly continue. > A more through implementation would start from the raiser inspecting > the execution stack and finding whether there are any try block above > it, if no try block exist it pass silently and if one exist it will > check whether it have a matching except clause. This also circumvents > a problem that simple implementation have, as described below. The described problems do not include the "where should execution resume" problem, which I think is central to the issue. Correct me if I've misunderstood: A "soft" exception is one that gets raised only if some calling frame has arranged to catch it. The if-exception-would-be-unhanded-then-pass logic strikes me as interesting. It would be a huge change to Python, so I doubt it will get traction here. Still, I'd say it's worth more consideration and discussion. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
The intel processor reach the very high place...
The intel processor reach the very high place... http://intelsprocessor.googlepages.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Arbitrary precision integer arithmetic: ceiling?
On Sun, 09 Mar 2008 20:57:15 +1100, Alasdair wrote: > Thanks, all - you've been most helpful. By the way, what does // do? I > haven't yet run down its definition in the manual. // is integer division. >>> 10//5 2 >>> 11//5 2 In Python 2.5 and older, / means integer division, unless you do from __future__ import division in which case / is true division, that is: >>> 10/5 2 >>> 11/5 2.5 In Python 3.x, / will always be true division, and you won't need the import. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking if a variable is a dictionary
>A protocol is just an interface that an object agrees to implement. In >your case, you would state that every object stored in your special >dict must implement the to_tagged_value method with certain agreeable >semantics. Hm... I've searched about the implementation of protocols and now (I believe) I know how to implement the iterable protocol, for instance, but have no clue about how to define my own... I'm surely not thinking the right way, but I don't seem to be able to wrap my head around the implementation details of "custom" protocols... Is it just a matter of extending the different object classes (dict, list, tuple...)? Where do you put the interface/protocol code? :-? Regards, Guillermo -- http://mail.python.org/mailman/listinfo/python-list
Re: parralel downloads
On Mar 8, 5:47 pm, Gary Herron <[EMAIL PROTECTED]> wrote: > poof65 wrote: > > For your problem you have to use threads. > > Not at all true. Thread provide one way to solve this, but another is > the select function. For this simple case, select() may (or may not) be > easier to write. Pseudo-code would look something like this: > > openSockets = list of sockets one per download file: > while openSockets: > readySockets = select(openSockets ...) # Identifies sockets with > data to be read > for each s in readSockets: > read from s and do whatever with the data > if s is at EOF: close and remove s from openSockets > > That's it. Far easier than threads. > > Gary Herron > > > You can have more information here. > >http://artfulcode.nfshost.com/files/multi-threading-in-python.html > > > On Sat, Mar 8, 2008 at 1:11 PM, John Deas <[EMAIL PROTECTED]> wrote: > > >> Hi, > > >> I would like to write a python script that will download a list of > >> files (mainly mp3s) from Internet. For this, I thought to use urllib, > >> with > > >> urlopen("myUrl").read() and then writing the resulting string to a > >> file > > >> my problem is that I would like to download several files at the time. > >> As I have not much experience in programming, could you point me the > >> easier ways to do this in python ? > > >> Thanks, > > >> JD > >> -- > >> http://mail.python.org/mailman/listinfo/python-list Thank you both for your help. Threads are working for me. However, a new problem for me is that the url I want to download are in an xml file (I want to download podcasts), and is not the same as the file downloaded: http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2BBD61E9ECD2C&ref=p_rss will be redirected to download: http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 is there a way, knowing the first url to get the second at runtime in my script ? -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Mar 9, 6:57 pm, Bryan Olson <[EMAIL PROTECTED]> wrote: > Lie wrote: > > [...]> Soft Exception is an exception that if is unhandled, pass silently as > > if nothing happened. > > [...] > > > Implementation: > > Simple implementation might be done by catching all exceptions at the > > highest level, then filtering which exceptions would be stopped (Soft > > Exception) and which exceptions will be reraised and terminate the > > program (Hard Exception). This is simple and can be easily implemented > > but is inefficient as that means all soft exceptions must bubble > > through its way to the top to find out if it is Soft or Hard. > > If I'm following what you want, that "simple implementation" does > not work. If a function, possibly deep in a call stack, raises a > soft exception that no caller above catches, what executes next? The highest possible code that could catch exceptions would have something like this: try: ## Everything is happening inside me except SoftException: pass > Correct me if I'm misunderstanding your idea: You want raising > an un-caught soft exception to be equivalent to a 'pass'; > execution continues as if the 'raise' never happened. > > Catching everything at a high level does nothing like that. The > exception causes execution to leave the function invoking the > raise statement, and abolishes the stack state from the point of > the raise to the point of the catch. The high-level mentioned here is outside our own code, it'll be inside Python's internal. When CPython (or any implementation of Python) sees that a particular exception is raised to a certain point, it'll check whether it is of type SoftException, and if it is, it'll return program state to the place where the exception is raised before. I don't know how Python's exception system works (as I tell you I know next to nothing about Python's internal, although I'm interested to know), so probably if there is any defect in the implementation schemes I mentioned, it is simply caused by my ignorance. > As Python exceptions currently work, "catching all exceptions > at the highest level" is either what Python already does, or > ill-defined nonsense. When an exception is uncaught, there is > no useful "highest level", other than the level at which the > program simply fails. Python *must* terminate execution upon > an unhanded exception, because the program defined no state > from which executions could correctly continue. That's where the difference between Soft Exceptions and Hard Exceptions lies. Soft Exception must be continued while Hard exceptions must terminate programs. Possibly this is impossible at the absolutely highest level, perhaps it should be done at the level that can guarantee > > A more through implementation would start from the raiser inspecting > > the execution stack and finding whether there are any try block above > > it, if no try block exist it pass silently and if one exist it will > > check whether it have a matching except clause. This also circumvents > > a problem that simple implementation have, as described below. > > The described problems do not include the "where should execution > resume" problem, which I think is central to the issue. I didn't mentioned it? I think it's obvious when I say: Execution should resume as if nothing happened, as if there is nothing raised, that means execution resumes at the point after the raise statement. If something was caught, execution isn't resumed and execution continues at the level of the handler (possibly we could also add a "resume" to explicitly resume the statement that was caught) > Correct me > if I've misunderstood: A "soft" exception is one that gets raised > only if some calling frame has arranged to catch it. That could be a way to implement it. And btw, that's a one-line- explanation that hits the right note (although from a different view I initially mentioned). > The if-exception-would-be-unhanded-then-pass logic strikes me as > interesting. It would be a huge change to Python, so I doubt it > will get traction here. Still, I'd say it's worth more > consideration and discussion. -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Mar 9, 4:31 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: > On 9 Mrz., 09:30, Lie <[EMAIL PROTECTED]> wrote: > > On Mar 9, 12:05 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: > > > > On 9 Mrz., 04:51, Lie <[EMAIL PROTECTED]> wrote: > > > > > A more through implementation would start from the raiser inspecting > > > > the execution stack and finding whether there are any try block above > > > > it, if no try block exist it pass silently and if one exist it will > > > > check whether it have a matching except clause. This also circumvents > > > > a problem that simple implementation have, as described below. > > > > This will not be easy in particular in the presence of inheritance and > > > dynamism. There is no way to statically decide whether an exception > > > BException has the type AException and will be caught by the except > > > clause in > > > > try: > > > BLOCK > > > except AException, e: > > > print "SoftException %s caught"%e > > > A feasible solution was to invert the try...except statement and > > > creating a continuation. > > > > catch AException, a: > > > print "SoftException A: %s"%a > > > catch BException , b: > > > print "SoftException B: %s"%b > > > ... > > > in: > > > BLOCK > > > > Here each SoftException is raised initially when a catch clause is > > > entered and a continuation is created that returns to the catch block > > > of the raised SoftException if required. When a SoftException is > > > raised within BLOCK a lookup will be made and if a corresponding > > > SoftException was found that was raised by a catch-clause the current > > > control flow will be suspended and the continuation is called. > > > I'd rather want to avoid any syntax changes, as I wished that Soft > > Exception can be added to the language silently[1] so that new > > programmers doesn't _need_ to know about it (although knowing it could > > change the way they write codes to be more structured and simple). > > I just tried to save your proposal from being unimplementable. Maybe > you can comment on it? Perhaps I'm not the appropriate person to talk about whether unchanged syntax is feasible for such implementation since I basically have no idea about how Python's internals works. It's only that I think if current syntax could be used, we could just use it (except if there is a strong reason why it shouldn't be done). > I know of course that syntax is Pythons holy cow but I'm not Guidos > mouthpiece and have a different perspective on some aspects of the > system for obvious reasons [1]. I agree, everybody have different perspective. But that differences is what makes languages evolves as it'd be continuously searching for the most optimal perspective. -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Sun, 09 Mar 2008 00:30:51 -0800, Lie wrote: > (3) Informing codes above it about what's currently happening inside, > the thing is just a mundane report that might be useful to codes above > > Which might be a useful place to use SoftExceptions Okay, now we're getting somewhere. So, I have a function foo() which raises a HardException on error, but it also raises a SoftException if it wants to notify me of something "mundane". def foo(sequence): if args == []: raise SoftException("empty list") return len(args) Now, how do I use that? try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" print x Am I close? But there's a problem. Once the SoftException is caught, execution will continue from the line "print x" -- but the function foo() never got a chance to actually return a result! In order to make that work, you would need a significant change to Python's internals. I don't know how difficult that would be, but I'm guess that it would be a lot of work for not much benefit. But even if that happened, it would mean that the one mechanism has TWO different effects: try: x = foo(sequence) except SoftException: print x # this is okay, because foo() did return except TypeError: print x # this is NOT okay, because foo() never returned That is a recipe for confusion. [...] > No, you're misunderstanding the purpose of Soft Exception, it's not for > silencing errors and not so much for exceptional cases. It's for the > more mundane tasks such as: [...] > Perhaps relabeling it as Warning, and renaming raise SoftException as > give Warning might make it more acceptable? Do you realise that Python already has a warnings module? > And I agree that the > probability for misuse is quite high, but the benefits is also quite > high, it's just that you can't see it since you're not used to using > such exceptions. The benefit of SoftExceptions lies mostly on the > regular programmings tasks, not the exceptional programming tasks > > Practical Example: > This example takes _case ideas_ from this simple gravity simulator > http://www.pygame.org/project/617/ BUT _no line of code is taken from > it_. I only give this link so you can easily know what the case is about > without lengthy explanation. > > A particle machine. > The particle machine calculates gravity created by the particles in a > field. Additionaly, it clumps together two particles that happens to be > near enough (less than the sum of their radiuses). > > The force two particle is expressing to each other is calculated with: > def calculateforce(P1, P2): > return (P1.mass - P2.mass) / distance(P1, P2) > > and this is done to every particle in the field against the current > particle. > > And the distance is calculated by: > def distance(P1, P2) > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > The problem happens when the distance is small enough and we want to > clump them together. > > A possible solution to this problem might be to check whether distance > is less than P1.radius + P2.radius in the calculateforce. But, this > obfuscate the code since we have to separate distance calculation from > the main formula (see !s), I don't agree that this obfuscates the code. > and this also insist that clumping be done on > force calculation level (see @s), shortly this piece of code is plain > bad: > def distance(P1, P2): > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > def calculateforce(P1, P2): > ## Separating this dist calculation into its own line is > ## necessary if we want to check the value of dist > ## Personally I think that's a bit obfuscated. > ## Well known formulas should be kept to one line if possible > ! dist = distance(P1, P2) > > if dist <= P1.radius + P2.radius: > ## Calling clump() here is bad, because > ## there are occasions where we only want to > ## calculate force but doesn't want to > ## clump it > @ clump(P1, P2) > else: > ! return (P1.mass - P2.mass) / dist I agree that calling clump() there is bad. > ## Codes calling calculateforce() > # Note: this code is located inside a loop > > F = calculateforce(P1, P2) > # Do something else, acceleration calculation, movement > calculations, etc > > > A better refactoring would be like this, but this requires calculating > distance twice (see !s): That's not better. Don't do it. > def distance(P1, P2): > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > def calculateforce(P1, P2): > ## Here distance is calculated once > ! return (P1.mass - P2.mass) / distance(P1, P2) > > ## Codes calling calculateforce() > # Note: this code is located inside a loop > > ## Here
Re: parralel downloads
On Mar 9, 1:25 pm, John Deas <[EMAIL PROTECTED]> wrote: > On Mar 8, 5:47 pm, Gary Herron <[EMAIL PROTECTED]> wrote: > > > > > poof65 wrote: > > > For your problem you have to use threads. > > > Not at all true. Thread provide one way to solve this, but another is > > the select function. For this simple case, select() may (or may not) be > > easier to write. Pseudo-code would look something like this: > > > openSockets = list of sockets one per download file: > > while openSockets: > > readySockets = select(openSockets ...) # Identifies sockets with > > data to be read > > for each s in readSockets: > > read from s and do whatever with the data > > if s is at EOF: close and remove s from openSockets > > > That's it. Far easier than threads. > > > Gary Herron > > > > You can have more information here. > > >http://artfulcode.nfshost.com/files/multi-threading-in-python.html > > > > On Sat, Mar 8, 2008 at 1:11 PM, John Deas <[EMAIL PROTECTED]> wrote: > > > >> Hi, > > > >> I would like to write a python script that will download a list of > > >> files (mainly mp3s) from Internet. For this, I thought to use urllib, > > >> with > > > >> urlopen("myUrl").read() and then writing the resulting string to a > > >> file > > > >> my problem is that I would like to download several files at the time. > > >> As I have not much experience in programming, could you point me the > > >> easier ways to do this in python ? > > > >> Thanks, > > > >> JD > > >> -- > > >> http://mail.python.org/mailman/listinfo/python-list > > Thank you both for your help. Threads are working for me. However, a > new problem for me is that the url I want to download are in an xml > file (I want to download podcasts), and is not the same as the file > downloaded: > > http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2... > > will be redirected to download: > > http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 > > is there a way, knowing the first url to get the second at runtime in > my script ? Found it: geturl() does the job -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking if a variable is a dictionary
On Sun, 09 Mar 2008 05:20:41 -0700, Guillermo wrote: >>A protocol is just an interface that an object agrees to implement. In >>your case, you would state that every object stored in your special dict >>must implement the to_tagged_value method with certain agreeable >>semantics. > > Hm... I've searched about the implementation of protocols and now (I > believe) I know how to implement the iterable protocol, for instance, > but have no clue about how to define my own... I'm surely not thinking > the right way, but I don't seem to be able to wrap my head around the > implementation details of "custom" protocols... Is it just a matter of > extending the different object classes (dict, list, tuple...)? Where do > you put the interface/protocol code? :-? A protocol is a convention that you insist other objects must follow, not code. To implement that convention, naturally you need to write code, but the convention makes the protocol, not the code. Some examples: To be considered a writable file, your object must include a write() method and a close() method. It doesn't matter what those methods do exactly, so long as they behave reasonably. For instance, the close() method might do nothing, and the write() method might send an SMS. To be a random-access writable file, it must also include a seek() method. To be a sequence, your object must obey the sequence protocol, which says it has a __getitem__ method which takes integer arguments starting at 0 and increasing, until it raises IndexError. You don't have to write any code to create a protocol, you just have to tell people what it is. Here's my parrot protocol: To be a parrot, your object must have a method speak() which takes an integer argument and returns the case-insensitive string "spam" repeated that many times. I'm done. I have a protocol. But if I want to actually use it, then I need an object that obeys it, and if I can't wait for somebody else to write it, I need to write one myself. So here it is: class Viking(object): def __init__(self, case='upper'): if case == 'upper': self.case = str.upper else: self.case = str.lower def speak(self, n): return self.case("spam"*n) And now Viking instances are also parrots, or rather, they obey the parrot protocol: >>> v = Viking() >>> v.speak(3) 'SPAMSPAMSPAM' I hope this helps. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: identifying and parsing string in text file
On 8 mar, 20:49, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > > I would like to identify the line by the tag (300a,0014) and then grab > the name (DoseReferenceStructureType) and value (SITE). It's obviously an XML file, so use a XML parser - there are SAX and DOM parsers in the stdlib, as well as the ElementTree module. -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
Lie schrieb: > I'm asking about people in c.l.py's opinion about a _probably_ very > Pythonic way of doing something if such features is implemented. It is > to be known that I'm not a Python expert and actually relatively new > to Python programming, so probably I'm just not thinking pythonic > enough yet or this feature might already exist somewhere in a > different name. > Anyway, I'm just asking for opinions, tell me problems I haven't > foreseen, or whether such things would be hard to implement, or > whether you think the idea is great or plain bad (and why). > > Soft Exception > What is "Soft Exception"? > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. For example, if a variable turns into NoneType, > it'll raise Soft Exception that it have become NoneException, > programmers that wants to handle it can handle it with a try...except > block while programmers that doesn't care about it (or know it won't > be a problem to his code) can just leave the code as it is. > > Soft Exception differs from Hard Exceptions (the regular Exception) in > a way that Hard Exception must be handled at all cost or the program > will be terminated while Soft Exception allow programmers not to > handle it if they don't want to. Is this soft-exception implemented anywhere, so that one can see what experiences and best practices have evolved around using it? Diez -- http://mail.python.org/mailman/listinfo/python-list
Uninstalling Eggs
I just installed the Shove module with the monumentally crap setuptools. Whilst the install succeeded, imports now trigger errors, so clearly it did not install correctly. Can I simply delete the .egg file from my lib/python2.3/site-packages/ directory? Cheers, -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking if a variable is a dictionary
Mamma mia! My head just exploded. I've seen the light. So you only need to ·want· to have a protocol? That's amazing... Far beyond the claim that Python is easy. You define protocols in writing basically! Even my grandma could have her own Python protocol. Okay, so I think I know where's the catch now -- you must rely on the fact that the protocol is implemented, there's no way to enforce it if you're expecting a parrot-like object. You'd try to call the speak() method and deal with the error if there's no such method? Thanks a lot! Guillermo -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking if a variable is a dictionary
On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote: > Okay, so I think I know where's the catch now -- you must rely on the > fact that the protocol is implemented, there's no way to enforce it if > you're expecting a parrot-like object. You'd try to call the speak() > method and deal with the error if there's no such method? That's right. That's called "duck typing" -- if all you want is something that quacks like a duck, then it doesn't matter if it actually is a duck or not. Or if you prefer: if it quacks like a duck and swims like a duck, then it's close enough to a duck as to make no difference. Sometimes though, you need to check for a parrot up front. So I'd so this: try: something.speak except AttributeError: # No speak() method, so it can't be a parrot. do_something_else() else: # It seems to follow the parrot protocol. yummy_goodness = something.speak(5) assert "spam" in yummy_goodness.lower() -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On 9 Mrz., 13:50, Lie <[EMAIL PROTECTED]> wrote: > On Mar 9, 4:31 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: > > > > > On 9 Mrz., 09:30, Lie <[EMAIL PROTECTED]> wrote: > > > On Mar 9, 12:05 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: > > > > > On 9 Mrz., 04:51, Lie <[EMAIL PROTECTED]> wrote: > > > > > > A more through implementation would start from the raiser inspecting > > > > > the execution stack and finding whether there are any try block above > > > > > it, if no try block exist it pass silently and if one exist it will > > > > > check whether it have a matching except clause. This also circumvents > > > > > a problem that simple implementation have, as described below. > > > > > This will not be easy in particular in the presence of inheritance and > > > > dynamism. There is no way to statically decide whether an exception > > > > BException has the type AException and will be caught by the except > > > > clause in > > > > > try: > > > > BLOCK > > > > except AException, e: > > > > print "SoftException %s caught"%e > > > > A feasible solution was to invert the try...except statement and > > > > creating a continuation. > > > > > catch AException, a: > > > >print "SoftException A: %s"%a > > > > catch BException , b: > > > >print "SoftException B: %s"%b > > > > ... > > > > in: > > > >BLOCK > > > > > Here each SoftException is raised initially when a catch clause is > > > > entered and a continuation is created that returns to the catch block > > > > of the raised SoftException if required. When a SoftException is > > > > raised within BLOCK a lookup will be made and if a corresponding > > > > SoftException was found that was raised by a catch-clause the current > > > > control flow will be suspended and the continuation is called. > > > > I'd rather want to avoid any syntax changes, as I wished that Soft > > > Exception can be added to the language silently[1] so that new > > > programmers doesn't _need_ to know about it (although knowing it could > > > change the way they write codes to be more structured and simple). > > > I just tried to save your proposal from being unimplementable. Maybe > > you can comment on it? > > Perhaps I'm not the appropriate person to talk about whether unchanged > syntax is feasible for such implementation since I basically have no > idea about how Python's internals works. It's only that I think if > current syntax could be used, we could just use it (except if there is > a strong reason why it shouldn't be done). You are an appropriate person to consider the workflow in a dynamic language, no matter how the language is implemented internally. Just start with function calls maybe_raise(ZeroDivisionError) The only requirement is that maybe_raise has to know when it shall raise ZeroDivisionError. This depends on whether the exception is caught. How do the program knows this in advance? There are no static analysis techniques available. When maybe_raise is entered the system must know that the exception is handled in the future. You can't inspect the call stack for this purpose because the call stack represents past events and continuations ( and you can't rely on names ). So you need something like this do_softexception(ZeroDivisionError) try: TRY_BLOCK except ZeroDivisionError: EXCEPT_BLOCK But this looks odd and the solution isn't DRY. So better one macro- transforms a new statement into this form. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a string to the most probable type
Pierre, > That's fine for people who write floats with a "." ; but others learn to > enter them with "," I have also been looking for a similar Python conversion library. One of my requirements is that such a library must be locale aware (so it can make reasonable assumptions regarding locale properties like thousands separators, decimal points, etc) - either via a locale attribute or by examining the locale of the thread its running under. Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: for-else
On Sat, Mar 08, 2008 at 04:15:31PM -0500, Terry Reedy wrote: > > I am sorry if you cannot appreciate such elegance > and can only spit on it as 'orwellian'. > I admire the elegance of your examples and your explanation. I will keep a copy of it in my Beazley, for I am afraid I have to read it again. As for orwellian, I must admit that I was quite happy when I thought of using that word, but that it was not my luckiest thought. But I have to persist in my malice. In the following snippet it is not at all clear to the naive programmer (me) that the else refers to an iterator_is_exhausted condition, whatever logical explanation you may offer. . for each_item in item_list: .do_something() . else: .do_else() My temporary solution will be to accompany this else with an appropriate comment: # exhausted e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 -- http://mail.python.org/mailman/listinfo/python-list
unable to install gdal
Hi On Windows xp sp2 and python 2.4 Yesterday I running old versions of gdal, and I try to upgrade I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 I follow install's instructions from http://trac.osgeo.org/gdal/wiki/GdalOgrInPython, all is ok, I set path and path_data variables with correct values, but whe I run a script, an error raises from osgeo import ogr File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? import _ogr ImportError: DLL load failed: process not found Also I try with instructions from http://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gdalinstall.html I move _gdal.pyd (and the others *.pyd) from my Python installation's (C:\Python24\Lib\site-packages\osgeo) into my Python installation's DLLs folder (C:\Python24\DLLs). When I run the script the error message persists. Some help is welcome. -- http://mail.python.org/mailman/listinfo/python-list
Changing the size of a Button
How do i change the size of a Button (using Tkinter), other than to set it during construction? I've found methods for getting the size but not applying them. I've been laborating with .setvar(*) but i've been unsuccessful. -- Regards Konrad Viltersten sleep- a substitute for coffee for the poor ambition - lack of sense to be lazy -- http://mail.python.org/mailman/listinfo/python-list
Returning values from function to Python shell/IPython
Hi all! I have a runTest() function inside my module, which sets up and initializes lots of objects and performs some basic tests on them. Usually (from IPython) I just write `run my_module.py`, and then `runTest()`. But sometimes I would like to manually twiddle with objects runTest creates. Is there any way I can "return" all those objects local to runTest(), and have them available in IPython (or ordinary Python shell)? Thanks... P.S. I know I can do it from a: if __name__ == '__main__': # lots of object initialization... and then have all those objects available in the interpreter. -- Karlo Lozovina -- Mosor -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning values from function to Python shell/IPython
On Sun, Mar 9, 2008 at 9:56 AM, Karlo Lozovina <[EMAIL PROTECTED]> wrote: > Hi all! > > I have a runTest() function inside my module, which sets up and initializes > lots of objects and performs some basic tests on them. Usually (from > IPython) I just write `run my_module.py`, and then `runTest()`. But > sometimes I would like to manually twiddle with objects runTest creates. Is > there any way I can "return" all those objects local to runTest(), and have > them available in IPython (or ordinary Python shell)? well after all it's a function so the only ways you can get things out of it are: - return a dict with all the objects - use global (very messy) - use a decorator to do either of the above. on the other hand have you consider using a proper test package? instead of inspecting the objects manually from the shell you could make it all automatic. with assert statements. you could use the std. python testing modules http://docs.python.org/lib/development.html or something less verbosed like nose http://code.google.com/p/python-nose/ > > Thanks... > > > P.S. > I know I can do it from a: > > if __name__ == '__main__': > # lots of object initialization... > > and then have all those objects available in the interpreter. > > -- > Karlo Lozovina -- Mosor > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
pure python hyphenator
Hi all, I'm just new to this list and I'm a musician and hobby programmer. I am busy with LilyKDE, a python plugin package for KDE's editor Kate, that makes using the LilyPond music typesetter from within Kate easier. While already busy writing a python module for breaking lyrics text (using hyphenation dicts from e.g. OpenOffice.org) I found Dr.Leo's PyHyphen. But just for fun I also continued my own plain python module, which now has it's SVN repository at: http://python-hyphenator.googlecode.com/ and it's PyPI page at: http://pypi.python.org/pypi/hyphenator . It needs more testing but seems to work nice. LilyKDE is located at http://lilykde.googlecode.com/ all the best. Guido and community: thanks for such a nice programming language, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandi -- http://mail.python.org/mailman/listinfo/python-list
Re: help on file storage for split multi part download
En Sat, 08 Mar 2008 08:27:12 -0200, <[EMAIL PROTECTED]> escribió: > On Mar 7, 2:14 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: >> En Fri, 07 Mar 2008 04:16:42 -0200, <[EMAIL PROTECTED]> escribi�: >> >> > BUT the thing thats going in my mind is thread safety. i plan to start >> > each part of the filedownloadin a different thread. and then when >> > each thread had downloaded more than 100kb (or eof or boundary >> > reached) write the buffer to the disk. can this be achieved using >> > mutex ? i have never shared objects between threads. >> >> Use a different (single) thread to write the file; the others put write >> requests on a Queue.queue object, and the writer just gets the requests >> and processes them. >> >> > is there a way to write this without using threads at all ??? >> >> Using asyncore, and perhaps the Twisted framework. > > asyncore is basically a server thing right? asyncore is usually used to build servers, because in a server you want to handle many requests with few resources, but you can use it to write a client too. Here is an example: http://effbot.org/zone/asyncore-ftp-client.htm How many files and how many simultaneous connections do you plan to handle? Using multiple threads to download and a single thread to write, connected thru a queue, looks like the "simplest thing that probably works" to me unless you have other constraints. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning values from function to Python shell/IPython
Jorge Vargas wrote: > well after all it's a function so the only ways you can get things out > of it are: > - return a dict with all the objects > - use global (very messy) > - use a decorator to do either of the above. Messy, all of those... :(. > on the other hand have you consider using a proper test package? > instead of inspecting the objects manually from the shell you could > make it all automatic. with assert statements. you could use the std. > python testing modules http://docs.python.org/lib/development.html or > something less verbosed like nose Usually, I'm using standard Python testing modules, but sometimes that is just an overkill. Sometimes I like to do 'exploratory programming', especially in the early phases of development - create a bunch of objects I want to play with and do that from IPython. Only way I found out to somewhat automate this procedure is to have a function that creates all of the test objects, and then raises an exception at the end. IPython starts ipdb, so I can work with the objects the function created (without copying them back to the shell). But this somehow looks too hack-ish for me, so I was wondering if there was an alternative... Anyway, thanks for your answer ;). -- Karlo Lozovina -- Mosor -- http://mail.python.org/mailman/listinfo/python-list
Need Help Building PythonQt on Windows
Hello, I'm creating an application using Qt (4.4 Beta atm). I have pretty close to zero experience with Python (consisting of installing the Python interpreter, downloading a python programming and executing it on the command-line). I would like to invoke a Python script from my C++ Qt program and capture its output as a C++ structure. It seems that PythonQt might be suitable for my needs. Being a Qt program, I want this thing to be cross-platform. I'm having trouble getting things set up in Windows. Has anyone had any experience with this? I've built Qt from source using the mingw32 compiler. I installed Python 2.5 binary. I am trying to build PythonQt from source. As per http://pythonqt.sourceforge.net/#Building it says I need a "developer installation" of Python containing the header files and the library files. When I look at my system after installing the Python 2.5 binary, I can see I have header files (C:\Python25\include), a 199k python25.lib (C:\Python25\libs) and a 2MB python25.dll (C:\Windows\System32\). Have I got what I need? I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts to build but then it fails: g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to `_imp__Py_NoSiteFlag' ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to `_imp__Py_NoSiteFlag' ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject': C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to `_imp___Py_NoneStruct' C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to `_imp___Py_NoneStruct' ./debug\PythonQt.o: In function `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to `_imp___Py_NoneStruct' C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to `_imp___Py_NoneStruct' ./debug\PythonQt.o: In function `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to `_imp__PyClass_Type' C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to `_imp__PyClass_Type' C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to `_imp__PyCFunction_Type' ... Since I'm new to compiling Qt with mingw and completely new to python, I was hoping for tips on why I'm getting these errors. If anyone has a better suggestion for a forum/mailing list then please let me know. Thanks, Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning values from function to Python shell/IPython
On Sun, Mar 9, 2008 at 11:07 AM, Karlo Lozovina <[EMAIL PROTECTED]> wrote: > Jorge Vargas wrote: > > > well after all it's a function so the only ways you can get things out > > of it are: > > - return a dict with all the objects > > - use global (very messy) > > - use a decorator to do either of the above. > > Messy, all of those... :(. > > > > on the other hand have you consider using a proper test package? > > instead of inspecting the objects manually from the shell you could > > make it all automatic. with assert statements. you could use the std. > > python testing modules http://docs.python.org/lib/development.html or > > something less verbosed like nose > > Usually, I'm using standard Python testing modules, but sometimes that is > just an overkill. Sometimes I like to do 'exploratory programming', > especially in the early phases of development - create a bunch of objects I > want to play with and do that from IPython. Only way I found out to > somewhat automate this procedure is to have a function that creates all of > the test objects, and then raises an exception at the end. IPython starts > ipdb, so I can work with the objects the function created (without copying > them back to the shell). But this somehow looks too hack-ish for me, so I > was wondering if there was an alternative... > ohhh if that is the case then what you are doing seems to be the optimal. Just have module lvl code ran the testing in fact I don't even put those into the if __name__, the reason is that this is just temp testing that will later become real unit testing, and will never hit a production app. it gives you the most flexibility. > Anyway, thanks for your answer ;). > welcome > > > -- > Karlo Lozovina -- Mosor > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Help Building PythonQt on Windows
Jeff Schiller schrieb: > Hello, > > I'm creating an application using Qt (4.4 Beta atm). I have pretty > close to zero experience with Python (consisting of installing the > Python interpreter, downloading a python programming and executing it > on the command-line). > > I would like to invoke a Python script from my C++ Qt program and > capture its output as a C++ structure. It seems that PythonQt might > be suitable for my needs. > > Being a Qt program, I want this thing to be cross-platform. I'm > having trouble getting things set up in Windows. Has anyone had any > experience with this? > > I've built Qt from source using the mingw32 compiler. I installed > Python 2.5 binary. I am trying to build PythonQt from source. As per > http://pythonqt.sourceforge.net/#Building it says I need a "developer > installation" of Python containing the header files and the library > files. When I look at my system after installing the Python 2.5 > binary, I can see I have header files (C:\Python25\include), a 199k > python25.lib (C:\Python25\libs) and a 2MB python25.dll > (C:\Windows\System32\). Have I got what I need? > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > to build but then it fails: > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyCFunction_Type' > ... > > Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. A few of suggestions: - take this to the PyQt mailing list (http://www.riverbankcomputing.com/mailman/listinfo/pyqt) - you only *need* pyqt if what you want to do in python has really to deal with Qt-objects - maybe "simple" embedding is enough for your needs - I don't see why you need to compile PyQt yourself at all - are you sure you can't use the stock PyQt for windows? What makes you believe you really need this to be self-compiled? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get items out of a set?
> > The intern() builtin uses this approach: > > > interned = {} > > def intern(s): > > if s in interned: > > return interned[s] > > interned[s] = s > > return s > > If you've seen it before, and have the old one, return the old one. > Do I have this straight? Right. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Help Building PythonQt on Windows
I said "PythonQt" not PyQt. That's an important distinction, I think :) See http://pythonqt.sourceforge.net/ Regards, Jeff On 3/9/08, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: > Jeff Schiller schrieb: > > > Hello, > > > > I'm creating an application using Qt (4.4 Beta atm). I have pretty > > close to zero experience with Python (consisting of installing the > > Python interpreter, downloading a python programming and executing it > > on the command-line). > > > > I would like to invoke a Python script from my C++ Qt program and > > capture its output as a C++ structure. It seems that PythonQt might > > be suitable for my needs. > > > > Being a Qt program, I want this thing to be cross-platform. I'm > > having trouble getting things set up in Windows. Has anyone had any > > experience with this? > > > > I've built Qt from source using the mingw32 compiler. I installed > > Python 2.5 binary. I am trying to build PythonQt from source. As per > > http://pythonqt.sourceforge.net/#Building it says I need a "developer > > installation" of Python containing the header files and the library > > files. When I look at my system after installing the Python 2.5 > > binary, I can see I have header files (C:\Python25\include), a 199k > > python25.lib (C:\Python25\libs) and a 2MB python25.dll > > (C:\Windows\System32\). Have I got what I need? > > > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > > to build but then it fails: > > > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > > `_imp__Py_NoSiteFlag' > > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > > `_imp__Py_NoSiteFlag' > > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > > `_imp___Py_NoneStruct' > > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > > `_imp___Py_NoneStruct' > > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > > `_imp___Py_NoneStruct' > > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > > `_imp___Py_NoneStruct' > > ./debug\PythonQt.o: In function > > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > > `_imp__PyClass_Type' > > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > > `_imp__PyClass_Type' > > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > > `_imp__PyCFunction_Type' > > ... > > > > Since I'm new to compiling Qt with mingw and completely new to python, > > I was hoping for tips on why I'm getting these errors. If anyone has > > a better suggestion for a forum/mailing list then please let me know. > > > > A few of suggestions: > > - take this to the PyQt mailing list > (http://www.riverbankcomputing.com/mailman/listinfo/pyqt) > > - you only *need* pyqt if what you want to do in python has really to > deal with Qt-objects - maybe "simple" embedding is enough for your needs > > - I don't see why you need to compile PyQt yourself at all - are you > sure you can't use the stock PyQt for windows? What makes you believe > you really need this to be self-compiled? > > Diez > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Help Building PythonQt on Windows
2008/3/9, Jeff Schiller <[EMAIL PROTECTED]>: > > Hello, I'm creating an application using Qt (4.4 Beta atm). I have pretty > close to zero experience with Python (consisting of installing the > Python interpreter, downloading a python programming and executing it > on the command-line). > > I would like to invoke a Python script from my C++ Qt program and > capture its output as a C++ structure. It seems that PythonQt might > be suitable for my needs. > > Being a Qt program, I want this thing to be cross-platform. I'm > having trouble getting things set up in Windows. Has anyone had any > experience with this? > > I've built Qt from source using the mingw32 compiler. I installed > Python 2.5 binary. I am trying to build PythonQt from source. As per > http://pythonqt.sourceforge.net/#Building it says I need a "developer > installation" of Python containing the header files and the library > files. When I look at my system after installing the Python 2.5 > binary, I can see I have header files (C:\Python25\include), a 199k > python25.lib (C:\Python25\libs) and a 2MB python25.dll > (C:\Windows\System32\). Have I got what I need? > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > to build but then it fails: > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyCFunction_Type' > ... > > Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. > > Thanks, > Jeff > > -- > http://mail.python.org/mailman/listinfo/python-list Another thing to be aware of, although this might not be something you need to worry about, is that there are debug-versions of the python libraries that are not installed by the MSI installer on windows. Sadly, the only way to get these libraries is to compile Python from source on your Windows machine, being sure to also create the debug libraries at this time. I don't know if you need them or not, because the error message you got was not entirely descriptive. ~mike -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Mar 9, 7:54 pm, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > On Sun, 09 Mar 2008 00:30:51 -0800, Lie wrote: > > (3) Informing codes above it about what's currently happening inside, > > the thing is just a mundane report that might be useful to codes above > > > Which might be a useful place to use SoftExceptions > > Okay, now we're getting somewhere. > > So, I have a function foo() which raises a HardException on error, but it > also raises a SoftException if it wants to notify me of something > "mundane". > > def foo(sequence): > if args == []: > raise SoftException("empty list") > return len(args) > > Now, how do I use that? > > try: > x = foo(something) > except TypeError: > print "you should pass a sequence" > sys.exit() # unrecoverable error > except SoftException: > print "you passed an empty list" > print x > > Am I close? > > But there's a problem. Once the SoftException is caught, execution will > continue from the line "print x" -- but the function foo() never got a > chance to actually return a result! In that particular case above, you don't need to handle the Soft Exception. As stated in it's original purpose, you don't need to handle a Soft Exception, it exists there if you need to handle the exceptional case, but ignorable on other cases. _IF_ printing the "you passed an empty list" is an important operation, you'd make it like this: try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" x = 0 print x or alternatively: try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" else: print x The case you states above only mentions that you haven't fully grasped the workflow in exception-based system. > In order to make that work, you would need a significant change to > Python's internals. I don't know how difficult that would be, but I'm > guess that it would be a lot of work for not much benefit. I too don't know how difficult that'd be, especially because the only thing I know about Python's internal is it implements its garbage collector by ref counting (which is barely useful here). > But even if that happened, it would mean that the one mechanism has TWO > different effects: > > try: > x = foo(sequence) > except SoftException: > print x # this is okay, because foo() did return > except TypeError: > print x # this is NOT okay, because foo() never returned > > That is a recipe for confusion. Both are not okay since foo() never return on both cases (soft statement doesn't return to finish the try clause except if explicitly resumed). (snip) > > Perhaps relabeling it as Warning, and renaming raise SoftException as > > give Warning might make it more acceptable? > > Do you realise that Python already has a warnings module? Ah... I completely forget about it, but anyway the Warning module is unrelated to this. Perhaps we could just think of another name, but names doesn't seems to be important in Python modules anyway, can you guess what pickle/zip/mutex/quopri/curses is if you're new to Python without looking at the documentations? There are some modules in Python that have weird names, we ought to reduce it, but we can't reduce it... we ought to live with it. (snip) > > A possible solution to this problem might be to check whether distance > > is less than P1.radius + P2.radius in the calculateforce. But, this > > obfuscate the code since we have to separate distance calculation from > > the main formula (see !s), > > I don't agree that this obfuscates the code. For a formula as complex as this: http://www.mapleprimes.com/blog/axel-vogt/computing-the-complex-gamma-function-using-spouges-formula it might be useful to fragment the formula to smaller pieces but in a simple to moderately complex that still fits in one line, fragmenting the code confuses the eye. > And here's a way to do it that doesn't calculate anything twice, and > doesn't require any exceptions: > > def calculateforce(P1, P2, dist): > return (P1.mass - P2.mass)/dist > > And then for all pairs of particles: > > dist = distance(P1, P2) > if dist <= P1.radius + P2.radius: > clump(P1, P2) > break > F = calculateforce(P1, P2, dist) That... is the worst solution that could ever be suggested. The Particle objects already contain their own position, supplying dist overrides their real distance of the particles and also it may make bug holes by supplying bogus distance: def calculateforce(P1, P2, dist): return (P1.mass - P2.mass) / dist calculateforce(P1, P2, 'bogus data') or simply by passing dist that isn't equal (P1.X - P2.X) ** 2 + (P1.Y - P2.Y) ** 2. If you want to do it that way, it'd be much better
Re: What c.l.py's opinions about Soft Exception?
On Mar 9, 9:29 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: (snip) > You are an appropriate person to consider the workflow in a dynamic > language, no matter how the language is implemented internally. I agree, but the only thing I'm not confident to talk about is how it'll be implemented, since I think an idea should suggest how it can be implemented in practice to show that it's not just a nonsense paper idea that's not possible in reality. > Just start with function calls > > maybe_raise(ZeroDivisionError) > > The only requirement is that maybe_raise has to know when it shall > raise ZeroDivisionError. This depends on whether the exception is > caught. How do the program knows this in advance? There are no static > analysis techniques available. Perhaps similar technique the compiler uses to determine whether a function is a normal function or a generator function? Positive forward lookup for any soft exceptions, which would then activate matching soft exceptions inside the code? > When maybe_raise is entered the system must know that the exception is > handled in the future. You can't inspect the call stack for this > purpose because the call stack represents past events and > continuations ( and you can't rely on names ). > > So you need something like this > > do_softexception(ZeroDivisionError) > try: > TRY_BLOCK > except ZeroDivisionError: > EXCEPT_BLOCK > > But this looks odd and the solution isn't DRY. So better one macro- > transforms a new statement into this form. -- http://mail.python.org/mailman/listinfo/python-list
Problems installing Python Imaging Library
Hi, I'm trying to install PIL from source on my CentOS 4.5 server. The build summary reports that I have everything installed... PIL 1.1.6 BUILD SUMMARY version 1.1.6 platform linux2 2.3.4 (#1, Dec 11 2007, 05:28:55) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] --- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok ... but if I try and build it I receive the following error: /usr/bin/ld: /usr/local/lib/libjpeg.a(jcparam.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC How do I fix this? I am currently running "python setup.py build" and don't understand how I would change the compiling options to add the "- fPIC" flag. I'm quite a newbie when it comes to Linux/Python so any help you could give me would be great. Thanks, Nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing the size of a Button
Hello Konrad, > How do i change the size of a Button > (using Tkinter), other than to set it > during construction? In Tkinter, usually the geometry managers (such as pack) are the ones who size the widgets. If you run something like: import Tkinter as tk root = tk.Tk() def change_size(): b["text"] = "More text" b = tk.Button(root, text="Text", command=change_size) b.pack() root.mainloop() You'll see that the button changes size to accommodate the new text. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Parse specific text in email body to CSV file
Hello, > I have been searching all over for a solution to this. I am new to > Python, so I'm a little lost. Any pointers would be a great help. I > have a couple hundred emails that contain data I would like to > incorporate into a database or CSV file. I want to search the email > for specific text. > > The emails basically look like this: > > random text _important text:_15648 random text random text random text > random text > random text random text random text _important text:_15493 random text > random text > random text random text _important text:_11674 random text random text > random text > ===Date: Wednesday March 5, 2008 > name1: 15 name5: 14 > > name2: 18 name6: 105 > > name3: 64 name7: 2 > > name4: 24 name8: 13 > > I want information like "name1: 15" to be placed into the CSV with the > name "name1" and the value "15". The same goes for the date and > "_important text:_15493". > > I would like to use this CSV or database to plot a graph with the > data. import re for match in re.finditer("_([\w ]+):_(\d+)", text): print match.groups()[0], match.groups()[1] for match in re.finditer("Date: ([^=]+)=", text): print match.groups()[0] for match in re.finditer("(\w+): (\d+)", text): print match.groups()[0], match.groups()[1] Now you have two problems :) HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
SV: Changing the size of a Button
>> How do i change the size of a Button >> (using Tkinter), other than to set it >> during construction? > In Tkinter, usually the geometry managers > (such as pack) are the ones who size the > widgets. If you run something like: >import Tkinter as tk > >root = tk.Tk() >def change_size(): >b["text"] = "More text" > >b = tk.Button(root, text="Text", command=change_size) >b.pack() > >root.mainloop() Thanks for the answer. Unfortunately, that won't help me at all, since i, apparently, asked the wrong question. Let me refrain myself. What i wish to do is to affect the size of the button but not due to change of text but due to resize of the frame it resides in. This far i've managed to get a callback to a function as the resize occurs and to print the sizes. However, i'd like to assign these values to the button so it always stays the same width as the frame. -- Regards Konrad Viltersten sleep- a substitute for coffee for the poor ambition - lack of sense to be lazy -- http://mail.python.org/mailman/listinfo/python-list
Re: gc question
On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote: > Well, that suits me. The most unnatural thing about Python was adapting > to the idea of just letting unreleased resources go jogging off > wherever. :) Yes, that's a bad habit that garbage collection can encourage. GC is good for managing memory, but not good for managing other resources, so if an object holds some other resource, it's important to make sure the resource is released in a timely fashion rather than relying on the finalizer (the __del__ function). CPython uses reference counting, so it usually destroys objects fairly soon after the stop being used. But JPython and IronPython don't do reference counting, so forgetting to clean up resources can be a significant problem. > "Where's the f.close?" > "You don't need it!" Although, you still don't need f.close, with the new with statement: with open('myfile') as f: string = f.readline() # f.close() gets called automatically here, without waiting for # garbage collection. If you want to use this in 2.5, you have to write: from __future__ import with_statement The big advantage here is that f.close will get called if the block exits normally, or if there is an exception. For more, see http://effbot.org/pyref/with.htm . -- http://mail.python.org/mailman/listinfo/python-list
[ANN] pysqlite and APSW projects moved
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Dear pysqlite users! I've moved both the pysqlite and APSW project to new homes. pysqlite web:http://oss.itsystementwicklung.de/trac/pysqlite aka http://pysqlite.org/ scm:pysqlite now uses a Mercurial repository http://oss.itsystementwicklung.de/hg/pysqlite/ APSW web:http://oss.itsystementwicklung.de/trac/apsw/ scm:Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ Both pysqlite and APSW have a common mailing list at http://itsystementwicklung.de/cgi-bin/mailman/listinfo/list-pysqlite Existing subscribers that have not set the "nomail" flag have been moved to the new list already. - -- Gerhard PS: Because of spam problems on the old Trac, I've patched AccountManager so that you will now have to verify your human-ness with a captcha when you register an account. The old Trac accounts were not moved on purpose to avoid spam. -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFH1C7tdIO4ozGCH14RAjAhAKCmxm+rKkjxMalCkH2Wjs88raxuCACgiV4B XJq+YweOK0Zh1IWHLkrl3LI= =b6zE -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: [pysqlite] [ANN] pysqlite and APSW projects moved
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Gerhard Häring wrote: > [...] APSW > > > web:http://oss.itsystementwicklung.de/trac/apsw/ > scm:Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ That should have been http://oss.itsystementwicklung.de/svn/apsw/apsw/ - -- Gerhard -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFH1DL7dIO4ozGCH14RAq4gAJ9tZuB9qcPERBkGzKEVBEx8nybfXgCeK8cX V7sH3uAskDDNBuxYG34vExI= =IXOx -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: SV: Changing the size of a Button
On Sun, 09 Mar 2008 19:45:58 +0100, K Viltersten wrote: > What i wish to do is to affect the size > of the button but not due to change of > text but due to resize of the frame it > resides in. > > This far i've managed to get a callback > to a function as the resize occurs and to > print the sizes. However, i'd like to > assign these values to the button so it > always stays the same width as the frame. Don't do it yourself, pack with the `fill` argument set to `Tkinter.X`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: SV: Changing the size of a Button
K Viltersten wrote: > What i wish to do is to affect the size > of the button but not due to change of > text but due to resize of the frame it > resides in. This is done by the layout manager, too: import Tkinter as tk root = tk.Tk() button = tk.Button(root, text="42") button.pack(fill=tk.BOTH, expand=True) root.mainloop() Alternatively, with a grid layout: button.grid(row=0, column=0, sticky="nsew") root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Help Building PythonQt on Windows
Jeff Schiller schrieb: > I said "PythonQt" not PyQt. That's an important distinction, I think :) > > See http://pythonqt.sourceforge.net/ It sure is. Sorry, didn't realize the difference. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: the way of "import"
En Sat, 08 Mar 2008 00:30:13 -0200, smalltalk <[EMAIL PROTECTED]> escribi�: > I have three files names t1.py,t2.py,t3.py in e:\test\dir1,of course > dir2 is exsit > the content of t1.py as follow: > t1.py > import os > print 'this is t1.py' > os.chdir('..\\dir2') > the content of t2.py as follow: > print "this is t2.py" > the content of t3.py as follow: > import t1 > import t2 > > > if i run t3.py in cmd of windows as follow: > python t3.py > > no errors show > > if i run t3.py in idle: import t3 > this is t1.py > Traceback (most recent call las > File "", line 1, in > File "t3.py", line 2, in > ImportError: No module named t2 > > can you give me a help? Which Python version? Which Windows version? With IDLE from Python 2.5.1 on XP I don't get the error (and that's the right thing) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: del class with recursive list
Thanks! I just need to remember to del the variables after "for in". -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
D'Aprano suggested callbacks. How does this work for you? class SomeNumeric(object): def __div__(a, b): if b == 0: raise ZeroDivisionError ## Hard Exception... if a == 0: msgboard- ZeroNumerator() f = a / b i = a // b if f == float(i): msgboard- IntegerDivision() return a // b #? return i? else: msgboard- FloatDivision() return a / b #? return f? If it works, I can write some implementations of msgboard and discuss its scope. It sounded at one point like you were augmenting control flow, but you cleared that up by saying, raise SoftException is not a true raise. Correct? There is a limit to how many behaviors you can fit in a single statement in any language. What behaviors is determined by other choices in the language design. Those choices have many consequences, some linguistic, some social, and some personal. If a dictator always makes impersonal decisions, which linguistic + social ones should he make? If the answer is, "No, we will not strike note J and K because we elected to strike notes L and M instead", then it's disappointing, but it might ease that to know what L and M are. Lastly, that notation I wrote was kind of sly. I might favor msgboard( ZeroNumerator() ) or even msgboard.add( ZeroNumerator() ). How far are you willing to come from the OP's proposal to get it to work? If they add something half-way there, but you don't get exactly what you want, is that fair? -- http://mail.python.org/mailman/listinfo/python-list
__iter__ yield
Hello! Someone knows if it's possible to make this __iter__ function with just one 'yield' intead of two? Is there some simpler way to make this __iter__ iter through all nodes? Thanks! class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): return '<'+str(self.data)+'>' def __iter__(self): yield self #1 for n in self.childs: for nn in n.__iter__(): yield nn #2 n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) for node in n: print node -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking if a variable is a dictionary
On Mar 9, 9:23 am, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote: > > Okay, so I think I know where's the catch now -- you must rely on the > > fact that the protocol is implemented, there's no way to enforce it if > > you're expecting a parrot-like object. You'd try to call the speak() > > method and deal with the error if there's no such method? > > That's right. That's called "duck typing" -- if all you want is something > that quacks like a duck, then it doesn't matter if it actually is a duck > or not. > > Or if you prefer: if it quacks like a duck and swims like a duck, then > it's close enough to a duck as to make no difference. The syntax checker over here raised a warning on this one. "So close to a duck as." (I'm using the so...as construct in my Propositional Calculus program.) > try: > something.speak > except AttributeError: > # No speak() method, so it can't be a parrot. > do_something_else() It might be a dead parrot. HAR! > else: > # It seems to follow the parrot protocol. > yummy_goodness = something.speak(5) > assert "spam" in yummy_goodness.lower() P.S. Is 'resemblant' a word? So resemblant of a duck as. -- http://mail.python.org/mailman/listinfo/python-list
Re: parralel downloads
> > > >> my problem is that I would like to download several files at the time. > > > >> As I have not much experience in programming, could you point me the > > > >> easier ways to do this in python ? > > > Thank you both for your help. Threads are working for me. However, a > > new problem for me is that the url I want to download are in an xml > > file (I want to download podcasts), and is not the same as the file > > downloaded: > > >http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2... > > > will be redirected to download: > > >http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 > > > is there a way, knowing the first url to get the second at runtime in > > my script ? > > Found it: geturl() does the job That's for normalizing schemes. I believe you subclass FancyURLopener and override the read method. -- http://mail.python.org/mailman/listinfo/python-list
Re: parralel downloads
En Sat, 08 Mar 2008 14:47:45 -0200, Gary Herron <[EMAIL PROTECTED]> escribi�: > poof65 wrote: >> For your problem you have to use threads. >> > Not at all true. Thread provide one way to solve this, but another is > the select function. For this simple case, select() may (or may not) be > easier to write. Pseudo-code would look something like this: > > openSockets = list of sockets one per download file: > while openSockets: > readySockets = select(openSockets ...) # Identifies sockets with > data to be read > for each s in readSockets: > read from s and do whatever with the data > if s is at EOF: close and remove s from openSockets > > That's it. Far easier than threads. Easier? If you omit all the relevant details, yes, looks easy. For example, you read some data from one socket, part of the file you're downloading. Where do you write it? You require additional structures to keep track of things. Pseudocode for the threaded version, complete with socket creation: def downloadfile(url, fn): s = create socket for url f = open filename for writing shutil.copyfileobj(s.makefile(), f) for each url, filename to retrieve: t = threading.Thread(target=downloadfile, args=(url,filename)) add t to threadlist t.start() for each t in threadlist: t.join() The downloadfile function looks simpler to me - it's what anyone would write in a single threaded program, with local variables and keeping full state. The above pseudocode can be converted directly into Python code - no more structures nor code are required. Of course, don't try to download a million files at the same time - neither a million sockets nor a million threads would work. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Regarding coding style
On Mar 8, 7:51 pm, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > On Sat, 08 Mar 2008 13:40:56 -0800, dave_mikesell wrote: > > On Mar 8, 2:27 pm, [EMAIL PROTECTED] wrote: > > >> Good comments are better than bad names. Good names are better than bad > >> comments. > > > If you're taking the time to write good comments, why not just fix the > > bad names? The compiler/interpreter can never, ever catch bad comments. > > Yes, but the Python compiler can only catch bad names if you do this at > the top of every module: > > import semantic_analysis > import magic.crystal_ball.read_programmers_mind dir( magic )! dir( magic.crystal_ball )? -- http://mail.python.org/mailman/listinfo/python-list
Re: Regarding coding style
On Mar 9, 4:25 am, Lie <[EMAIL PROTECTED]> wrote: > On Mar 9, 3:27 am, [EMAIL PROTECTED] wrote: > > > To Lie: > > > > Personally I preferred a code that has chosen good names but have > > > little or no comments compared to codes that makes bad names and have > > > Personally I don't. Show me a good one. Until you do, it's not that > > I won't like it, it's that I can't. You know, in linguistics, there's > > But I much prefer it that the code has good names AND concise > comments, not too short and not too long that it becomes obscure. What do you mean? If 'obscure' is the right word, then it's subjective (from metrics import obscurity?), which means that 10% of the people disagree with you, or 90% do. The end-all be-all, there is no such thing. I don't think it's obscure; I do. Is it? -- http://mail.python.org/mailman/listinfo/python-list
execute
i'm trying to execute a file without replacing the current process, but after searching the help file, documentations and the web, i can't a way of doing that. os.exec*() will close the current program. ps: by executing i mean like typing "mspaint" in run dialog.. it's not a python file -- http://mail.python.org/mailman/listinfo/python-list
1.5.2 and functools or similar
Hello, I am writing a simple delayed-call mechanism , that is causing a bit of headache. Works like this: myPrint(s) print "..." + s myTimer.add(myPrint , "hello" , 15) This means that the myprint function is called in 15 seconds with the parameter "hello". The housekeeping of these timers is called by the main loop of the "os" This works well but i would like to be able to use it with any number of parameters Functools is not a part of the 1.5.2+ python that I am running on (embedded device), so i tried to pass the parameters as a tuple like this myTimer.add(myAdder , (3,6) , 15) and the housekeeping function would then call the function like this def updateTimers() for timerItm in timerTable: ... timerItm.func(*timerItm.parameters) Works well on python 2.5 but not on 1.5.2 (?) Current solution is to have default parameters None for the add function def add( func , timeout , param1 = None , param2 = None) And the update function then checks if parameters is specified def updateTimers() for timerItm in timerTable: ... # ugly part : if timerItm.param1 is not None and timerItm.param2 is not None: timerItm.func(timerItm.param1, timerItm.param2) # two parameters elif .. timerItm.func(timerItm.param1) # one parameter else timerItm.func() # no parameters This has the implication that I can not call a function with the parameter None if I wanted to. (not a huge problem) Right now it works quite well with up to two parameters, it covers 99% of usage. If I need to call a function with more parameters, i can always write a wrapper function for it. Wondering if anyone had some sugestions ? By the way, is it bad style to check for object identity instead of value "None". What aboutt integers ? if value is 0: .. I guess it is implementation specific / could change in future versions ? Thx, Troels -- http://mail.python.org/mailman/listinfo/python-list
Logically/Selectively Sub Class?
Might be a silly question, but is it possible to selectively subclass, IE subclass is a supporting module is present and not otherwise. Regards, Kenneth Miller -- http://mail.python.org/mailman/listinfo/python-list
Re: execute
i know os.popen() but i want to execute a file with args -- http://mail.python.org/mailman/listinfo/python-list
Re: execute
ok i found a workaround. -- http://mail.python.org/mailman/listinfo/python-list
Re: Logically/Selectively Sub Class?
xkenneth schrieb: > Might be a silly question, but is it possible to selectively subclass, > IE subclass is a supporting module is present and not otherwise. Yes, something like this should work class Foo(some, base, classes) pass if condition: Temp = Foo class Foo(Temp, otherclass): pass Alternatively, you can use the type-function to create classes explicit with a list of base-classes. However it smells after bad design... what's your actual usecase? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: execute
On Sun, Mar 9, 2008 at 5:22 PM, Gif <[EMAIL PROTECTED]> wrote: > i'm trying to execute a file without replacing the current process, > but after searching the help file, documentations and the web, i can't > a way of doing that. > > os.exec*() will close the current program. > > ps: by executing i mean like typing "mspaint" in run dialog.. it's not > a python file On *nix, you can use os.fork(). According to http://effbot.org/librarybook/os.htm , you can use os.spawn to accomplish a similar effect on Windows, although I haven't used it. Also, you might check the subprocess module -- http://docs.python.org/lib/module-subprocess.html . -dan -- http://mail.python.org/mailman/listinfo/python-list
Re: 1.5.2 and functools or similar
On Mar 9, 4:26 pm, "Troels Thomsen" wrote: > Hello, > > I am writing a simple delayed-call mechanism , that is causing a bit of > headache. Works like this: > > myPrint(s) > print "..." + s > > myTimer.add(myPrint , "hello" , 15) > > This means that the myprint function is called in 15 seconds with the > parameter "hello". > The housekeeping of these timers is called by the main loop of the "os" > > This works well but i would like to be able to use it with any number of > parameters > > Functools is not a part of the 1.5.2+ python that I am running on (embedded > device), > so i tried to pass the parameters as a tuple like this > > myTimer.add(myAdder , (3,6) , 15) > > and the housekeeping function would then call the function like this > > def updateTimers() > for timerItm in timerTable: > ... > > > timerItm.func(*timerItm.parameters) > > Works well on python 2.5 but not on 1.5.2 (?) > > Current solution is to have default parameters None for the add function > > def add( func , timeout , param1 = None , param2 = None) > > And the update function then checks if parameters is specified > > def updateTimers() > for timerItm in timerTable: > ... > > > # ugly part : > if timerItm.param1 is not None and timerItm.param2 is not None: > timerItm.func(timerItm.param1, timerItm.param2) # two parameters > elif .. > timerItm.func(timerItm.param1) # one parameter > else > timerItm.func() # no parameters > > This has the implication that I can not call a function with the parameter > None if I wanted to. > (not a huge problem) > > Right now it works quite well with up to two parameters, it covers 99% of > usage. If I need to call a function with more parameters, i can always write > a wrapper function for it. Wondering if anyone had some sugestions ? > > By the way, is it bad style to check for object identity instead of value > "None". > What aboutt integers ? if value is 0: .. > I guess it is implementation specific / could change in future versions ? > > Thx, > Troels def g( arg1, arg2 ): print( arg1, arg2 ) return arg1 def h( arg1 ): print( arg1 ) return arg1 def caller( fun, *args, **kwargs ): return fun( *args, **kwargs ) print( caller( g, 'abc', 'def' ) ) print( caller( h, 'abc' ) ) ''' abc def abc abc abc ''' -- http://mail.python.org/mailman/listinfo/python-list
Re: Logically/Selectively Sub Class?
On Mar 9, 4:38 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > xkenneth schrieb: > > > Might be a silly question, but is it possible to selectively subclass, > > IE subclass is a supporting module is present and not otherwise. > > Yes, something like this should work > > class Foo(some, base, classes) > pass > > if condition: > Temp = Foo > class Foo(Temp, otherclass): pass > > Alternatively, you can use the type-function to create classes explicit > with a list of base-classes. > > However it smells after bad design... what's your actual usecase? > > Diez Yeah, it's really a non-issue, just more a curiosity. I'm using ZODB for a lot of my stuff now, and I need my objects to be persistent, however there might be a case where my classes could be used in a non- persistent manner. I'll just have ZODB as a requirement for my package. Regards, Kenneth Miller -- http://mail.python.org/mailman/listinfo/python-list
Re: Logically/Selectively Sub Class?
On Mar 9, 4:28 pm, xkenneth <[EMAIL PROTECTED]> wrote: > Might be a silly question, but is it possible to selectively subclass, > IE subclass is a supporting module is present and not otherwise. > > Regards, > Kenneth Miller if mod is present: class Waypoint( Mine, Yours ): pass else: class Waypoint( Mine ): pass class NewClass( Waypoint ). In 3.0, you can do if mod is present: bases= Mine, Yours else: bases= Mine, class NewClass( *bases ). -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
> Perhaps similar technique the compiler uses to determine whether a > function is a normal function or a generator function? Positive > forward lookup for any soft exceptions, which would then activate > matching soft exceptions inside the code? The difference between generators and functions is made on the yield-keyword. However, the exception-mechanism isn't governed by the compiler, but at runtime. You can do things like this: eclass = HardException if full_moon() else: SoftException raise eclass() Which means that you don't stand a chance determining soft-exception-usage at compiletime. What would work is most probably to register soft-exception-handlers when encountering them at runtime, thus making raising-code aware of them and execute it only if there are one (or several) present. However, IMHO it's not a worthy extension to the language - for the same reasons Steven gave. It seems only useful for tightly coupled code, not as a general mechanism. And callbacks or maybe even thread-local state are sufficient to deal with that I'd say. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Logically/Selectively Sub Class?
xkenneth schrieb: > On Mar 9, 4:38 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: >> xkenneth schrieb: >> >>> Might be a silly question, but is it possible to selectively subclass, >>> IE subclass is a supporting module is present and not otherwise. >> Yes, something like this should work >> >> class Foo(some, base, classes) >> pass >> >> if condition: >> Temp = Foo >> class Foo(Temp, otherclass): pass >> >> Alternatively, you can use the type-function to create classes explicit >> with a list of base-classes. >> >> However it smells after bad design... what's your actual usecase? >> >> Diez > > Yeah, it's really a non-issue, just more a curiosity. I'm using ZODB > for a lot of my stuff now, and I need my objects to be persistent, > however there might be a case where my classes could be used in a non- > persistent manner. I'll just have ZODB as a requirement for my > package. Ah. Then this also might work try: from ZODB import Persistent except ImportError: class Persistent: pass Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: __iter__ yield
duccio schrieb: > > Hello! > Someone knows if it's possible to make this __iter__ function with just > one 'yield' intead of two? > Is there some simpler way to make this __iter__ iter through all nodes? > Thanks! > > class Node: > def __init__(self, data=None): > self.childs=[] > self.data=data > def appendNode(self, n): > node=Node(n) > self.childs.append(node) > return node > def __str__(self): > return '<'+str(self.data)+'>' > def __iter__(self): > yield self #1 > for n in self.childs: > for nn in n.__iter__(): > yield nn #2 Nope. There have been numerous discussions about this, introducing something like a yield_all-keyword or such thing that would replace the above boilerplate - but so far they all have been rejected. Search the archives for the reasons, I don't remember them :) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Regarding coding style
> > >> Good comments are better than bad names. Good names are better than bad > > >> comments. > > > > If you're taking the time to write good comments, why not just fix the > > > bad names? The compiler/interpreter can never, ever catch bad comments. > > > Yes, but the Python compiler can only catch bad names if you do this at > > the top of every module: > > > import semantic_analysis > > import magic.crystal_ball.read_programmers_mind > > dir( magic )! > dir( magic.crystal_ball )? Someone should try annotating code with a dictionary lookup on identifiers. Anyone bored on Fridays? No one should try printing out the definitions in real-time as the code is executing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Help Building PythonQt on Windows
> Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. These symbols are all from pythonxy.dll. You need to add the corresponding import library (libpythonxy.a/pythonxy.lib) into the linker line, using a -l option. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: 1.5.2 and functools or similar
"Troels Thomsen" writes: > timerItm.func(*timerItm.parameters) > > Works well on python 2.5 but not on 1.5.2 (?) I think in 1.5.2 the *args notation wasn't present and you had to say: apply(timerItm.func, timerItm.parameters) -- http://mail.python.org/mailman/listinfo/python-list
Re: __iter__ yield
On Mar 9, 8:58 pm, duccio <[EMAIL PROTECTED]> wrote: > Someone knows if it's possible to make this __iter__ function with just > one 'yield' intead of two? > ... > def __iter__(self): > yield self #1 > for n in self.childs: > for nn in n.__iter__(): > yield nn #2 Only one yield and shorter (but not really any simpler): from itertools import chain class Node: ... def __iter__(self): for x in chain([self], *self.childs): yield x -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Distributed App - C++ with Python for Portability?
Hello! I am looking at developing an enterprise-grade distributed data sharing application - key requirements are productivity and platform portability. Will it be sensible to use C++ for performance-critical sections and Python for all the glue logic. Pls comment from your *experiences* how Python scales to large projects( > 200KLOC). I assume the C++/Python binding is fairly painless. Regards Elam. -- http://mail.python.org/mailman/listinfo/python-list
Re: execute
> > os.exec*() will close the current program. > > On *nix, you can use os.fork(). According > tohttp://effbot.org/librarybook/os.htm, you can use Do you mean, and block for the process to terminate? Or do you mean, do something else in the meantime, perhaps for a certain amount (of meantime)? [Enter event loops. Exeunt.] P.S. What do you do if you think of a comeback for something from a week ago on the newsgroup? P.P.S. Why are you thinking of comebacks on a newsgroup besides alt.flame? P.P.P.S. Anyone read alt.tasteless? -- http://mail.python.org/mailman/listinfo/python-list
Re: Beautiful Code in Python?
On Mar 2, 1:18 pm, [EMAIL PROTECTED] wrote: > On Mar 2, 12:01 pm, John DeRosa <[EMAIL PROTECTED]> wrote: > > > On Mon, 3 Mar 2008 01:23:32 +0900, js <[EMAIL PROTECTED]> wrote: > > >Hi, > > > >Have you ever seen Beautiful Python code? > > >Zope? Django? Python standard lib? or else? > > > >Please tell me what code you think it's stunning. > > > Just about any Python code I look at. > > Decorators, with, and namedtuple. Oh yeah, and variable arguments and keyword dictionaries. -- http://mail.python.org/mailman/listinfo/python-list
Re: Intra-Package References
En Sat, 08 Mar 2008 17:36:12 -0200, xkenneth <[EMAIL PROTECTED]> escribió: > Does your python module have to exist in the path in order for intra- > package references to work? No, but Python must be aware that the importing module is inside a package. So the script being executed (main) should live outside the package. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: 1.5.2 and functools or similar
"Troels Thomsen" <"nej tak..."@bag.python.org> wrote in message news:[EMAIL PROTECTED] | def updateTimers() | for timerItm in timerTable: | ... | | |timerItm.func(*timerItm.parameters) | | Works well on python 2.5 but not on 1.5.2 (?) apply(timerItm.func, timerItm.parameters) # see http://docs.python.org/lib/non-essential-built-in-funcs.html apply disappears in 3.0 tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning values from function to Python shell/IPython
> > > well after all it's a function so the only ways you can get things out > > > of it are: > > > - return a dict with all the objects > > > - use global (very messy) > > > - use a decorator to do either of the above. > > > Messy, all of those... :(. > > > > on the other hand have you consider using a proper test package? > > > instead of inspecting the objects manually from the shell you could > > > make it all automatic. with assert statements. you could use the std. > > > python testing moduleshttp://docs.python.org/lib/development.htmlor > > > something less verbosed like nose > > > Usually, I'm using standard Python testing modules, but sometimes that is > > just an overkill. Sometimes I like to do 'exploratory programming', > > especially in the early phases of development - create a bunch of objects I > > want to play with and do that from IPython. Only way I found out to > > somewhat automate this procedure is to have a function that creates all of > > the test objects, and then raises an exception at the end. IPython starts > > ipdb, so I can work with the objects the function created (without copying > > them back to the shell). But this somehow looks too hack-ish for me, so I > > was wondering if there was an alternative... > > ohhh if that is the case then what you are doing seems to be the > optimal. Just have module lvl code ran the testing in fact I don't > even put those into the if __name__, the reason is that this is just > temp testing that will later become real unit testing, and will never > hit a production app. it gives you the most flexibility. While you're at it, can you call up prior source, and edit it? BASIC had line numbers: 10 def f( a ): 20 return a+ 1 >>> 15 print( a ) 10 def f( a ): 15 print( a ) 20 return a+ 1 >>> 15 print( a ) 10 def f( a ): 15 print( a ) 20 return a+ 1 '''Interactives could some day have this too:''' >>> edit f Object f opened in editor >>> close Object f written back. Elapsed time 5 minutes. >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Mar 9, 4:51 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > > Perhaps similar technique the compiler uses to determine whether a > > function is a normal function or a generator function? Positive > > forward lookup for any soft exceptions, which would then activate > > matching soft exceptions inside the code? > > What would work is most probably to register soft-exception-handlers > when encountering them at runtime, thus making raising-code aware of > them and execute it only if there are one (or several) present. > > [HO snip] Mr. Roggisch, I just said that. You can unplonk me now. -- http://mail.python.org/mailman/listinfo/python-list
any chance regular expressions are cached?
I've got a bit of code in a function like this: s=re.sub(r'\n','\n'+spaces,s) s=re.sub(r'^',spaces,s) s=re.sub(r' *\n','\n',s) s=re.sub(r' *$','',s) s=re.sub(r'\n*$','',s) Is there any chance that these will be cached somewhere, and save me the trouble of having to declare some global re's if I don't want to have them recompiled on each function invocation? Many TIA! Mark -- Mark Harrison Pixar Animation Studios -- http://mail.python.org/mailman/listinfo/python-list
Re: parralel downloads
> > That's it. Far easier than threads. I'll order a 'easyness' metric from the warehouse. Of course, resources are parameters to the metric, such as facility given lots of time, facility given lots of libraries, facility given hot shots, &c. > Easier? If you omit all the relevant details, yes, looks easy. For > > def downloadfile(url, fn): > s = create socket for url > f = open filename for writing > shutil.copyfileobj(s.makefile(), f) > > for each url, filename to retrieve: [ threadlist.addandstart( threading.Thread(target=downloadfile, args=(url,filename)) ) ] > [ threadlist.joineach() ] > Of course, don't try to download a million files at the same time - > neither a million sockets nor a million threads would work. Dammit! Then what's my million-core machine for? If architectures "have reached the point of diminishing returns" ( off py.ideas ), then what's the PoDR for numbers of threads per core? Answer: One. Just write data structures and don't swap context. But when do you want it by? What is the PoDR for amount of effort per clock cycle saved? Get a Frank and a Brit and ask them what language is easiest to speak. (Answer: Math. Har *plonk*.) -- http://mail.python.org/mailman/listinfo/python-list
Re: any chance regular expressions are cached?
> s=re.sub(r'\n','\n'+spaces,s) > s=re.sub(r'^',spaces,s) > s=re.sub(r' *\n','\n',s) > s=re.sub(r' *$','',s) > s=re.sub(r'\n*$','',s) > > Is there any chance that these will be cached somewhere, and save > me the trouble of having to declare some global re's if I don't > want to have them recompiled on each function invocation? >>> import this ... Explicit is better than implicit ... Sounds like what you want is to use the compile() call to compile once, and then use the resulting objects: re1 = re.compile(r'\n') re2 = re.compile(r'^') ... s = re1.sub('\n' + spaces, s) s = re2.sub(spaces, s) ... The compile() should be done once (outside loops, possibly at a module level, as, in a way, they're constants) and then you can use the resulting object without the overhead of compiling. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Timed execution in eval
> > > and I want to be able to stop [functions] if they run too long. > > > That's tricky [due to a synthetic limitation]. It would suck if you couldn't hold the GIL for as long as you need to. But how much is it used? Wrote the docs: > when two threads simultaneously increment the reference count of the same > object Well, the example sucked. Just synchronize ref count manipulation. Every OS has locking primitives, and a library exists to deny requests to block that lock dead. How integral is the GIL to Python? > The Python interpreter is not fully thread safe -Make- it so. -- http://mail.python.org/mailman/listinfo/python-list
RE: any chance regular expressions are cached?
> On Behalf Of Tim Chase > Sounds like what you want is to use the compile() call to > compile once, and then use the resulting objects: > >re1 = re.compile(r'\n') >re2 = re.compile(r'^') >... >s = re1.sub('\n' + spaces, s) >s = re2.sub(spaces, s) Yes. And I would go a step further and suggest that regular expressions are best avoided in favor of simpler things when possible. That will make the code easier to debug, and probably faster. A couple of examples: >>> text = """spam spam spam spam spam spam spam""" >>> # normalize newlines >>> print "\n".join([line for line in text.splitlines() if line]) spam spam spam spam spam spam spam >>> # normalize whitespace >>> print " ".join(text.split()) spam spam spam spam spam spam spam >>> # strip leading/trailing space >>> text = " spam " >>> print text.lstrip() spam >>> print text.rstrip() spam >>> print text.strip() spam Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
Re: Timed execution in eval
> Write the docs: > > > when two threads simultaneously increment the reference count of the same > > object > > Well, the example sucked. Just synchronize ref count manipulation. > Every OS has locking primitives, and a library exists to deny requests > to block that lock dead. How integral is the GIL to Python? > > > The Python interpreter is not fully thread safe > > Make it so. Per-thread reference counts do the trick. -- http://mail.python.org/mailman/listinfo/python-list
python-2.5.2 src rpm
Hello, I am trying to install python 2.5.2 onto enterprise linux, and would like to start with a source rpm package so that I can build the package locally and make sure I have all necessary dependencies. I have been unable to locate a source rpm package for python 2.5.2 or any version of 2.5 for that matter. Any pointers would be appreciated. Donald Raikes | Accessibility Specialist Phone: +1 602 824 6213 | Fax: +1 602 824 6213 | Mobile: +1 520 271 7608 Oracle JDeveloper QA "Please consider your environmental responsibility before printing this e-mail" -- http://mail.python.org/mailman/listinfo/python-list
Re: Uninstalling Eggs
On Mar 9, 8:30 am, PB <[EMAIL PROTECTED]> wrote: > I just installed the Shove module with the monumentally crap > setuptools. Whilst the install succeeded, imports now trigger errors, > so clearly it did not install correctly. Can I simply delete the .egg > file from my lib/python2.3/site-packages/ directory? > > Cheers, Deleting the shove-egg folder is definitely the recommended and easiest way I know of to "uninstall" an egg. I've used it successfully before. Mike -- http://mail.python.org/mailman/listinfo/python-list
Python 2.5 segmentation faulting importing random
Hi, Whenever I try to import random in a python module, I get a segmentation fault. I've traced it using, import pdb pdb.set_trace() import random When it gets to.. > /usr/lib/python2.5/random.py(57)() -> LOG4 = _log(4.0) It seg faults. I'm running on OpenSuse 10.2. Linux devhost 2.6.18.8-0.7-bigsmp #1 SMP Tue Oct 2 17:21:08 UTC 2007 i686 i686 i386 GNU/Linux The python header says.. Python 2.5 (r25:51908, May 25 2007, 16:14:04) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Any ideas? Regards, Ian. -- http://mail.python.org/mailman/listinfo/python-list
Re: any chance regular expressions are cached?
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | I've got a bit of code in a function like this: | |s=re.sub(r'\n','\n'+spaces,s) |s=re.sub(r'^',spaces,s) |s=re.sub(r' *\n','\n',s) |s=re.sub(r' *$','',s) |s=re.sub(r'\n*$','',s) | | Is there any chance that these will be cached somewhere, and save | me the trouble of having to declare some global re's if I don't | want to have them recompiled on each function invocation? The last time I looked, several versions ago, re did cache. Don't know if still true. Not part of spec, I don't think. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Solve a Debate
> days_in_month 12: > 31 > 30 > 28 > 31 > ... > 30 > 31 > assign $days days_in_month[$month] > > This program consists of 2 operations (table jump and assignment) > and 12 values. This makes a memory consumption of 12+2 = 14 Along the same lines, you could populate the table somewhat sparsely, and goto a modulo key. You could even put functions in it: setreturn $endoftable hash month goto -0 -1 -2 jan.-> 3: setvjmp janfun -4 -5 apr.-> 6: setvjmp aprfun $endoftable Sweet! Are you stack-ops? -- http://mail.python.org/mailman/listinfo/python-list
Import - interpreter works but .py import does not
First post and very much a newbie to Python. Have 2.5 on Linux (GG). I think I have set up PYTHONPATH correctly in that I can import a module apply_bp and it complains about line 20 in apply_bp which is: import sys, aipy, numpy, os At the interpreter prompt, however, I can import sys, numpy etc. and can do dir() and see the entry points so I think my overall installation is OK. Why does line not work ? Also I would have thought that when I pre- imported sys et al that they would be in the symbol table so that the import line would be a noop. Thanks, Slainte, John -- http://mail.python.org/mailman/listinfo/python-list