Re: How to check the exists of a name?
On Sat, Oct 17, 2009 at 11:43 PM, StarWing wrote: > On 10月18日, 下午2时37分, Chris Rebert wrote: >> On Sat, Oct 17, 2009 at 11:30 PM, StarWing wrote: >> > Sometimes I want to make a simple flags. and i need to check there is >> > a name in current scope or not (that is, we can visit this name, no >> > matter where is it). and how to do that in python? >> >> You should avoid needing to do that in the first place. Common >> alternatives include using a dict instead of variables, depending on >> your circumstances. > > Okay... Thank you... But if I want to do that, what shall I do? > > I got a idea, use a try...except statement. there are another way to > do it ? > > (I just curious now, because I solve my problem in another way :-) Perhaps if you could explain why there's the possibility these variables might not be defined... Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check the exists of a name?
David <[email protected]> writes: > Il Sat, 17 Oct 2009 23:43:36 -0700 (PDT), StarWing ha scritto: > > > I got a idea, use a try...except statement. there are another way to > > do it ? > > > > (I just curious now, because I solve my problem in another way :-) > > locals().has_key(myname) > globals().has_key(myname) The ‘dict.has_key’ method is deprecated, and is removed in Python 3. The ‘in’ operator now works on dict objects: 'foo' in locals() 'foo' in globals() -- \ “We must become the change we want to see.” —Mahatma Gandhi | `\ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: weekdays in range
Ben Finney wrote: Jive Dadson writes: Can someone think of an easy way to calculate the number of weekdays between two calendar dates (in Python)? That depends on what you mean by “weekdays”. >>> import datetime >>> begin_date = datetime.date(2009, 10, 9) >>> end_date = datetime.date(2009, 10, 22) >>> import calendar >>> print calendar.month(2009, 10) October 2009 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 >>> end_date - begin_date datetime.timedelta(13) If you're expecting to exclude Saturday and Sunday (i.e. if you expect the above result to be 9 days instead of 13), you can use other functions of the ‘calendar’ module; try starting with: >>> friday_weekday = 4 >>> len([ ... date for date in ( ... begin_date + datetime.timedelta(days) ... for days in range((end_date - begin_date).days)) ... if calendar.weekday(date.year, date.month, date.day) <= friday_weekday]) 9 Thanks for your help. For a non-expert at Python, that last compound statement is pretty inscrutable. I am trying to scrute it. Wish me luck. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
On Saturday, 17 October 2009 16:30:55 Aahz wrote: > In article , > > Tim Rowe wrote: > >The point is that an exception causes a change in program flow, so of > >course they're used for flow control. It's what they do. The question > >is in what cases it's appropriate to use them. > > Standard Python idiom: > > try: > d[key] += value > except KeyError: > d[key] = value > > Maybe you need to re-think "appropriate". Standard Python idiom: if key in d: d[key] += value else: d[key] = value Maybe you need to re-think "appropriate". - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: a gap of do....while?
Chris Rebert wrote: On Sat, Oct 17, 2009 at 10:22 PM, StarWing wrote: okay, I think somethings dowhile is useful, but why python didn't have it? For simplicity of syntax and less duplication among the basic syntactic constructs. Less language features means less decisions to make. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check the exists of a name?
On Sat, 17 Oct 2009 23:30:02 -0700, StarWing wrote: > Sometimes I want to make a simple flags. and i need to check there is a > name in current scope or not (that is, we can visit this name, no matter > where is it). and how to do that in python? (1) Use a sentinel: myname = None # always exists ... # much later if myname is None: print "initialising myname" else: process(myname) (2) Try it and see: try: myname except NameError: print "myname does not exist" else: print "myname exists" (3) Look Before You Leap: # inside a class: 'myname' in self.__dict__ or self.__class__.__dict__ # better, because it uses inheritance and supports __slots__: hasattr(self, 'myname') # inside a function 'myname' in locals() 'myname' in globals() -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: weekdays in range
Jive Dadson writes: > Ben Finney wrote: > > >>> friday_weekday = 4 > > >>> len([ > > ... date for date in ( > > ... begin_date + datetime.timedelta(days) > > ... for days in range((end_date - begin_date).days)) > > ... if calendar.weekday(date.year, date.month, date.day) <= > > friday_weekday]) > > 9 > > > > Thanks for your help. For a non-expert at Python, that last compound > statement is pretty inscrutable. I am trying to scrute it. Wish me > luck. I'll help you by showing (liberally editing to make me look reptrospectively clever) how I built it up: >>> import datetime >>> import calendar >>> import pprint >>> begin_date = datetime.date(2009, 10, 9) >>> end_date = datetime.date(2009, 10, 22) >>> end_date - begin_date datetime.timedelta(13) >>> (end_date - begin_date).days 13 >>> range((end_date - begin_date).days) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> begin_date + datetime.timedelta(0) datetime.date(2009, 10, 9) >>> begin_date + datetime.timedelta(1) datetime.date(2009, 10, 10) >>> (begin_date + datetime.timedelta(days) ... for days in range((end_date - begin_date).days)) >>> [ ... date for date in ( ... begin_date + datetime.timedelta(days) ... for days in range((end_date - begin_date).days)) ... ] [datetime.date(2009, 10, 9), datetime.date(2009, 10, 10), datetime.date(2009, 10, 11), datetime.date(2009, 10, 12), datetime.date(2009, 10, 13), datetime.date(2009, 10, 14), datetime.date(2009, 10, 15), datetime.date(2009, 10, 16), datetime.date(2009, 10, 17), datetime.date(2009, 10, 18), datetime.date(2009, 10, 19), datetime.date(2009, 10, 20), datetime.date(2009, 10, 21)] >>> pprint.pprint([ ... date for date in ( ... begin_date + datetime.timedelta(days) ... for days in range((end_date - begin_date).days)) ... ]) [datetime.date(2009, 10, 9), datetime.date(2009, 10, 10), datetime.date(2009, 10, 11), datetime.date(2009, 10, 12), datetime.date(2009, 10, 13), datetime.date(2009, 10, 14), datetime.date(2009, 10, 15), datetime.date(2009, 10, 16), datetime.date(2009, 10, 17), datetime.date(2009, 10, 18), datetime.date(2009, 10, 19), datetime.date(2009, 10, 20), datetime.date(2009, 10, 21)] >>> len([ ... date for date in ( ... begin_date + datetime.timedelta(days) ... for days in range((end_date - begin_date).days)) ... ]) 13 >>> friday_weekday = 4 >>> calendar.weekday(begin_date.year, begin_date.month, begin_date.day) 4 >>> calendar.weekday(end_date.year, end_date.month, end_date.day) 3 >>> [ ... date for date in ( ... begin_date + datetime.timedelta(days) ... for days in range((end_date - begin_date).days)) ... if calendar.weekday(date.year, date.month, date.day) <= friday_weekday] [datetime.date(2009, 10, 9), datetime.date(2009, 10, 12), datetime.date(2009, 10, 13), datetime.date(2009, 10, 14), datetime.date(2009, 10, 15), datetime.date(2009, 10, 16), datetime.date(2009, 10, 19), datetime.date(2009, 10, 20), datetime.date(2009, 10, 21)] >>> pprint.pprint([ ... date for date in ( ... begin_date + datetime.timedelta(days) ... for days in range((end_date - begin_date).days)) ... if calendar.weekday(date.year, date.month, date.day) <= friday_weekday]) [datetime.date(2009, 10, 9), datetime.date(2009, 10, 12), datetime.date(2009, 10, 13), datetime.date(2009, 10, 14), datetime.date(2009, 10, 15), datetime.date(2009, 10, 16), datetime.date(2009, 10, 19), datetime.date(2009, 10, 20), datetime.date(2009, 10, 21)] >>> len([ ... date for date in ( ... begin_date + datetime.timedelta(days) ... for days in range((end_date - begin_date).days)) ... if calendar.weekday(date.year, date.month, date.day) <= friday_weekday]) 9 -- \ “We are all agreed that your theory is crazy. The question that | `\ divides us is whether it is crazy enough to have a chance of | _o__)being correct.” —Niels Bohr (to Wolfgang Pauli), 1958 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: weekdays in range
Wow. It's a danged tutorial. Thanks again. Take a break. -- http://mail.python.org/mailman/listinfo/python-list
Sunday 18th 12N-3P PDST Global Python Mtg - BerkeleyTIP - for forwarding
Join the global Free SW HW & Culture meeting online via VOIP & IRC. Sunday Oct 18, 12N-3P Pacific Daylight Savings Time (UTC-8), 3P-6P Eastern, (7P-10P UTC?) http://sites.google.com/site/berkeleytip/remote-attendance Or, come to the UCBerkeley Free Speech Cafe. Discuss the videos, work on your own projects & share them with others, & help work on the group projects. Get a VOIP headset, & join the #berkeleytip channel on irc.freenode.net We'll help you install VOIP client SW, & join the global meeting. Join with the meeting from your home via VOIP, or create a local meeting at your local college wifi cafe. http://sites.google.com/site/berkeleytip/schedule I finally got some posters up around campus. :) = Talk/Video October: Open Source-and-Mac Other OSs http://www.eweek.com/c/a/Linux-and-Open-Source/OpenSource-and-Mac-Alternatives-to-Windows-7-649233/ http://sites.google.com/site/berkeleytip/talk-videos = Some Topics for discussion: How get better WiFi at FSC - talk to UCB net services? FreeSwitch install on UCB box KUbuntu 9.10 out this month Plan for a UCB installfest - leaders, helpers, announcements Flyers post throughout campus beginning November? SSL & OpenVPN on UCB box = Join the mailing lists & say hi, tell us what you are interested in. http://groups.google.com/group/BerkTIPGlobal You are invited to forward this message anywhere it would be welcomed. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check the exists of a name?
On Sat, 17 Oct 2009 23:54:37 -0700, Chris Rebert wrote: > Perhaps if you could explain why there's the possibility these variables > might not be defined... If I have to support older versions of Python: try: bin except NameError: # Define my own. def bin(arg): ... But for my own variables? No way. I just make sure they're defined. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
On Sat, 17 Oct 2009 23:37:51 -0700, Paul Rubin wrote:
> Steven D'Aprano writes:
>> For the record, the four lines Paul implies are "confusing" are:
>>
>> try:
>> d[key] += value
>> except KeyError:
>> d[key] = value
>
> Consider what happens if the computation of "key" or "value" itself
> raises KeyError.
How does using a defaultdict for d save you from that problem?
table = {101: 'x', 202: 'y'}
data = {'a': 1, 'b': 2}
d = collections.defaultdict(int)
d[table[303]] += data['c']
It may not be appropriate to turn table and data into defaultdicts --
there may not be a legitimate default you can use, and the key-lookup
failure may be a fatal error. So defaultdict doesn't solve your problem.
If you need to distinguish between multiple expressions that could raise
exceptions, you can't use a single try to wrap them all. If you need to
make that distinction, then the following is no good:
try:
key = keytable[s]
value = datatable[t]
d[key] += value
except KeyError:
print "An exception occurred somewhere"
But if you need to treat all three possible KeyErrors identically, then
the above is a perfectly good solution.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
Paul Rubin wrote: Steven D'Aprano writes: For the record, the four lines Paul implies are "confusing" are: try: d[key] += value except KeyError: d[key] = value Consider what happens if the computation of "key" or "value" itself raises KeyError. Isn't key and value just a simple variables/names? Why should it ever raises KeyError? The only other error that try-block code could ever possibly throw are NameError and possibly MemoryError. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
Hendrik van Rooyen writes: > Standard Python idiom: > > if key in d: > d[key] += value > else: > d[key] = value The issue is that uses two lookups. If that's ok, the more usual idiom is: d[key] = value + d.get(key, 0) -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
Lie Ryan writes: > Paul Rubin wrote: > > Steven D'Aprano writes: > >> For the record, the four lines Paul implies are "confusing" are: > >> > >> try: > >> d[key] += value > >> except KeyError: > >> d[key] = value > > > > Consider what happens if the computation of "key" or "value" itself > > raises KeyError. > > Isn't key and value just a simple variables/names? In that example, yes. Paul is encouraging the reader to think of more complex cases where they are compound expressions, that can therefore raise other errors depending on what those expressions contain. -- \ “Don't be afraid of missing opportunities. Behind every failure | `\ is an opportunity somebody wishes they had missed.” —Jane | _o__) Wagner, via Lily Tomlin | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: restriction on sum: intentional bug?
Dieter Maurer wrote: Christian Heimes writes on Fri, 16 Oct 2009 17:58:29 +0200: Alan G Isaac schrieb: I expected this to be fixed in Python 3: sum(['ab','cd'],'') Traceback (most recent call last): File "", line 1, in TypeError: sum() can't sum strings [use ''.join(seq) instead] Of course it is not a good way to join strings, but it should work, should it not? Naturally, It's not a bug. sum() doesn't work on strings deliberately. ''.join() *is* the right and good way to concatenate strings. Apparently, "sum" special cases 'str' in order to teach people to use "join". It would have been as much work and much more friendly, to just use "join" internally to implement "sum" when this is possible. Dieter Earlier, I would have agreed with you. I assumed that this could be done invisibly, with the only difference being performance. But you can't know whether join will do the trick without error till you know that all the items are strings or Unicode strings. And you can't check that without going through the entire iterator. At that point it's too late to change your mind, as you can't back up an iterator. So the user who supplies a list with mixed strings and other stuff will get an unexpected error, one that join generates. To put it simply, I'd say that sum() should not dispatch to join() unless it could be sure that no errors might result. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: weekdays in range
Jive Dadson wrote: Wow. It's a danged tutorial. Thanks again. Take a break. Ben Finney's method is a very good approach, and an experienced Python programmer would consider it straightforward. But I have to ask whether the range of dates you might be considering could be large. For example, if you want to know how many week-days there are between a date in 1904 and 2207, it'd build a list of some 110 thousand items. There are other approaches which would be faster, consume much less memory, and be much harder to read. I'm not offering to debug it, but here's such an approach, subject to the old plus/minus one bugs. def epochweekdays (datetimeobj) """Given an arbitrary Monday long ago, figure out how many weekdays have occurred between that day and the argument""" subtract to get total_days return int(totaldays/7) * 5 + max(totaldays%7, 5) Now, your answer is just epochweekdays(b) - epochweekdays(a) DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
On Sat, 17 Oct 2009 13:12:52 +0100, Tim Rowe wrote: > 2009/10/17 Steven D'Aprano : > >> No, you have a fundamental misunderstanding. They're called exceptions, >> not errors, because they represent exceptional cases. Often errors are >> exceptional cases, but they're not the only sort of exceptional case. > > The whole reason for the mechanism, across all languages that have it, > is to deal with situations that you don't know how to deal with locally. That confuses me. If I call: y = mydict[x] how does my knowledge of what to do if x is not a key relate to whether the language raises an exception, returns an error code, dumps core, or prints "He's not the Messiah, he's a very naughty boy" to stderr? You seem to be making a distinction of *intent* which, as far as I can tell, doesn't actually exist. What's the difference in intent between these? y = mydict[x] if y == KeyErrorCode: handle_error_condition() process(y) and this? try: y = mydict[x] except KeyError: handle_error_condition() process(y) Neither assumes more or less knowledge of what to do in handle_error_condition(). Neither case assumes that the failure of x to be a key is an error: try: y = mydict[x] except KeyError: process() # working as expected else: print 'found x in dict, it shouldn't be there' sys.exit() Either way, whether the language uses error codes or exceptions, the decision of what to do in an exceptional situation is left to the user. If you'll excuse me pointing out the bleedin' obvious, there are differences between error codes and exceptions, but they aren't one of intention. Error codes put the onus on the caller to check the code after every single call which might fail (or have a buggy program), while exceptions use a framework that do most of the heavy lifting. > That's why they have the overhead that they do. Exceptions don't have one common overhead across all languages that use them. They have different overhead in different languages -- they're very heavyweight in C++ and Java, but lightweight in Python. The Perl Exception::Base module claims to be lightweight. The overhead of exceptions is related to the implementation of the language. >> Python uses exceptions for flow control: > > Yes, and in some cases I think that's a serious language wart. Not > enough to put me off the language, but a serious wart nevertheless. I disagree with that. I think exceptions are a beautiful and powerful way of dealing with flow control, much better than returning a special code, and much better than having to check some status function or global variable, as so often happens in C. They're more restricted, and therefore safer, than goto. They're not a panacea but they're very useful. >> Similarly, it's hardly an *error* for [1, 2, 3].index(5) to fail -- who >> is to say that the list is supposed to have 5 in it? ValueError (a >> slightly misleading name in this situation) is used to indicate an >> exceptional, but not unexpected, occurrence. > > That one is, I think, a legitimate use of an exception. The result > returned by index is defined if the index is in bounds. If not, index > doesn't know whether it was supposed to be in bounds or not, and so > can't handle the case locally. It could suggest an error or merely > (IMHO) poor programming. Because index cannot know what the proper > action is, an exception is the appropriate response. I think you're confused about what list.index(obj) does. You seem to me to be assuming that [1,2,3].index(5) should return the item in position 5 of the list, and since there isn't one (5 is out of bounds), raise an exception. But that's not what it does. It searches the list and returns the position at which 5 is found. Of course list.index() could have returned an error code instead, like str.find() does. But str also has an index() method, which raises an exception -- when handling strings, you can Look Before You Leap or Ask For Forgiveness Instead Of Permission, whichever you prefer. >> Likewise, KeyboardInterrupt is used to allow the user to halt >> processing; SystemExit is used to shut down the Python virtual machine; >> and warnings are implemented using exceptions. > > Again, I think it's fair to treat a program being killed from outside as > an exception as far as the program is concerned. No, it's not being killed from outside the program -- it's being *interrupted* from *inside* the program by the user. What you do in response to that interrupt is up to you -- it doesn't necessarily mean "kill the program". If you kill the program from outside, using (say) kill or the TaskManager or something, you don't necessarily get an exception. With kill -9 on POSIX systems you won't get anything, because the OS will just yank the carpet out from under your program's feet and then drop a safe on it to be sure. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: print()
Il Sat, 17 Oct 2009 10:38:55 -0400, Dave Angel ha scritto:
> mattia wrote:
>> Il Fri, 16 Oct 2009 22:40:34 -0700, Dennis Lee Bieber ha scritto:
>>
>>
>>> On Fri, 16 Oct 2009 23:39:38 -0400, Dave Angel
>>> declaimed the following in gmane.comp.python.general:
>>>
>>>
>>>
You're presumably testing this in the interpreter, which prints extra
stuff. In particular, it prints the result value of any expressions
entered at the interpreter prompt. So if you type
sys.stdout.write("hello")
then after the write() method is done, the return value of the method
(5) will get printed by the interpreter.
>>> I was about to respond that way myself, but before doing so I
>>>
>> wanted
>>
>>> to produce an example in the interpreter window... But no effect?
>>>
>>> C:\Documents and Settings\Dennis Lee Bieber>python ActivePython
>>> 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911,
>>> Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on win32 Type
>>> "help", "copyright", "credits" or "license" for more information.
>>>
>> import sys
>> sys.stdout.write("hello")
>>
>>> hello>>>
>>>
>>>
>>> PythonWin 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit
>>> (Intel)] on win32.
>>> Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin'
>>> for further copyright information.
>>>
>> import sys
>> sys.stdout.write("This is a test")
>>
>>> This is a test
>>>
>> print sys.stdout.write("Hello")
>>
>>> HelloNone
>>>
>>>
>>> No count shows up... neither PythonWin or Windows command line/
>>>
>> shell
>>
>> Indeed I'm using py3. But now everythong is fine. Everything I just
>> wanted to know was just to run this simple script (I've also sent the
>> msg 'putchar(8)' to the newsgroup):
>>
>> import time
>> import sys
>>
>> val = ("|", "/", "-", "\\", "|", "/", "-", "\\") for i in range(100+1):
>> print("=", end="")
>> # print("| ", end="")
>> print(val[i%len(val)], " ", sep="", end="") print(i, "%", sep="",
>> end="")
>> sys.stdout.flush()
>> time.sleep(0.1)
>> if i > 9:
>> print("\x08"*5, " "*5, "\x08"*5, sep="", end="")
>> else:
>> print("\x08"*4, " "*4, "\x08"*4, sep="", end="")
>> print(" 100%\nDownload complete!")
>>
>>
> Seems to me you're spending too much energy defeating the things that
> print() is automatically doing for you. The whole point of write() is
> that it doesn't do anything but ship your string to the file/device. So
> if you want control, do your own formatting.
>
> Consider:
>
> import time, sys, itertools
>
> val = ("|", "/", "-", "\\", "|", "/", "-", "\\") sys.stdout.write("
> ")
> pattern = "\x08"*8 + " {0}{1:02d}%" for percentage, string in
> enumerate(itertools.cycle(val)):
> if percentage>99 : break
> paddednum = pattern.format(string, percentage)
> sys.stdout.write(paddednum)
> sys.stdout.flush()
> time.sleep(0.1)
> print("\x08\x08\x08\x08 100%\nDownload complete!")
>
>
> Note the use of cycle() which effectively repeats a list indefinitely.
> And enumerate, which makes an index for you automatically when you're
> iterating through a list. And str.format() that builds our string,
> including using 0 padding so the percentages are always two digits.
>
>
> DaveA
It's always good to learn something new, thanks!
--
http://mail.python.org/mailman/listinfo/python-list
Re: print()
Il Sat, 17 Oct 2009 10:02:27 -0400, Dave Angel ha scritto:
> mattia wrote:
>> Il Fri, 16 Oct 2009 21:04:08 +, mattia ha scritto:
>>
>>
>>> Is there a way to print to an unbuffered output (like stdout)? I've
>>> seen that something like sys.stdout.write("hello") works but it also
>>> prints the number of characters!
>>>
>>>
>> Another question (always py3). How can I print only the first number
>> after the comma of a division?
>> e.g. print(8/3) --> 2.667
>> I just want 2.6 (or 2.66)
>>
>> Thanks, Mattia
>>
>>
> Just as sys.stdout.write() is preferable to print() for your previous
> question, understanding str.format() is important to having good control
> over what your output looks like. It's certainly not the only way, but
> the docs seem to say it's the preferred way in version 3.xIt was
> introduced in 2.6, so there are other approaches you might want if you
> need to work in 2.5 or earlier.
>
> x = 8/3
> dummy0=dummy1=dummy2=42
> s = "The answer is approx. {3:07.2f} after rounding".format(dummy0,
> dummy1, dummy2, x)
> print(s)
>
>
> will print out the following:
>
> The answer is approx. 0002.67 after rounding
>
> A brief explanation of the format string {3:07.2f} is as follows:
> 3 selects argument 3 of the function, which is x 0 means to
> zero-fill the value after conversion 7 means 7 characters total
> width (this helps determine who many
> zeroes are inserted)
> 2 means 2 digits after the decimal
> f means fixed point format
>
> You can generally leave out the parts you don't need, but this gives you
> lots of control over what things should look like. There are lots of
> other parts, but this is most of what you might need for controlled
> printing of floats.
>
> The only difference from what you asked is that this rounds, where you
> seemed (!) to be asking for truncation of the extra columns. If you
> really need to truncate, I'd recommend using str() to get a string, then
> use index() to locate the decimal separator, and then slice it yourself.
>
> DaveA
Yes, reading the doc I've come up with
s = "%(0)03.02f%(1)s done" % {"0": 100.0-100.0*(size/tot), "1": "%"}
but to it is not a good idea to use a dict here..
--
http://mail.python.org/mailman/listinfo/python-list
Re: print()
On Oct 18, 12:35 pm, mattia wrote:
> Yes, reading the doc I've come up with
> s = "%(0)03.02f%(1)s done" % {"0": 100.0-100.0*(size/tot), "1": "%"}
> but to it is not a good idea to use a dict here..
Also look at the new str.format()
--
http://mail.python.org/mailman/listinfo/python-list
dav caldav webdav
I want to write a script to add events to a groupware calendar. I am using sogo and i have a test server tom play with. I want to be able to script a process of accessing a file of ~10^5 events into a calendaring system so that I can prepopulate a load of calendars with the users' timetables at the beginning of an academic year. It does not seem to be too difficult according to some > 2009/10/6 Helge Hess > > On 06.10.2009, at 09:35, Brian Lockwood wrote: >> >>> In order to use Python to do bulk calendar updates I need the API for the >>> Python libraries involved. Any idea where I can find them? >>> Brian >>> >> >> http://caldav.calconnect.org/implementations/librariestools.html >> >> But you can also just use httplib and contruct/parse the PROPFINDs >> manually. Not that hard. Helge may be correct but I need a little more help to get started. I have come to the conclusion that I need a library with an appropriate api and have found zanshin. It would be incredibly helpful to find some code snippets or examples or an api to help get started on this. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tracking down DLL load errors in Windows ?
Fred P said : > Hi, a bit of platform-specific advice sought here... I'm trying to > diagnose one of those mysteries Windows is so fond of... > Say that I have code that imports some binary Python module from site- > packages (in this case, libpyexiv2.pyd through pyexiv2.py, could be > anythng else). > On three Windows boxes I've tried it (XP Pro or Home, Python 2.5) > everything works fine. On a fourth, importing the module fails with a > traceback like this : > Traceback (most recent call last): > File "", line 1, in > File "c:\python\lib\site-packages\pyexiv2.py", line 60, in > import libpyexiv2 > ImportError: DLL load failed: This application could not start > because its configuration is incorrect. Reinstalling it might solve > the problem. > I have tried long and hard to spot a meaningful difference between the > first three systems and the last, without success. > Is there any tool and/or methodology I could use to at least pinpoint > the exact DLL that libpyexiv2 is failing to load, and ideally also the > reason why ?... Thanks to Mark and Christian : dependency-walker confirmed the VC++ issue. After installing the MS redistributable DLL package -- actually I had to install *three* before hitting the right one (2005SP1) -- libpyexiv2 finally loads all its dependencies. Of course I've still no idea why/how it ran on the first three systems (and most others, from the look of it) without doing anything, and not on this one... but at least now it works :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: More & More Fun w/ Pics & MySQL
Thank you all. I have __no__idea__ why the link I sent you, that you tested,
__didn't__ work for me. Was it a problem with the browser? Why did it render
other images fine? Strange! Well, glad it works *today*. Hopefully it'll
work tomorrow, when I try and pick up a check from my client!
Regarding Carsten's misunderstanding of my mentioning of commenting out
statements, are the following two statements identical or not?
print 'Content-type: image/jpeg'
print 'Content-type: image/jpeg'
#print 'Content-type: text/plain'
This is what I mean. Sorry it was so difficult to communicate that to you.
Thanks again,
V
On Sat, Oct 17, 2009 at 2:57 PM, Neo wrote:
> Hi,
>
> Victor Subervi schrieb:
> > Let me clarify. This prints out "all sorts of crap", which means an
> > image string, the image as a string, to the screen:
> >
> > print 'Content-type: image/jpeg'
> > print 'Content-Encoding: base64'
> > print
> > print pic().encode('base64')
> > print ''
> >
> > The following once upon a time printed images, but now it doesn't. Why
> > would that be? I would refresh the screen, and it would print. I'd
> > change a line and it wouldn't. I'd change it back to what it was and it
> > would no longer the image to the screen. Why is that? The same happens
> > with or without the base64 stuff. Commenting out a line seemed to make a
> > difference!
> >
> > print 'Content-type: text/plain'
> > #print 'Content-type: image/jpeg'
> > print
> > print pic()
> > print ''
> >
> > The above prints out a broken image of correct dimensions.
>
> Only with a broken client (I assume Internetexplorer here?)
> Any you don't know what it does in guessing and caching (Try
> shift-reload when you test things)
>
> You should work from a static page and a static image and look what
> is transferred by the server (wireshark or tcpflow are of great help,
> but nc | hexdump -C | more is probably more easy if you work out the
> HTTP protocol (see rfc2616)
>
> You script needs to do the same as a server would do serving a static
> resource. Just look how it works and rebuild it.
>
> You will quickly find out, that there is obviously no reason to have
> at the end of a binary resource an Image is.
> Also correct mime type is important unless you deal with broken clients.
>
> There are a lot more HTTP-Headers you want to understand and use but the
> simple usage above, provided pic() indeed returns the binary data of the
> image unaltered, should work (w/o the html crap at the end).
> You would not use print since it adds a linefeed at the end which is not
> part of the data. sys.stdout.write() should work better (and can be used
> incremental to avoid returning the whole image data from memory)
>
> > Of course I try and figure out how things work once they get working.
> > Sometimes, however, there is __no__ logic to it __at__all__. Sorry.
> > After years of struggling with python I've come to realize that even
> > though I may not be a good programmer, it isn't me. It may not be python
> > itself. It may be the crappy hardware the server farms use. It may be
> > the way they tweak their python interpreter. But it isn't just me.
>
> Sorry to tell you that but its just you. There is no magic in that.
> Ok, there is one thing: what makes you sure the data in the database
> is really unaltered image data? I mean, you are using mysql...
> for a first thing I'd write the output into a file and try to open it
> in a graphic viewer.
>
> > It would be nice if I could get this code printing images to the screen
> > as it was before I had to put out another unnecessary fire when code
>
> Images are not "printed to screen" the whole idea is just wrong.
>
> > that previously uploaded the images in the first place inexplicably no
> > longer worked. Then, lo and behold, when I came back to this code that I
> > hadn't touched and was working fine earlier this week, it no longer
> > works. Lovely. My "plug-and-play" program has devoured two weeks of my
> > time and I'm still up the creek without a paddle. Sure would appreciate
> > any help you can give.
>
> I see "plug and play" and read cargo-cult. You need to read a bit about
> the basics on the matter or you will constantly run uphill - and even if
> it seems to work it has no value if you don't know _why_.
>
> Regards
> Tino
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Spawning Cmd Window via Subprocess
On Oct 16, 5:26 pm, TerryP wrote: > On Oct 16, 8:15 pm, D wrote: > > > Hello, > > > I would like to be able to spawn a new CMD window (specifing size, > > color and placement of the window), and write to it separately. > > Specifically, I have a backup program that displays each file backed > > up in the main window, and I would like to spawn and continually > > update a second CMD window that will display the current status (i.e. > > number of files backed up, amount of data backed up). Also, I only > > want to display the update messages, don't want to display any command > > prompts. I'm thinking I should be able to do this using subprocess, > > but I haven't been able to find out how. Any help would be greatly > > appreciated! > > you'll likely want to fiddle with subprocess.Popen with the arguments > set to suitable values to invoke a cmd window and establish pipes for > communication; see the documentation. If that doesn't work, it would > probably be time to muck with the Windows API. Thanks, TerryP..I briefly played around with subprocess.Popen, but so far no luck (certainly not to say I haven't missed something). You could be right that the Win API is needed.. I try to avoid whenever possible though. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: help to convert c++ fonction in python
If you change your last line from: print s to: print u you'll get different results :) TC -- http://mail.python.org/mailman/listinfo/python-list
Re: More & More Fun w/ Pics & MySQL
Victor Subervi wrote: > Thank you all. I have __no__idea__ why the link I sent you, that you > tested, __didn't__ work for me. Was it a problem with the browser? My Magic 8-Ball says "Unclear. Ask again later." > Regarding Carsten's misunderstanding of my mentioning of commenting out > statements, are the following two statements identical or not? > > print 'Content-type: image/jpeg' > > > print 'Content-type: image/jpeg' > #print 'Content-type: text/plain' Those two sets of lines are functionally identical, and they *will* *always* produce the same results in the same context. If they don't, then your server isn't executing the code that you think it's executing. -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
Ben Finney wrote: Lie Ryan writes: Paul Rubin wrote: Steven D'Aprano writes: For the record, the four lines Paul implies are "confusing" are: try: d[key] += value except KeyError: d[key] = value Consider what happens if the computation of "key" or "value" itself raises KeyError. Isn't key and value just a simple variables/names? In that example, yes. Paul is encouraging the reader to think of more complex cases where they are compound expressions, that can therefore raise other errors depending on what those expressions contain. If key and value had been anything but simple variable/name, then definitely you're writing the try-block the wrong way. try-block must be kept as simple as possible. Here is a simple, and effective way to mitigate the concern about compound expressions: key = complex_compound_expression_to_calculate_key value = complex_compound_expression_to_calculate_value try: d[key] += value except KeyError: d[key] = value The point is: "complex expressions and exceptions are used for different purpose" -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
Lie Ryan writes: > If key and value had been anything but simple variable/name, then > definitely you're writing the try-block the wrong way. try-block must > be kept as simple as possible. Avoiding the try-block completely is the simplest possibility of them all. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Python(x,y) 2.6.3.0 released
Hi all, I'm quite pleased (and relieved) to announce that Python(x,y) version 2.6.3.0 has been released. It is the first release based on Python 2.6 -- note that Python(x,y) version number will now follow the included Python version (Python(x,y) vX.Y.Z.N will be based on Python vX.Y.Z). Python(x,y) is a free Python distribution providing a ready-to-use scientific development software for numerical computations, data analysis and data visualization based on Python programming language, Qt graphical user interfaces (and development framework), Eclipse integrated development environment and Spyder interactive development environment. Its purpose is to help scientific programmers used to interpreted languages (such as MATLAB or IDL) or compiled languages (C/C++ or Fortran) to switch to Python. It is now available for Windows XP/Vista/7 (as well as for Ubuntu through the pythonxy-linux project -- note that included software may differs from the Windows version): http://www.pythonxy.com Major changes since v2.1.17: * Python 2.6.3 * Spyder 1.0.0 -- the Scientific PYthon Development EnviRonment, a powerful MATLAB-like development environment introducing exclusive features in the scientific Python community (http://packages.python.org/spyder/) * MinGW 4.4.0 -- including gcc 4.4.0 and gfortran * Pydev 1.5.0 -- now including the powerful code analysis features of Pydev Extensions (formerly available as a commercial extension to the free Pydev plugin) * Enthought Tool Suite 3.3.0 * PyQt 4.5.4 and PyQwt 5.2.0 * VTK 5.4.2 * ITK 3.16 -- Built for Python 2.6 thanks to the help of Charl Botha, DeVIDE (Delft Visualisation and Image processing Development Environment) Complete release notes: http://www.pythonxy.com/download.php - Pierre -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Spyder v1.0.0 released
Hi all, I'm pleased to announce here that Spyder version 1.0.0 has been released: http://packages.python.org/spyder Previously known as Pydee, Spyder (Scientific PYthon Development EnviRonment) is a free open-source Python development environment providing MATLAB-like features in a simple and light-weighted software, available for Windows XP/Vista/7, GNU/Linux and MacOS X: * advanced code editing features (code analysis, ...) * interactive console with MATLAB-like workpace (with GUI-based list, dictionary, tuple, text and array editors -- screenshots: http://packages.python.org/spyder/console.html#the-workspace) and integrated matplotlib figures * external console to open an interpreter or run a script in a separate process (with a global variable explorer providing the same features as the interactive console's workspace) * code analysis with pyflakes and pylint * search in files features * documentation viewer: automatically retrieves docstrings or source code of the function/class called in the interactive/external console * integrated file/directories explorer * MATLAB-like path management ...and more! Spyder is part of spyderlib, a Python module based on PyQt4 and QScintilla2 which provides powerful console-related PyQt4 widgets. I would like to thanks here all the Spyder users and especially the beta testers and contributors: without them, Spyder wouldn't be as stable, easy-to-use and full-featured as it is. - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: help to convert c++ fonction in python
Thomas wrote: If you change your last line from: print s to: print u you'll get different results :) if you change: s1 = base64.b64decode( s ) into s = base64.b64decode( s ) you'll get the same result again. -- http://mail.python.org/mailman/listinfo/python-list
problem with re.MULTILINE
Hello i ´ve got a little problem: I ´ve this text:
http://openpaste.org/en/secret/17343/pass-python and I need to parse
it. So i wrote this:
>>>
patternNode = re.compile("""
# Node (\w*).*
(.*)""", re.MULTILINE)
with open("test.msg", "r") as file:
testData = file.read()
for Node in re.findall(patternNode, testData):
print "Node:", Node[0]
print Node
<<<
but it prints only one line from text. If i am using re.DOTALL it
wouldn´t print anything.. So don´t you know whre the problem is?
Sorry for my English - it´s not my native language...
--
http://mail.python.org/mailman/listinfo/python-list
(from stdlib-sig) ctypes or struct from an h file
Is there a way that Python and C can have a shared definition for a binary data structure? It could be nice if: 1. struct or ctypes had a function that could parse a .h/.c/.cpp file to auto-generate constructors or 2. a ctypes definition could be exported to a .h file. So my question is - is there a way to do this in the std-lib or even pypi? --yuv ps If this doesn't exist, then I'm probably going to open a project and would like some tips/ideas. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with re.MULTILINE
Necronymouse wrote:
Hello i ´ve got a little problem: I ´ve this text:
http://openpaste.org/en/secret/17343/pass-python and I need to parse
it. So i wrote this:
patternNode = re.compile("""
# Node (\w*).*
(.*)""", re.MULTILINE)
with open("test.msg", "r") as file:
testData = file.read()
for Node in re.findall(patternNode, testData):
print "Node:", Node[0]
print Node
<<<
but it prints only one line from text. If i am using re.DOTALL it
wouldn´t print anything.. So don´t you know whre the problem is?
I assume you mean that it's giving you only the first line of text of
each node.
"(.*)" will capture a single (and possibly empty) line of text.
"(.+\n)" will capture a single non-empty line of text ending with a
newline.
I think you want to capture multiple non-empty lines, each line ending
with a newline:
patternNode = re.compile("""
# Node (\w*).*
((?:.+\n)*)""", re.MULTILINE)
Sorry for my English - it´s not my native language...
It's better than my Czech/Slovak (depending on what Google says)! :-)
--
http://mail.python.org/mailman/listinfo/python-list
Re: More & More Fun w/ Pics & MySQL
Carsten Haese wrote: Victor Subervi wrote: Thank you all. I have __no__idea__ why the link I sent you, that you tested, __didn't__ work for me. Was it a problem with the browser? My Magic 8-Ball says "Unclear. Ask again later." Regarding Carsten's misunderstanding of my mentioning of commenting out statements, are the following two statements identical or not? print 'Content-type: image/jpeg' print 'Content-type: image/jpeg' #print 'Content-type: text/plain' Those two sets of lines are functionally identical, and they *will* *always* produce the same results in the same context. If they don't, then your server isn't executing the code that you think it's executing. Only in HTML commented line can sometimes not be ignored and is parsed depending on the time of the day (specifically the in a
Re: (from stdlib-sig) ctypes or struct from an h file
On Sun, Oct 18, 2009 at 2:44 PM, Yuvgoog Greenle wrote: > Is there a way that Python and C can have a shared definition for a > binary data structure? > > It could be nice if: > 1. struct or ctypes had a function that could parse a .h/.c/.cpp file > to auto-generate constructors > or > 2. a ctypes definition could be exported to a .h file. > > So my question is - is there a way to do this in the std-lib or even pypi? > > > --yuv I wrote a bit of code a while ago that does something similar. You can find it here: http://code.activestate.com/recipes/576734/. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
Russ P. wrote: > On Oct 10, 1:15pm, kj wrote: > > I'm coaching a group of biologists on basic Python scripting. One > > of my charges mentioned that he had come across the advice never > > to use loops beginning with "while True". Of course, that's one > > way to start an infinite loop, but this seems hardly a sufficient > > reason to avoid the construct altogether, as long as one includes > > an exit that is always reached. (Actually, come to think of it, > > there are many situations in which a bona fide infinite loops > > (typically within a try: block) is the required construct, e.g. > > when implementing an event loop.) > > > > I use "while True"-loops often, and intend to continue doing this > > "while True", but I'm curious to know: how widespread is the > > injunction against such loops? Has it reached the status of "best > > practice"? > > Never, ever use "while True". It's an abomination. The correct form is > "while 1". equivalently appears doable with for statement too, but not C-style for (;;), however like this from itertools import count for a in (2*b in itertools.count() if b**2 > 3): doThis() sleep(5) doThat() best regards, NR -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with re.MULTILINE
On 18 říj, 21:20, MRAB wrote:
> Necronymouse wrote:
> > Hello i ´ve got a little problem: I ´ve this text:
> >http://openpaste.org/en/secret/17343/pass-pythonand I need to parse
> > it. So i wrote this:
>
> > patternNode = re.compile("""
> > # Node (\w*).*
> > (.*)""", re.MULTILINE)
>
> > with open("test.msg", "r") as file:
> > testData = file.read()
>
> > for Node in re.findall(patternNode, testData):
> > print "Node:", Node[0]
> > print Node
> > <<<
>
> > but it prints only one line from text. If i am using re.DOTALL it
> > wouldn´t print anything.. So don´t you know whre the problem is?
>
> I assume you mean that it's giving you only the first line of text of
> each node.
>
> "(.*)" will capture a single (and possibly empty) line of text.
>
> "(.+\n)" will capture a single non-empty line of text ending with a
> newline.
>
> I think you want to capture multiple non-empty lines, each line ending
> with a newline:
>
> patternNode = re.compile("""
> # Node (\w*).*
> ((?:.+\n)*)""", re.MULTILINE)
>
> > Sorry for my English - it´s not my native language...
>
> It's better than my Czech/Slovak (depending on what Google says)! :-)
Yeah this works ( ((?:.+\r\n)*) ), thanks.. It´s czech..
--
http://mail.python.org/mailman/listinfo/python-list
Capturing a var from JavaScript
Hi;
I have the following code:
#!/usr/bin/python
def getResolution():
print 'Content-Type: text/html\n'
print '''
http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd'>
var winX = screen.width;
var winY = screen.height;
'''
x = eval('document.write(winX)')
#document.write('Your screen resolution is ' + winX + ' x ' + winY + ',
which is below the recommended size for this application. If possible,
please reset your screen resolution to 800 x 600 or higher. Thank you!');
print '''
'''
print x
print '''
'''
getResolution()
It doesn't work. What I want is to capture winX and winY and use them in
python. How?
TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list
Re: (from stdlib-sig) ctypes or struct from an h file
Yuvgoog Greenle schrieb: Is there a way that Python and C can have a shared definition for a binary data structure? It could be nice if: 1. struct or ctypes had a function that could parse a .h/.c/.cpp file to auto-generate constructors or 2. a ctypes definition could be exported to a .h file. So my question is - is there a way to do this in the std-lib or even pypi? --yuv ps If this doesn't exist, then I'm probably going to open a project and would like some tips/ideas. gccxml can be used to do this, there is a ctypes utilities module that works with the output of gccxml. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: (from stdlib-sig) ctypes or struct from an h file
I'd like to clarify the use case. Lets say you're writing a client and a server, one is in python and the other is C. If these 2 programs need to pass binary information between them (lets say over a socket) there are 2 options, it could be nice if you could only write the struct once (either in python or in C) without any Cython or C extension (for portability and ease of development's sake). Just trying to keep it DRY... --yuv -- http://mail.python.org/mailman/listinfo/python-list
Re: (from stdlib-sig) ctypes or struct from an h file
On Sun, Oct 18, 2009 at 4:13 PM, Diez B. Roggisch wrote: > Yuvgoog Greenle schrieb: >> >> Is there a way that Python and C can have a shared definition for a >> binary data structure? >> >> It could be nice if: >> 1. struct or ctypes had a function that could parse a .h/.c/.cpp file >> to auto-generate constructors >> or >> 2. a ctypes definition could be exported to a .h file. >> >> So my question is - is there a way to do this in the std-lib or even pypi? >> >> >> --yuv >> >> >> ps If this doesn't exist, then I'm probably going to open a project >> and would like some tips/ideas. > > > gccxml can be used to do this, there is a ctypes utilities module that works > with the output of gccxml. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Found this: http://starship.python.net/crew/theller/ctypes/old/codegen.html which I take to be the module you're talking about. From the docs it doesn't appear to have worked with gccxml since before 0.6, which is more than 5 years old. Am I at the wrong place? Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
[ANN] "Python for Bioinformatics" available and in stock
I announced that Python for Bioinformatics was ready, now I want to
announce that is available and in stock in most book sellers.
Worldwide, use Amazon.
In Argentina, it is more convenient buying it from me at MercadoLibre:
http://articulo.mercadolibre.com.ar/MLA-64715574-libro-python-for-bioinformatics-opcional-firmado-x-autor-_JM
Here is my stock:
http://www.flickr.com/photos/sbassi/4018649164/sizes/l/
Book announcement:
Python for Bioinformatics book
"Python for Bioinformatics"
ISBN 1584889292
Amazon: http://www.tinyurl.com/biopython
Publisher: http://www.crcpress.com/product/isbn/9781584889298
This book introduces programming concepts to life science researchers,
bioinformaticians, support staff, students, and everyone who is
interested in applying programming to solve biologically-related
problems. Python is the chosen programming language for this task
because it is both powerful and easy-to-use.
It begins with the basic aspects of the language (like data types and
control structures) up to essential skills on today's bioinformatics
tasks like building web applications, using relational database
management systems, XML and version control. There is a chapter
devoted to Biopython (www.biopython.org) since it can be used for most
of the tasks related to bioinformatics data processing.
There is a section with applications with source code, featuring
sequence manipulation, filtering vector contamination, calculating DNA
melting temperature, parsing a genbank file, inferring splicing sites,
and more.
There are questions at the end of every chapter and odd numbered
questiona are answered in an appendix making this text suitable for
classroom use.
This book can be used also as a reference material as it includes
Richard Gruet's Python Quick Reference, and the Python Style Guide.
DVD: The included DVD features a virtual machine with a special
edition of DNALinux, with all the programs and complementary files
required to run the scripts commented in the book. All scripts can be
tweaked to fit a particular configuration. By using a pre-configured
virtual machine the reader has access to the same development
environment than the author, so he can focus on learning Python. All
code is also available at the http://py3.us/## where ## is the code
number, for example: http://py3.us/57
I've been working on this book for more than two years testing the
examples under different setups and working to make the code
compatible for most versions of Python, Biopython and operating
systems. Where there is code that only works with a particular
dependency, this is clearly noted.
Finally, I want to highlight that non-bioinformaticians out there can
use this book as an introduction to bioinformatics by starting with
the included "Diving into the Gene Pool with BioPython" (by Zachary
Voase and published originally in Python Magazine)
--
Sebastián Bassi. Diplomado en Ciencia y Tecnología.
Non standard disclaimer: READ CAREFULLY. By reading this email,
you agree, on behalf of your employer, to release me from all
obligations and waivers arising from any and all NON-NEGOTIATED
agreements, licenses, terms-of-service, shrinkwrap, clickwrap,
browsewrap, confidentiality, non-disclosure, non-compete and
acceptable use policies ("BOGUS AGREEMENTS") that I have
entered into with your employer, its partners, licensors, agents and
assigns, in perpetuity, without prejudice to my ongoing rights and
privileges. You further represent that you have the authority to release
me from any BOGUS AGREEMENTS on behalf of your employer.
--
http://mail.python.org/mailman/listinfo/python-list
Re: (from stdlib-sig) ctypes or struct from an h file
geremy condra schrieb: On Sun, Oct 18, 2009 at 4:13 PM, Diez B. Roggisch wrote: Yuvgoog Greenle schrieb: Is there a way that Python and C can have a shared definition for a binary data structure? It could be nice if: 1. struct or ctypes had a function that could parse a .h/.c/.cpp file to auto-generate constructors or 2. a ctypes definition could be exported to a .h file. So my question is - is there a way to do this in the std-lib or even pypi? --yuv ps If this doesn't exist, then I'm probably going to open a project and would like some tips/ideas. gccxml can be used to do this, there is a ctypes utilities module that works with the output of gccxml. Diez -- http://mail.python.org/mailman/listinfo/python-list Found this: http://starship.python.net/crew/theller/ctypes/old/codegen.html which I take to be the module you're talking about. From the docs it doesn't appear to have worked with gccxml since before 0.6, which is more than 5 years old. Am I at the wrong place? Nope, that's it. I don't understand what you mean with "since before 0.6" - all I can say is I got it working last year with a GCC 3.X or 4.x project. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Spawning Cmd Window via Subprocess
En Sun, 18 Oct 2009 14:22:07 -0200, D escribió:
On Oct 16, 5:26 pm, TerryP wrote:
On Oct 16, 8:15 pm, D wrote:
> I would like to be able to spawn a new CMD window (specifing size,
> color and placement of the window), and write to it separately.
> Specifically, I have a backup program that displays each file backed
> up in the main window, and I would like to spawn and continually
> update a second CMD window that will display the current status (i.e.
> number of files backed up, amount of data backed up). Also, I only
> want to display the update messages, don't want to display any command
> prompts. I'm thinking I should be able to do this using subprocess,
> but I haven't been able to find out how. Any help would be greatly
> appreciated!
you'll likely want to fiddle with subprocess.Popen with the arguments
set to suitable values to invoke a cmd window and establish pipes for
communication; see the documentation. If that doesn't work, it would
probably be time to muck with the Windows API.
Thanks, TerryP..I briefly played around with subprocess.Popen, but so
far no luck (certainly not to say I haven't missed something). You
could be right that the Win API is needed.. I try to avoid whenever
possible though. :)
If all you need is a status line, try using SetConsoleTile; it sets the
window title (caption) and you don't need a second console.
from win32api import SetConsoleTitle
SetConsoleTitle("File %d/%d - Bytes %s/%s total" %
(i, len(files), bytes2str(fsize), bytes2str(totalsize)))
If you still require a separate console (and a separate process, and some
form of IPC...) use the startupinfo argument to subprocess.Popen (from
win32process; the one from subprocess only supports a few fields). You can
find the structure definition in the Microsoft documentation:
http://msdn.microsoft.com/en-us/library/ms686285(VS.85).aspx
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: (from stdlib-sig) ctypes or struct from an h file
On 08:13 pm, [email protected] wrote: Yuvgoog Greenle schrieb: Is there a way that Python and C can have a shared definition for a binary data structure? It could be nice if: 1. struct or ctypes had a function that could parse a .h/.c/.cpp file to auto-generate constructors or 2. a ctypes definition could be exported to a .h file. So my question is - is there a way to do this in the std-lib or even pypi? --yuv ps If this doesn't exist, then I'm probably going to open a project and would like some tips/ideas. gccxml can be used to do this, there is a ctypes utilities module that works with the output of gccxml. Diez -- http://mail.python.org/mailman/listinfo/python-list ctypes_configure can do this, too, doesn't require gccxml, and works with non-gcc compilers. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: (from stdlib-sig) ctypes or struct from an h file
Yuvgoog Greenle wrote: I'd like to clarify the use case. Lets say you're writing a client and a server, one is in python and the other is C. If these 2 programs need to pass binary information between them (lets say over a socket) there are 2 options, it could be nice if you could only write the struct once (either in python or in C) without any Cython or C extension (for portability and ease of development's sake). It's not as simple as that. You have to know the binary format layouts (say, for floating point numbers) and struct padding that's used (since it can be inserted arbitrarily) on the C side of things, not to mention you have to arrange the whole the to be put into consistent (network) byte order. Both sides have to take care of this, since if the server and client are running on different architectures, there's no guarantees any of these things will be the same. -- Erik Max Francis && [email protected] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Diplomacy and defense are not substitutes for one another. Either alone would fail. -- John F. Kennedy, 1917-1963 -- http://mail.python.org/mailman/listinfo/python-list
Re: slicing return iter?
En Sun, 18 Oct 2009 03:02:27 -0200, StarWing escribió: On 10月18日, 上午9时09分, Raymond Hettinger wrote: [StarWing] > > > sometimes I want to iterate a part of a sequence. but don't want to > > > copy it. i.e. . . . > I had checked it for serval times. maybe it's my inattention :-(. but > what i could find the nearest thing is itertools.islice. but it can't > process negative index -- that's supported by slice. so I need > something, bind object with slice, and return a iter. I can find > anything like it...:-( If it really is a sequence (with len and getitem), you can write your own indexing iterator: def myslice(seq, start, stop, step): 'Allow forward or backwards iteration over a subslice' for i in range(start, stop, step): yield seq[i] Raymond Thank you. but it can't support negative index :-( Terry Reedy is right. since a range (or xrange or slice etc.) don't have a length, so it can't support a negative index. so the best way to do it is that binding a range with a object. and return a iter. I think, why standard library didn't have anything like that, that will be very useful. maybe we should have a builtin functoin itertools.bslice (stands for bind slice)... A variation of the code above would do, using a slice() object: py> def myslice(seq, start, stop, step): ... 'Allow forward or backwards iteration over a subslice' ... for i in xrange(*slice(start, stop, step).indices(len(seq))): ... yield seq[i] ... py> import string py> lst = list(string.lowercase) py> list(myslice(lst, 5, 18, 2)) # as in lst[5:18:2] ['f', 'h', 'j', 'l', 'n', 'p', 'r'] py> list(myslice(lst, -5, None, None)) # as in lst[-5:] ['v', 'w', 'x', 'y', 'z'] py>py> list(myslice(lst, None, None, -1)) # as in lst[::-1] ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', ..., 'a'] Slice objects are not-so-well known, and are documented here: http://docs.python.org/reference/datamodel.html#types -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Reverse Iteration Through Integers
I'm trying to make an integer that is the reverse of an existing integer such that 169 becomes 961. I guess I don't know enough yet to figure out how to do this without a ton of awkward-looking code. I've tried for loops without much success. I guess I need a good way of figuring out the length of the input integer so my loop can iterate that many times to reverse the number, but I keep getting errors that say "TypeError: 'Int' object is not iterable". Any help would be much appreciated, Benjamin "Self-Proclaimed Python Newbie" -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
Benjamin Middaugh wrote:
I'm trying to make an integer that is the reverse of an existing integer
such that 169 becomes 961. I guess I don't know enough yet to figure out
how to do this without a ton of awkward-looking code. I've tried for
loops without much success. I guess I need a good way of figuring out
the length of the input integer so my loop can iterate that many times
to reverse the number, but I keep getting errors that say "TypeError:
'Int' object is not iterable".
Any help would be much appreciated,
Benjamin "Self-Proclaimed Python Newbie"
you need to turn the int to a str:
>>> n = 169
>>> rn = int(''.join(reversed(str(n
>>> rn
961
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
On Sun, 18 Oct 2009 19:34:09 +0100, Benjamin Middaugh wrote: I'm trying to make an integer that is the reverse of an existing integer such that 169 becomes 961. I guess I don't know enough yet to figure out how to do this without a ton of awkward-looking code. I've tried for loops without much success. I guess I need a good way of figuring out the length of the input integer so my loop can iterate that many times to reverse the number, but I keep getting errors that say "TypeError: 'Int' object is not iterable". Alternatively, turn your integer into a string, reverse the string, and turn it back: rho...@gnudebst:~$ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. n = 123 int(str(n)[::-1]) 321 -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
Benjamin Middaugh schrieb: > I'm trying to make an integer that is the reverse of an existing integer > such that 169 becomes 961. I guess I don't know enough yet to figure out > how to do this without a ton of awkward-looking code. I've tried for > loops without much success. I guess I need a good way of figuring out > the length of the input integer so my loop can iterate that many times > to reverse the number, but I keep getting errors that say "TypeError: > 'Int' object is not iterable". > > Any help would be much appreciated, Here is a simplistic version that doesn't use fancy math: >>> str(24) '24' >>> str(24)[::-1] '42' >>> int(str(24)[::-1]) 42 -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding slice notation to iterators/generators?
On Oct 16, 7:38 pm, Carl Banks wrote: > You would burden everyone who writes a custom iterator to provide a > __getitem__ method just because you're too lazy to type out the word > islice? No, of course not. That would be stupid. Custom iterators are iterators, so they would also get the default __getitem__ which would work just perfectly for them. If they needed to override it, they could. Remember, my proposal was to add a default __getitem__ for iterators that is really just islice. Ryles makes a good point though: >I think Python programmers have learned to expect certain things from >objects that support __getitem__. For example, indexing and slicing is >repeatable on the same object: That indexing/slicing iterators is not repeatable is likely to negate much of the advantage of supporting a larger interface (because it would be supported inconsistently, passing an iterator to something that expects __getitem__ could be surprising.) That does not mean it has no value in working with iterators, it offers the same value islice does, just more conveniently. Steven: >If you want to support slicing, go right ahead, but please, I beg you, >don't force me to support it in my iterators! As I said to Carl Banks, forcing you do something differently is not my aim here. Your other points apply equally to islice, which already exists, and do not invalidate its purpose. The main use case I'm thinking about here is skipping elements or limiting results from iterators, usually in for loops: for x in my_iter[5:]: ... for x in my_iter[:5]: ... Clearly that's easier and more readable than using islice. Nobody has yet to provide a concrete reason why that would be a _bad thing_. That doesn't make it a _good thing_, either. -Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
Benjamin Middaugh writes: > I'm trying to make an integer that is the reverse of an existing > integer such that 169 becomes 961. I guess I don't know enough yet to > figure out how to do this without a ton of awkward-looking code. I've > tried for loops without much success. I guess I need a good way of > figuring out the length of the input integer so my loop can iterate > that many times to reverse the number, but I keep getting errors that > say "TypeError: 'Int' object is not iterable". Sounds like you're working on Euler problems ;-). The simplest way is to turn the integer to a string: n_int = 961 n_string = str(n_int) then reverse the string: n_string_reversed = reversed(n_string) and turn it back into an int: n_int_reversed = int(n_string_reversed) If you want to peel off digits from an int one by one without string conversions, it's easiest to do that in reverse order: n = 961 digits = [] while n > 0: n,d = divmod(n, 10) digits.append(d) Look up the docs for "divmod" for an explanation of that handy function. Now the above gives you a reversed list of digits--what to do with it is an exercise for you ;-). Note that if n=0 then you get the empty list. Yet another way is to use recursion. I'll leave that as an exercise too. -- http://mail.python.org/mailman/listinfo/python-list
Re: print()
En Sun, 18 Oct 2009 10:35:34 -0200, mattia escribió:
Il Sat, 17 Oct 2009 10:02:27 -0400, Dave Angel ha scritto:
mattia wrote:
Il Fri, 16 Oct 2009 21:04:08 +, mattia ha scritto:
Another question (always py3). How can I print only the first number
after the comma of a division?
e.g. print(8/3) --> 2.667
I just want 2.6 (or 2.66)
x = 8/3
dummy0=dummy1=dummy2=42
s = "The answer is approx. {3:07.2f} after rounding".format(dummy0,
dummy1, dummy2, x)
print(s)
will print out the following:
The answer is approx. 0002.67 after rounding
Yes, reading the doc I've come up with
s = "%(0)03.02f%(1)s done" % {"0": 100.0-100.0*(size/tot), "1": "%"}
but to it is not a good idea to use a dict here..
No need for a dict, you could use instead:
s = "%03.02f%s done" % (100.0-100.0*(size/tot), "%")
or (%% is the way to embed a single %):
s = "%03.02f%% done" % (100.0-100.0*(size/tot),)
or even:
s = "%03.02f%% done" % (100.0-100.0*(size/tot))
but the new str.format() originally suggested by Dave Angel is better:
s = "{0:03.02f}% done".format(100.0-100.0*(size/tot))
(BTW, why 03.02f? The output will always have at least 4 chars, so 03
doesn't mean anything... Maybe you want {0:06.2f} (three places before the
decimal point, two after it, filled with 0's on the left)?)
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Checking a Number for Palindromic Behavior
Thanks to everyone who helped with my query on reversing integers. I have one more simple problem I'm having trouble solving. I want to check a number for palindromic behavior (reading the same backwards and forwards). So if I have an integer 1457 it can tell me this is not the same from both ends but 1551 is. I think the simplest way would be to work inwards from both ends checking digits for equality, but I don't know enough (yet) to do this. All help is much appreciated. Benjamin -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
Benjamin Middaugh wrote: I'm trying to make an integer that is the reverse of an existing integer such that 169 becomes 961. I guess I don't know enough yet to figure out how to do this without a ton of awkward-looking code. I've tried for loops without much success. I guess I need a good way of figuring out the length of the input integer so my loop can iterate that many times to reverse the number, but I keep getting errors that say "TypeError: 'Int' object is not iterable". Any help would be much appreciated, You need to remember that you're not actually trying to reverse an integer (does that actually make sense?), but the digits when it's represented as a string (and in decimal). -- http://mail.python.org/mailman/listinfo/python-list
Re: print()
Il Sun, 18 Oct 2009 20:04:11 -0200, Gabriel Genellina ha scritto:
> En Sun, 18 Oct 2009 10:35:34 -0200, mattia escribió:
>
>> Il Sat, 17 Oct 2009 10:02:27 -0400, Dave Angel ha scritto:
>>> mattia wrote:
Il Fri, 16 Oct 2009 21:04:08 +, mattia ha scritto:
Another question (always py3). How can I print only the first number
after the comma of a division?
e.g. print(8/3) --> 2.667
I just want 2.6 (or 2.66)
>>> x = 8/3
>>> dummy0=dummy1=dummy2=42
>>> s = "The answer is approx. {3:07.2f} after rounding".format(dummy0,
>>> dummy1, dummy2, x)
>>> print(s)
>>>
>>> will print out the following:
>>>
>>> The answer is approx. 0002.67 after rounding
>>
>> Yes, reading the doc I've come up with s = "%(0)03.02f%(1)s done" %
>> {"0": 100.0-100.0*(size/tot), "1": "%"} but to it is not a good idea to
>> use a dict here..
>
> No need for a dict, you could use instead:
>
> s = "%03.02f%s done" % (100.0-100.0*(size/tot), "%")
>
> or (%% is the way to embed a single %):
>
> s = "%03.02f%% done" % (100.0-100.0*(size/tot),)
>
> or even:
>
> s = "%03.02f%% done" % (100.0-100.0*(size/tot))
>
> but the new str.format() originally suggested by Dave Angel is better:
>
> s = "{0:03.02f}% done".format(100.0-100.0*(size/tot))
>
> (BTW, why 03.02f? The output will always have at least 4 chars, so 03
> doesn't mean anything... Maybe you want {0:06.2f} (three places before
> the decimal point, two after it, filled with 0's on the left)?)
No need of 03, you are right, thanks.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
Benjamin Middaugh wrote: Thanks to everyone who helped with my query on reversing integers. I have one more simple problem I'm having trouble solving. I want to check a number for palindromic behavior (reading the same backwards and forwards). So if I have an integer 1457 it can tell me this is not the same from both ends but 1551 is. I think the simplest way would be to work inwards from both ends checking digits for equality, but I don't know enough (yet) to do this. All help is much appreciated. It's a palindrome if it's the same as its reverse. You already know how to reverse it, and you should already know how to check whether two things are the same, so... :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: More & More Fun w/ Pics & MySQL
En Fri, 16 Oct 2009 16:23:31 -0300, Victor Subervi escribió: This will print all sorts of crap to the screen. I know it's an image, because for some reason "occasionally" it once upon a time today printed the actual image to the screen when I had these lines last:[...] Notice the commented out line was essential, but it doesn't matter any more because the tempermental python interpreter gods changed their attitude toward this particular code snippet. Good grief. At any rate, this stupid code worked fine before the last problem that way-laid me for 2 days, and now it doesn't want to work again. What gives? I think you'll benefit from using *any* sort of source versioning (cvs, svn, mercurial...) This way you can go back in time to the moment when things were working fine, and see what changed since then. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Frameworks
Hi I have been searching through the vast array of python frameworks http://wiki.python.org/moin/WebFrameworks and its quite astounding the choice available. I am looking at using a web framework for my personal project which isn't actually aimed at developing a website as such. However I deduce that rather than creating a gui application and screen input for data, I can use a web browser for this and have a great array of tools to format input screens and output display formats. Since I will be retreiving information from several websites (usually csv files) formatting them and submitting them to a database and creating queries and printouts based on them most frameworks seem to handle this basically with ease and for any complex queries most support SqlAlchemy. Is it simply a case of just picking one and starting and I would find it hard to be dissapointed or is there a few special considerations to make, though I am unsure what they are? Most obvious ones I am considering are Django (Of course), Pylons includes SqlAlchemy, Sql Object and templating and I here turbogears plans to sit on top of this platform. Zope I am considering but I am a little confused by this. The are heaps of others but not sure how to narrow the selection criteria. How/Why woul you split Django and Pylons let alone the others? Database likely to be MySQl -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
Benjamin Middaugh wrote: Thanks to everyone who helped with my query on reversing integers. I have one more simple problem I'm having trouble solving. I want to check a number for palindromic behavior (reading the same backwards and forwards). So if I have an integer 1457 it can tell me this is not the same from both ends but 1551 is. I think the simplest way would be to work inwards from both ends checking digits for equality, but I don't know enough (yet) to do this. All help is much appreciated. Benjamin This problem (and the OP's previous problem) are probably homework problems. If so, it was unethical for the student to ask for a solution here, and it was careless of several responders to provide a solution. Let's not make the same mistake this time. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: restriction on sum: intentional bug?
Dave Angel wrote: Dieter Maurer wrote: Christian Heimes writes on Fri, 16 Oct 2009 17:58:29 +0200: Alan G Isaac schrieb: I expected this to be fixed in Python 3: sum(['ab','cd'],'') Traceback (most recent call last): File "", line 1, in TypeError: sum() can't sum strings [use ''.join(seq) instead] Of course it is not a good way to join strings, but it should work, should it not? Naturally, It's not a bug. sum() doesn't work on strings deliberately. ''.join() *is* the right and good way to concatenate strings. Apparently, "sum" special cases 'str' in order to teach people to use "join". It would have been as much work and much more friendly, to just use "join" internally to implement "sum" when this is possible. Dieter Earlier, I would have agreed with you. I assumed that this could be done invisibly, with the only difference being performance. But you can't know whether join will do the trick without error till you know that all the items are strings or Unicode strings. And you can't check that without going through the entire iterator. At that point it's too late to change your mind, as you can't back up an iterator. So the user who supplies a list with mixed strings and other stuff will get an unexpected error, one that join generates. To put it simply, I'd say that sum() should not dispatch to join() unless it could be sure that no errors might result. DaveA How is this different than passing a list to sum with other incompatible types? Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class Dummy(object): ... pass ... >>> test1 = [1, 2, 3.4, Dummy()] >>> sum(test1) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'float' and 'Dummy' >>> test2 = ['a', 'string', 'and', 'a', Dummy()] >>> ''.join(test2) Traceback (most recent call last): File "", line 1, in TypeError: sequence item 4: expected string, Dummy found Looks like a TypeError either way, only the verbage changes. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Tracking down DLL load errors in Windows ?
"Fred Pacquier" wrote in message news:[email protected]... After installing the MS redistributable DLL package -- actually I had to install *three* before hitting the right one (2005SP1) -- libpyexiv2 finally loads all its dependencies. Of course I've still no idea why/how it ran on the first three systems (and most others, from the look of it) without doing anything, and not on this one... but at least now it works :-) Yes, welcome to Microsoft's solution to DLL Hell...Side-by-Side DLL Hell. -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding slice notation to iterators/generators?
En Sun, 18 Oct 2009 19:53:20 -0200, Eloff escribió:
On Oct 16, 7:38 pm, Carl Banks wrote:
You would burden everyone who writes a custom iterator to provide a
__getitem__ method just because you're too lazy to type out the word
islice?
No, of course not. That would be stupid. Custom iterators are
iterators, so they would also get the default __getitem__ which would
work just perfectly for them. If they needed to override it, they
could. Remember, my proposal was to add a default __getitem__ for
iterators that is really just islice.
Note that iterators don't have a common base class - so where would such
__getitem__ reside? *Anything* with a next/__next__ method is an iterator.
In some, very limited cases, you can 'inject' a __getitem__ method into an
existing iterator:
py> from itertools import islice
py>
py> def __getitem__(self, subscript):
... if isinstance(subscript, slice):
... return islice(self, subscript.start, subscript.stop,
subscript.step)
... elif isinstance(subscript, int):
... return next(islice(self, subscript, subscript+1, 1))
...
py> def add_slice_support(iterator):
... oldtype = type(iterator)
... newtype = type(oldtype.__name__, (oldtype,), {'__getitem__':
__getitem__})
... iterator.__class__ = newtype
... return iterator
Unfortunately this only works for user-defined iterators:
py> add_slice_support(range(30))
Traceback (most recent call last):
File "", line 1, in
File "", line 4, in add_slice_support
TypeError: __class__ assignment: only for heap types
And even then, there are surprises:
py> class Foo(object):
... i = 0
... def __iter__(self): return self
... def next(self):
... ret, self.i = self.i, self.i+1
... return ret
...
py> it = add_slice_support(Foo())
py> print it[2]
2
py> for z in it[5:10]: print z
...
8 # 8???
9
10
11
12
py> for z in it[5:10]: print z
...
18 # 18???
19
20
21
22
py>
The main use case I'm thinking about here is skipping elements or
limiting results from iterators, usually in for loops:
for x in my_iter[5:]:
...
for x in my_iter[:5]:
...
Clearly that's easier and more readable than using islice. Nobody has
yet to provide a concrete reason why that would be a _bad thing_. That
doesn't make it a _good thing_, either.
You'll have to remember to never reuse my_iter again, as my example above
shows. Or keep track of the past items so you can adjust the indices. But
anyway you can't retrieve those past items, unless you maintain them all
in a list and take the memory penalty. Or just use islice when needed -
only six letters, and you avoid all those problems... ;)
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: How about adding slice notation to iterators/generators?
On Oct 18, 2:53 pm, Eloff wrote: > On Oct 16, 7:38 pm, Carl Banks wrote: > > > You would burden everyone who writes a custom iterator to provide a > > __getitem__ method just because you're too lazy to type out the word > > islice? > > No, of course not. That would be stupid. Custom iterators are > iterators, so they would also get the default __getitem__ which would > work just perfectly for them. Ok, here's a simple (Python 2.x) custom iterator. class Alphabet(object): def __init__(self): self.c = 65 def __iter__(self): return self def next(self): if self.c > 90: raise StopIteration letter = chr(self.c) self.c += 1 return letter Let's see what happens *currently* in Python when you try to apply slice indexing. for x in AB()[4:9]: # loop through letters 4 through 8 print x This, as expected, raises a type error: TypeError: 'AB' object is unsubscriptable Now, let's try to modify Python to fix this. All we have to do is to define __getitem__ for the default iterator, so let's define it in the common iterator type, which is Hm, wait a second, problem here. The simple iterator I defined above isn't an instance of any common iterator type. In fact there is no common iterator type. You see, iterator is a *protocol*. An object is not an iterator by virtue of being an instance of an iterator type, it's an iterator because it supports a protocol. In fact that protocol is extremely simple: all an iterator has to do is define __iter__() to return self, define next() to return next item, and raise StopIteration when it's done. So you see, to support slice syntax one would indeed burden all custom iterators to implement __getitem__ method, which would arguably increase the implementor's burden by 30%. > If they needed to override it, they > could. Remember, my proposal was to add a default __getitem__ for > iterators that is really just islice. There is no default __getitem__ for iterators so this proposal won't work. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: restriction on sum: intentional bug?
On Oct 18, 4:07 pm, Ethan Furman wrote: > Dave Angel wrote: > > Earlier, I would have agreed with you. I assumed that this could be > > done invisibly, with the only difference being performance. But you > > can't know whether join will do the trick without error till you know > > that all the items are strings or Unicode strings. And you can't check > > that without going through the entire iterator. At that point it's too > > late to change your mind, as you can't back up an iterator. So the user > > who supplies a list with mixed strings and other stuff will get an > > unexpected error, one that join generates. > > > To put it simply, I'd say that sum() should not dispatch to join() > > unless it could be sure that no errors might result. > > How is this different than passing a list to sum with other incompatible > types? > > Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> class Dummy(object): > ... pass > ... > >>> test1 = [1, 2, 3.4, Dummy()] > >>> sum(test1) > Traceback (most recent call last): > File "", line 1, in > TypeError: unsupported operand type(s) for +: 'float' and 'Dummy' > >>> test2 = ['a', 'string', 'and', 'a', Dummy()] > >>> ''.join(test2) > Traceback (most recent call last): > File "", line 1, in > TypeError: sequence item 4: expected string, Dummy found > > Looks like a TypeError either way, only the verbage changes. This test doesn't mean very much since you didn't pass the the same list to both calls. The claim is that "".join() might do something different than a non-special-cased sum() would have when called on the same list, and indeed that is true. Consider this thought experiment: class Something(object): def __radd__(self,other): return other + "q" x = ["a","b","c",Something()] If x were passed to "".join(), it would throw an exception; but if passed to a sum() without any special casing, it would successfully return "abcq". Thus there is divergence in the two behaviors, thus transparently calling "".join() to perform the summation is a Bad Thing Indeed, a much worse special-case behavior than throwing an exception. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: slicing return iter?
[Raymond] > > If it really is a sequence (with len and getitem), you can write your > > own indexing iterator: > > > def myslice(seq, start, stop, step): > > 'Allow forward or backwards iteration over a subslice' > > for i in range(start, stop, step): > > yield seq[i] [StarWing] > Thank you. but it can't support negative index :-( The negative index is handled by the line, "yield seq[i]". >>> s[-2:-5:-1] == ''.join(myslice(s, -2, -5, -1)) True >>> s[-5:-2:1] == ''.join(myslice(s, -5, -2, 1)) True Raymond -- http://mail.python.org/mailman/listinfo/python-list
Python 2.6.4rc2
Hello everyone. The source tarballs and Windows installers for Python 2.6.4rc2 are now available: http://www.python.org/download/releases/2.6.4/ Please download them, install them, and try to use them with your projects and environments. Let's make 2.6.4 a rock solid release! If there are no more regressions found, we'll do the final release in one week, on 25-October. Enjoy, -Barry PGP.sig Description: This is a digitally signed message part -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
Paul Rubin wrote: > Yet another way is to use recursion. I'll leave that as an exercise too. This time with big numbers: def trampoline(bouncing, *args, **kwargs): while bouncing: result, bouncing, args, kwargs = bouncing(*args, **kwargs) if result: return result() def bouncy(function): return lambda *args, **kwargs:(None, function, args, kwargs) def land(result=None): return lambda:result, None, None, None def reverse(n): @bouncy def rev(i=n, j=0, k=0): if i: return rev(*divmod(i, 10), k=(j+k)*10) return land(j + k) return trampoline(rev) print reverse(169883903200298309284038223098439430943092816286 ** 123) Try it without the @bouncy decoration. Granted, the code looks like a serious case of Haskell envy, but after recursion and tail call optimization being cryptic was just the logical consequence ;-) Mick. -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
On Oct 18, 4:20 pm, MRAB wrote: > Benjamin Middaugh wrote: > > Thanks to everyone who helped with my query on reversing integers. I > > have one more simple problem I'm having trouble solving. I want to check > > a number for palindromic behavior (reading the same backwards and > > forwards). So if I have an integer 1457 it can tell me this is not the > > same from both ends but 1551 is. I think the simplest way would be to > > work inwards from both ends checking digits for equality, but I don't > > know enough (yet) to do this. > > > All help is much appreciated. > > It's a palindrome if it's the same as its reverse. You already know how > to reverse it, and you should already know how to check whether two > things are the same, so... :-) Something like: def is_palidrome (n): return str(n) == ''.join (reversed (str(n))) which will return True if integer n is a palidromic or False otherwise. -- http://mail.python.org/mailman/listinfo/python-list
Re: restriction on sum: intentional bug?
Carl Banks wrote: On Oct 18, 4:07 pm, Ethan Furman wrote: Dave Angel wrote: Earlier, I would have agreed with you. I assumed that this could be done invisibly, with the only difference being performance. But you can't know whether join will do the trick without error till you know that all the items are strings or Unicode strings. And you can't check that without going through the entire iterator. At that point it's too late to change your mind, as you can't back up an iterator. So the user who supplies a list with mixed strings and other stuff will get an unexpected error, one that join generates. To put it simply, I'd say that sum() should not dispatch to join() unless it could be sure that no errors might result. How is this different than passing a list to sum with other incompatible types? Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class Dummy(object): ... pass ... >>> test1 = [1, 2, 3.4, Dummy()] >>> sum(test1) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'float' and 'Dummy' >>> test2 = ['a', 'string', 'and', 'a', Dummy()] >>> ''.join(test2) Traceback (most recent call last): File "", line 1, in TypeError: sequence item 4: expected string, Dummy found Looks like a TypeError either way, only the verbage changes. This test doesn't mean very much since you didn't pass the the same list to both calls. The claim is that "".join() might do something different than a non-special-cased sum() would have when called on the same list, and indeed that is true. Consider this thought experiment: class Something(object): def __radd__(self,other): return other + "q" x = ["a","b","c",Something()] If x were passed to "".join(), it would throw an exception; but if passed to a sum() without any special casing, it would successfully return "abcq". Thus there is divergence in the two behaviors, thus transparently calling "".join() to perform the summation is a Bad Thing Indeed, a much worse special-case behavior than throwing an exception. Carl Banks Unfortunately, I don't know enough about how join works to know that, but I'll take your word for it. Perhaps the better solution then is to not worry about optimization, and just call __add__ on the objects. Then it either works, or throws the appropriate error. This is obviously slow on strings, but mention of that is already in the docs, and profiling will also turn up such bottlenecks. Get the code working first, then optimize, yes? We've all seen questions on this list with folk using the accumulator method for joining strings, and then wondering why it's so slow -- the answer given is the same as we would give for sum()ing a list of strings -- use join instead. Then we have Python following the same advice we give out -- don't break duck-typing, any ensuing errors are the responsibility of the caller. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: slicing return iter?
En Sun, 18 Oct 2009 23:07:40 -0200, Raymond Hettinger escribió: [Raymond] > If it really is a sequence (with len and getitem), you can write your > own indexing iterator: > def myslice(seq, start, stop, step): > 'Allow forward or backwards iteration over a subslice' > for i in range(start, stop, step): > yield seq[i] [StarWing] Thank you. but it can't support negative index :-( The negative index is handled by the line, "yield seq[i]". s[-2:-5:-1] == ''.join(myslice(s, -2, -5, -1)) True s[-5:-2:1] == ''.join(myslice(s, -5, -2, 1)) True But not always: py> s[10:-1:1]==''.join(myslice(s, 10, -1, 1)) False py> s[-10:25:1]==''.join(myslice(s, -10, 25, 1)) False You have to take the sequence length into account before computing the range, not after. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleXMLRPCServer clobbering sys.stderr? (2.5.2)
> > I was having a mysterious problem with SimpleXMLRPCServer. (I am using > > Python 2.5.2) > > I'd start updating Python to the latest 2.5 release: 2.5.4 Ubuntu doesn't have 2.5.4. :( > > The request handlers were sometimes failing without any error message > > to the log output. > > > What I discovered was perplexing. > > I had some 'print' statements in the handers that, assuming the > > request would be handled, would print just fine. When I switched to > > 'print >> sys.stderr', the request handlers would just fail > > completely, and not make the sys.stderroutput that I desired. > > Perhaps you need to flush the file also? sys.stderr.flush() Flushing will not help, because it will be too late. It is almost like when I write to sys.stderr, the XMLRPC connection just hangs up or something like that. > XMLRPCServer doesn't reassign or alter sys.stderr, just uses it in the > log_message method. I'd look in some other place... Here's what I see: * If I use logging to write the output, I don't see any output in the server log, but the client gets correct results. * If I use sys.stderr to write the output, I don't see any output in the server log AND the client gets INcorrect results. * If I use sys.stdout to write the output, I DO see any output in the server log AND the client gets correct results. Why does only sys.stdout work within XMLRPCServer registered methods? Thanks, Joseph -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleXMLRPCServer clobbering sys.stderr? (2.5.2)
> Here's what I see: > * If I use logging to write the output, I don't see any output in the > server log, but the client gets correct results. > * If I use sys.stderrto write the output, I don't see any output in > the server log AND the client gets INcorrect results. > * If I use sys.stdout to write the output, I DO see any output in the > server log AND the client gets correct results. Oh, one more thing. If I write sys.stdout and then issue: sys.stdout.flush() It appears that the handler aborts at that point and gets no further into the method. Why would this happen? Thanks, Joseph -- http://mail.python.org/mailman/listinfo/python-list
Re: restriction on sum: intentional bug?
On Sun, 18 Oct 2009 19:52:41 -0700, Ethan Furman wrote: > This is obviously slow on strings, but mention of that is already in the > docs, and profiling will also turn up such bottlenecks. Get the code > working first, then optimize, yes? Well, maybe. Premature optimization and all, but sometimes you just *know* something is going to be slow, so you avoid it. And it's amazing how O(N**2) algorithms can hide for years. Within the last month or two, there was a bug reported for httplib involving repeated string concatenation: http://bugs.python.org/issue6838 I can only imagine that the hidden O(N**2) behaviour was there in the code for years before somebody noticed it, reported it, spent hours debugging it, and finally discovered the cause and produced a patch. The amazing thing is, if you look in the httplib.py module, you see this comment: # XXX This accumulates chunks by repeated string concatenation, # which is not efficient as the number or size of chunks gets big. > We've all seen questions on this > list with folk using the accumulator method for joining strings, and > then wondering why it's so slow -- the answer given is the same as we > would give for sum()ing a list of strings -- use join instead. Then we > have Python following the same advice we give out -- don't break > duck-typing, any ensuing errors are the responsibility of the caller. I'd be happy for sum() to raise a warning rather than an exception, and to do so for both strings and lists. Python, after all, is happy to let people shoot themselves in the foot, but it's only fair to give them warning the gun is loaded :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: python along or bash combined with python (for manipulating files)
On Tue, Oct 13, 2009 at 11:18 PM, TerryP wrote: > On Oct 14, 2:13 am, Peng Yu wrote: >> Bash is easy to use on manipulating files and directories (like change >> name or create links, etc) and on calling external programs. For >> simple functions, bash along is enough. However, bash does not support >> the complex functions. Python has a richer library that could provide >> support for complex functions (such compute the relative path between >> two paths). >> >> I'm wondering for a task that can not be done with bash along whether >> it would be better to do in pure python or with a mix of both python >> and bash. What I care is mostly coding speed and a little bit >> maintainability (but not much). Can somebody provide some experience >> on when to combine python and bash and when to use pure python? > > bash can **not** manipulate files and directories beyond things like > the '>' and '>>' I/O redirections, and some minor loading/saving of > state data from/to files (command history, directory stack, etc). Most > of what you refer to are **separate operating system specific > programs** and have absolutely nothing to do with the shell. > > Very sophisticated scripts are possible using bash and ksh, there is > even a form of ksh that has tk capabilities! (tksh). The Python and > Bourne-derived languages are however fundamentally different > creatures, and use very different data models. You should **not** > write Python (or Perl) scripts as if they were shell scripts -- doing > so is very bad practice. When you want a shell script, write a shell > script. When you write a Python script, write a Python script. It > really is that simple. > > > As a rule of thumb, when you have need of data structures beyond what > scalar strings and very simple word lists can provide -- you should > use Python. bash and ksh provide support for arrays, and ksh even has > dictionaries! (Hashes in Perl speak.) That makes programming in bash/ > ksh more robust then pure sh, but also less portable. The best time to > use bash is when you require bash specific features, other wise don't > use bash. The same can be said for ksh. Do you know what are bash and ksh specific features? Is there a thing that bash/ksh can do but python can not do? > When the words array, dictionary, class, object, and/or using multiple > source files comes to mind when implementing a program - you probably > want to use Python, Perl, Ruby, or some other general programming > language, not a shell scripting language like bash. > > You should be cautious to avoid mixing bash and Python code in one > file. > > > > If maintainability is not a factor in what you are writing, then you > should probably not be writing code in any language unless it is the > language of Mathematics (and even then, maintainability is a wise > consideration). > > -- > TerryP. > Just Another Programmer. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
On Oct 19, 12:32 pm, [email protected] wrote: > On Oct 18, 4:20 pm, MRAB wrote: > > > Benjamin Middaugh wrote: > > > Thanks to everyone who helped with my query on reversing integers. I > > > have one more simple problem I'm having trouble solving. I want to check > > > a number for palindromic behavior (reading the same backwards and > > > forwards). So if I have an integer 1457 it can tell me this is not the > > > same from both ends but 1551 is. I think the simplest way would be to > > > work inwards from both ends checking digits for equality, but I don't > > > know enough (yet) to do this. > > > > All help is much appreciated. > > > It's a palindrome if it's the same as its reverse. You already know how > > to reverse it, and you should already know how to check whether two > > things are the same, so... :-) > > Something like: > > def is_palidrome (n): > return str(n) == ''.join (reversed (str(n))) > > which will return True if integer n is a palidromic or False > otherwise. _Not_ providing the code was MRAB's entire point here. It's nice to show that you're clever and all, but that doesn't really help the OP learn. -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks
On Oct 19, 10:01 am, flebber wrote: > Hi > > I have been searching through the vast array of python > frameworkshttp://wiki.python.org/moin/WebFrameworksand its quite astounding > the > choice available. > > I am looking at using a web framework for my personal project which > isn't actually aimed at developing a website as such. However I deduce > that rather than creating a gui application and screen input for data, > I can use a web browser for this and have a great array of tools to > format input screens and output display formats. > > Since I will be retreiving information from several websites (usually > csv files) formatting them and submitting them to a database and > creating queries and printouts based on them most frameworks seem to > handle this basically with ease and for any complex queries most > support SqlAlchemy. > > Is it simply a case of just picking one and starting and I would find > it hard to be dissapointed or is there a few special considerations to > make, though I am unsure what they are? > > Most obvious ones I am considering are Django (Of course), Pylons > includes SqlAlchemy, Sql Object and templating and I here turbogears > plans to sit on top of this platform. Zope I am considering but I am a > little confused by this. The are heaps of others but not sure how to > narrow the selection criteria. > > How/Why woul you split Django and Pylons let alone the others? > > Database likely to be MySQl I guess what makes it so interesting is that there appear to be so man high quality options. Its astounding. -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
On Oct 18, 9:45 pm, alex23 wrote: > On Oct 19, 12:32 pm, [email protected] wrote: > > On Oct 18, 4:20 pm, MRAB wrote: > > > Benjamin Middaugh wrote: > > > > Thanks to everyone who helped with my query on reversing integers. I > > > > have one more simple problem I'm having trouble solving. I want to check > > > > a number for palindromic behavior (reading the same backwards and > > > > forwards). So if I have an integer 1457 it can tell me this is not the > > > > same from both ends but 1551 is. I think the simplest way would be to > > > > work inwards from both ends checking digits for equality, but I don't > > > > know enough (yet) to do this. > > > > > All help is much appreciated. > > > > It's a palindrome if it's the same as its reverse. You already know how > > > to reverse it, and you should already know how to check whether two > > > things are the same, so... :-) > > > Something like: > > > def is_palidrome (n): > > return str(n) == ''.join (reversed (str(n))) > > > which will return True if integer n is a palidromic or False > > otherwise. > > _Not_ providing the code was MRAB's entire point here. It's nice to > show that you're clever and all, but that doesn't really help the OP > learn. I hardly think that code is evidence of cleverness. Re helping the OP learn... MRAB (and gherron) were wrong. One, it was suggested without any evidence the the OP was "probably" asking about homework. My observation over several years is that this group has a very poor record of identifying homework problems. And if someone can conclude that the OPs problem was homework with no evidence, then I can conclude that it wasn't, without evidence, equally validly. As for learning better by "working it out oneself", that is a myth. I know it is not (universally) true by counter-example: I once asked a question here got several answers. One person explained the behavior I'd not understood in a single sentence. Another provided a long transcript of an interactive Python session intended to demonstrate the behavior and its origin. I read the first response and it was immediately clear what my misunderstanding was, and why Python was doing what I hadn't understood. I never bothered with the long demo since it would have been a waste of my time, despite that the poster had obviously put significant time into writing it. I realize that in many courses the pedagogy involves working out the basic ideas, theorems, etc. But the environment of a course taught by an instructor thoughorly covering an organized range of topics is totally different than a usenet newsgroup. Different people have different goals and learning styles. I gave the OP another option. He can choose whichever helps him learn most effectively. That is a *good* thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
Hi, Would someone explain how str[::-1] work? I'm new to Python and I only saw so far the str[begin:end] notation. What is the second colon? Thanks, Laszlo > Here is a simplistic version that doesn't use fancy math: > str(24) > '24' str(24)[::-1] > '42' int(str(24)[::-1]) > 42 -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a Number for Palindromic Behavior
[email protected] wrote: > One, it was suggested without any evidence the the OP was > "probably" asking about homework. My observation over > several years is that this group has a very poor record > of identifying homework problems. And if someone can > conclude that the OPs problem was homework with no evidence, > then I can conclude that it wasn't, without evidence, > equally validly. I've always seen the accusation of "homework problem" to be less about homework and more about an attempt to get other people to provide working code. In this case, the absence of evidence (ie posting what code has been tried) _is_ indicative of such problems. This isn't about being churlish, it's about not being able to identify the experience level at which such posters are operating, about not wasting time providing answers that have already been tried & rejected etc etc > As for learning better by "working it out oneself", that is > a myth. MRAB broke the OP's request down into already-understood-by-the-OP operations; being able to extrapolate from that is _essential_ to becoming a programmer. I'm not sure how you think that giving someone an answer will ever help them be able to answer similar questions themselves. The process followed to achieve the solution is what is important here, not the solution itself. Give a programmer a code fragment, and you've helped him for a day. Teach a programmer to code, however... -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
On Sun, Oct 18, 2009 at 10:53 PM, Jabba Laci wrote: > Hi, > > Would someone explain how str[::-1] work? I'm new to Python and I only > saw so far the str[begin:end] notation. What is the second colon? Specifies the step value, as in: foo[start:stop:step] When not specified it, defaults to 1. So foo[::-1] gives the entire sequence backwards. Analogously, foo[::2] gives every other item in the sequence, forwards. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
On Oct 19, 3:53 pm, Jabba Laci wrote: > Would someone explain how str[::-1] work? I'm new to Python and I only > saw so far the str[begin:end] notation. What is the second colon? Slice notation is of the form [start:stop:step]. start defaults to the start of the sequence, stop to the end, and step to 1. So a slice of [::-1] returns the full sequence in reverse, stepping back one character at a time from the end of the sequence to the beginning. The only mention I could find was http://docs.python.org/dev/3.0/library/functions.html#slice -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse Iteration Through Integers
alex23 wrote: > The only mention I could find was > http://docs.python.org/dev/3.0/library/functions.html#slice No idea why that link was the one that came up, this is more appropriate: http://docs.python.org/3.1/library/functions.html#slice -- http://mail.python.org/mailman/listinfo/python-list
Re: help to convert c++ fonction in python
You wrote: > >For the love of baby kittens, please, please, please tell me that >you do not believe this securely encrypts your data. The original poster asked to have two C++ functions converted to Python. That's what I did, using the same names as the original. I neither know nor care how they are used, but let us hope the O.P. understands their limitations. These are roughly as useful as the old ROT13 encoding. -- Tim Roberts, [email protected] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against "while True:" loops
On Sunday, 18 October 2009 11:31:19 Paul Rubin wrote: > Hendrik van Rooyen writes: > > Standard Python idiom: > > > > if key in d: > > d[key] += value > > else: > > d[key] = value > > The issue is that uses two lookups. If that's ok, the more usual idiom is: > > d[key] = value + d.get(key, 0) I was actually just needling Aahz a bit. The point I was trying to make subliminally, was that there is a relative cost of double lookup for all cases versus exceptions for some cases. - Depending on the frequency of "some", I would expect a breakeven point. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
