Re: Power with modulu

2004-12-05 Thread Bengt Richter
e M take an optional initialization parameter to override what's set with mmod. Or if you override all the time, not bother with mmod. Depends on what you need & how you are going to use the stuff. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

[BUG] IMO, but no opinions? Uncle Tim? was: int(float(sys.maxint)) buglet ?

2004-12-05 Thread Bengt Richter
.maxint-1) ('-2147483648L', '-2147483648') or maybe at least check for equality of these?: >>> type(int(float(sys.maxint))), type(sys.maxint) (, ) >>> type(int(float(-sys.maxint-1))), type(-sys.maxint-1) (, ) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: [BUG] IMO, but no opinions? Uncle Tim? was: int(float(sys.maxint)) buglet ?

2004-12-07 Thread Bengt Richter
On Mon, 6 Dec 2004 10:30:06 -0500, Tim Peters <[EMAIL PROTECTED]> wrote: >[Bengt Richter] >> Peculiar boundary cases: >> >> >>> 2.0**31-1.0 >> 2147483647.0 >> >>> int(2147483647.0) >> 2147483647L >> >>> int(

Re: [BUG] IMO, but no opinions? Uncle Tim? was: int(float(sys.maxint)) buglet ?

2004-12-08 Thread Bengt Richter
On Tue, 7 Dec 2004 16:44:56 -0500, Tim Peters <[EMAIL PROTECTED]> wrote: >[Tim Peters] >>> ... there's no promise anywhere, e.g., that Python will return an int >>> whenever it's physically possible to do so. > >[Bengt Richter] >> Ok, I understa

Re: How do I do this? (eval() on the left hand side)

2004-12-09 Thread Bengt Richter
nt call last): File "", line 1, in ? File "", line 6, in __getattr__ AttributeError: 'Magic' object has no attribute 'z' >>> o.z = "y" >>> o().z 'a' >>> o.z 'y' Anyway, getattr/setattr functionality provides the primal cauldron for python magic, if you want to cook something up, and incantations usually involve prefixing the name of a magic instance to your spell(ing)s ;-) Add descriptors for extra spice ... Double, double, toil and trouble... oh, wait, that's for floating point ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))

2004-12-09 Thread Bengt Richter
7;x']",d['x'] ... print "D['x']", D['x'] ... return d, D, locals() ... >>> d,D,L = f() x 3 d['x'] 3 x 3 d['x'] 5 D['x'] 3 d['x'] 5 D['x'] 7 >>> d {'x': 3, 'd': {...}, 'D': {'x': 7, 'd': {...}}} >>> D {'x': 7, 'd': {'x': 3, 'd': {...}, 'D': {...}}} >>> L {'x': 3, 'd': {...}, 'D': {'x': 7, 'd': {...}}} >>> L['d']['x'] # not 5 3 >>> L['D']['x'] # is 7 7 >>> d['x'] 3 >>> D['x'] 7 >>> Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Wrapper objects

2004-12-09 Thread Bengt Richter
7;strange', 'stuff') >>> o3 'strange' >>> o3.otherdata ('stuff',) >>> o3[2:] 'range' >>> >>> o3.z Traceback (most recent call last): File "", line 1, in ? File "", line 16, in __getattr__ AttributeError: Wrapped 'Wrapped_str' object has no attribute 'z' Not tested beyond what you see ;-) This doesn't wrap setting attributes on the wrapped object, so setting attributes sets them on the wrapper itself, but that could be fixed. Now what was it you wanted to use a wrapper for? ;-) Note: >>> o3 += 'fail' >>> o3 'strangefail' >>> type(o3) So if you want new wrapped instances as results from various ops, we need some more code ;-) Another time ... (cf. a recent post of mine re wrapping complex as a point type). Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Find Items & Indices In A List...

2004-12-10 Thread Bengt Richter
ter method... > >Thanks for every suggestion. > One way: >>> mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10] >>> [i for i,v in enumerate(mylist) if v==1] [1, 2, 3, 4, 9] Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Wrapper objects

2004-12-10 Thread Bengt Richter
On 10 Dec 2004 09:33:51 -0800, [EMAIL PROTECTED] wrote: >Bengt Richter wrote: >> On 9 Dec 2004 06:11:41 -0800, [EMAIL PROTECTED] (Egil M?ller) wrote: >> >> >So my naive implementation of a wrapper class, >> > >> > >> >class wrapper(o

Re: Find Items & Indices In A List...

2004-12-10 Thread Bengt Richter
1 >... > >>> getindices([0,1,1,1,1,5,6,7,8,1,10], equalsone) >[1, 2, 3, 4, 9] > >>> def f(v): >...return pow(v, 3, 4) == 3 >... > >>> getindices([0,1,1,1,1,5,6,7,8,1,10], f) >[7] > Conclusion: Python is programmer's Lego ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Wrapper objects

2004-12-11 Thread Bengt Richter
Foo (time n/a) 'orig Foo cvar ;-)' <__main__.Foo object at 0x00901630> Foo (time n/a) 'orig Foo cvar ;-)' <__main__.Foo object at 0x00901390> Wrapped_Wrap_one_Foo W1: Sat Dec 11 01:16:40 2004 'Wrap_one cvar' Wrap_one {'bar': 'this is bar'} repr: <__main__.Wrapped_Wrap_one_Foo object at 0x00901390> Wrapped_Wrap_two_Foo W2: Sat Dec 11 01:16:40 2004 'orig Foo cvar ;-)' Wrap_two (22, 33) repr: <__main__.Wrapped_Wrap_two_Foo object at 0x00901390> Foo (time n/a) 'orig Foo cvar ;-)' <__main__.Foo object at 0x00901390> Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: thread/queue bug

2004-12-11 Thread Bengt Richter
# the ';' are not eliminated > if wds[0] == 'S': recvsucc(msg); continue > if wds[0] == 'E': recvevent(msg); continue > if wds[0] == 'ACK': recvack(msg[4:]); continue > if wds[0] == 'MONITOR': > if addr not in monitorlist: > print 'This line ALWAYS PRINTS' > queuelist.append( Queue(0) ) Why are you apparently creating *new* queues in this thread that you are not using and appending them to queuelist in the main thread? Are you testing to see how many can be created, or for some Queue creation bug? What do you get if you print 'queuelist length = %s'%len(queuelist) here? How often are you getting 'MONITOR'? > ## The above fails if this code is imported Imported from where? Do you mean that this code works if it is embedded in some larger code, and if you put an import of this at the top of that code it doesn't work? That would not only be moving the source, but also the point of invocation. I.e., the import *executes* what you import once, putting the result in the module's global name space (other than code that explicitly accesses other modules etc.) Do you need to wrap part of this in a function that you can call *after* importing the definitions? If your real app has multiple threads accessing a main thread queuelist without a lock, you might want to look closely and see if that needs to be a queue mechanism itself. > ## It doesn't matter whether it is imported > ##as .py or .pyc > ## also mq = Queue(0); queuelist.append(mq) # fails > print 'This line ALWAYS PRINTS if i execute this source' > print 'but NEVER PRINTS if I import ' > print 'this source from a 1 line program' > print 'Thats weird' > monitoron.append( 1 ) > monitorlist.append( addr ) > Do you want all the following to be executed once at the point of importing this? >queuelist = [Queue(0)] What is this for? (oops, I hope I restored the above line correctly) > > >listenersocket = socket(AF_INET,SOCK_DGRAM) >listenersocket.bind(ListenAddr) > >procm = Thread(target=procmsgs) >procm.start() >listenr = Thread(target=listener) >listenr.start() > >## Then start a bunch of other threads and queuea. > > >Don't spend a lot of time on this, not worth it. >I just thought someone might have experienced >something similar. > Just some thoughts. HTH. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Persistent objects

2004-12-12 Thread Bengt Richter
hought out. But it's alluring enough that I thought I'd ask if >anyone else sees something to pursue here. The strings-only version would let you build various pickling on top of that for other objects, and there wouldn't be so much re-inventing to do ;-) That seems like an evening's project, to get a prototype. But no time now... Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: create lowercase strings in lists - was: (No subject)

2004-12-16 Thread Bengt Richter
rs occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. to compete well, if table setup were for free (otherwise, UIAM, table should be ''.join([chr(i) for i in xrange(256)]) for identity translation, and that might pay for a couple of .replace loops, depending). Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Why are tuples immutable?

2004-12-17 Thread Bengt Richter
... except ValueError: ... raise KeyError, '%r' %key ... self.mutvals.append(value) ... def __repr__(self): ... return '' % (dict.__repr__(self), ... ', '.join(['%r:%r'%t for t in zip(self.mutkeys, self.mutvals)])) ... >>> md = MKD(a=1,b=2) >>> md >>> k12 = [1,2] >>> k13 = [1,3] >>> md[k12]=12 >>> md >>> md[k13]=13 >>> md >>> k12 [1, 2] >>> k12[1]+=1 >>> k12 [1, 3] >>> md[k12] 12 >>> md ^k12^^ ^k13^^ >>> del md[k12] >>> md ^k13^^ >>> md[k12] 13 >>> del md['a'] >>> md >>> k12 [1, 3] >>> k12[1]-=1 >>> k12 [1, 2] >>> md[k12] Traceback (most recent call last): File "", line 1, in ? File "", line 35, in __getitem__ KeyError: '[1, 2]' But k13 is bound to the dicts mutable key, so >>> k13 [1, 3] >>> k13[1]-=1 it shows up in the repr of the dict: >>> md and k12's value now matches, so it can retrieve the value >>> md[k12] 13 >>> Any new thoughts? ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: ".>>>" is a good idea! (OT, was: Re: do you master list comprehensions?)

2004-12-17 Thread Bengt Richter
tinuing to hold the shift key down to select a box of text (need not be at edges) this can also scroll through buffer as necessary to select more than can be visible at one time. Just keep holding down shift. press enter to capture box of text to clipboard paste as usual with ctrl-v ins some apps, sh

Re: uptime for Win XP?

2004-12-12 Thread Bengt Richter
tools subdirectory under the latter. Pstat prints a snapshot of pmon plus drivers info which means info about every process and thread running as well as drivers loaded, so the above threw away a lot of lines to get the one: [23:38] C:\pywk\clp>pstat|wc 442 3350 27404 ;-) There's got to be something leaner though. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: better lambda support in the future?

2004-12-17 Thread Bengt Richter
via('a') ... def dispatch(): return 'dispatched a' ... >>> @dispvia('b') ... def dispatch(): return 'dispatched b' ... >>> @dispvia('c') ... def dispatch(): return 'dispatched c' ... >>> for t in sorted(dispatch.items()): print '%5s: %r'%t ... a: b: c: >>> for k in dispatch: print dispatch[k](), ... dispatched a dispatched c dispatched b >>> for k in sorted(dispatch): print dispatch[k](), ... dispatched a dispatched b dispatched c Hm... this seems like an interesting opening ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Cool object trick

2004-12-18 Thread Bengt Richter
>print "%(title)s was written by %(author)s" % vars(m) > >>> m = object() >>> m.title = 'not so fast ;-)' Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'title' >>> m=type('',(),{})() >>> m.title = 'not so fast ;-)' >>> m.title 'not so fast ;-)' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: better lambda support in the future?

2004-12-18 Thread Bengt Richter
On Sat, 18 Dec 2004 03:05:08 -0500, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > >"Bengt Richter" <[EMAIL PROTECTED]> wrote in message >news:[EMAIL PROTECTED] >> Looks like your standard pattern could be updated: >> >> >>> dis

Re: better lambda support in the future?

2004-12-18 Thread Bengt Richter
On Sat, 18 Dec 2004 14:39:54 -0500, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > >"Bengt Richter" <[EMAIL PROTECTED]> wrote in message >news:[EMAIL PROTECTED] >> On Sat, 18 Dec 2004 03:05:08 -0500, "Terry Reedy" <[EMAIL PROTECTED]>

Re: Easy "here documents" ??

2004-12-19 Thread Bengt Richter
_ would do what one might like. A sys._getframe(depth).f_localnamespace frame attribute as a way of peeking into various local namespaces via their __localnamespace__ objects might make name-chasing easier and more regular there too. Just a thought, not thought out ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: expression form of one-to-many dict?

2004-12-19 Thread Bengt Richter
be def setdefault(self, key, ``default=None): ... default = eval(default) ... etc BTW, note that def foo(``default=expr): ... and def foo(``default=``expr): ... could mean different things, depending on preferred semantics and ``expr as a generally valid expression. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Is this a good use for lambda

2004-12-19 Thread Bengt Richter
, lambda:'two', lambda:'three'] >>> for use in xrange(2): ... for i in xrange(3): ... print '%susing fun[%s] => %r' %('re'*(use>0), i, funs[i]()) ... using fun[0] => 'one' using fun[1] => 'two' using fun[2] => 'three' reusing fun[0] => 'one' reusing fun[1] => 'two' reusing fun[2] => 'three' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: dot products

2004-12-19 Thread Bengt Richter
print '%3s * %-3s => %s (tot %s)' %(x, y, prod, self.tot) ... return prod ... >>> sum(map(OpShow(), a, b)) 0 * 5 => 0 (tot 0) 1 * 6 => 6 (tot 6) 2 * 7 => 14 (tot 20) 3 * 8 => 24 (tot 44) 4 * 9 => 36 (tot 80) 80 Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: A rational proposal

2004-12-20 Thread Bengt Richter
Rational Type to Python, Craig, Zadka > (http://www.python.org/peps/pep-0239.html) >.. [#PEP-240] Adding a Rational Literal to Python, Craig, Zadka > (http://www.python.org/peps/pep-0240.html) >.. [#PEP-327] Decimal Data Type, Batista > (http://www.python.org/peps/pep-0327.html) >.. [#PEP-239-implicit] PEP 240 adds a new literal type to Pytbon, > PEP 239 implies that division of integers would > change to return rationals. > > >Copyright >= > >This document has been placed in the public domain. > > > >.. > Local Variables: > mode: indented-text > indent-tabs-mode: nil > sentence-end-double-space: t > fill-column: 70 > End: Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Easy "here documents" ??

2004-12-20 Thread Bengt Richter
;> >>> s = """ ... v = ${variable1} ... v2's value is: ${variable2} ... """ >>> print s.replace('${','%(').replace('}',')s') % locals() v = 1 v2's value is: 2 Better would be to write it with %(...)s in the first place though, or you may need regex help for correct conversion (if involve other uses for the ${} chars). Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: convert \uXXXX to native character set?

2004-12-21 Thread Bengt Richter
lyph whose unicode code is u'\u4e00' >>> list(ichi.encode('big5')) ['\xa4', '@'] going from big5-encoded str back to unicode then takes de-coding: >>> '\xa4@'.decode('big5') u'\u4e00' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Why are tuples immutable?

2004-12-22 Thread Bengt Richter
On 21 Dec 2004 10:37:20 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote: >Op 2004-12-18, Bengt Richter schreef <[EMAIL PROTECTED]>: >>> >>>As it turns out, python makes no difference in difficulty for making >>>either mutable or immutable objects usable as

Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-25 Thread Bengt Richter
lease DYFR ;-) > >I don't really recommend that option. > >A potentially more fruitful course is the dictionary variants identity_dict or >override_dict. The current dict() implementation forces the use of hash() for >sorting into hash buckets and "x == y" for key matching. An identity_dict >variant that uses id() (or object.__hash__ in Jython) and "x is y" would seem >to >quite happily meet the use cases you have posted in this thread, without >silencing currently detected bugs. IMO it's a matter of going back to what you really want your ideal dict to do, which I presume is to maintain a set of unique defined keys, by whatever means, and have arbitrary values associated with those unique keys, and be able to use an arbitrary object to see if that object is equal in some sense to one of the defined and unique (in the same equality sense) keys, and if so to retrieve the associated value object, and raise KeyError or give some error indication if not. Then you can see about optimizing an implementation to suit your intended usage patterns. You just need to DYFR ;-) > >override_dict is probably just a case of compulsive overgeneralisation that >can >be ignored for the time being :) At least until requirements are defined ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Unicode entries on sys.path

2004-12-27 Thread Bengt Richter
stem references such as sys.path need to be virtualized to carry relevant file system encoding and protocol info etc. That could cover synthetic or compressed info sources too, IWT. Homogeneous package representation could be a similar problem, I guess. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: FutureWarning

2004-12-27 Thread Bengt Richter
ing to indicate how to interpret, like the old 0x prefix, but not 0x obviously. '0b' for binary would be nice and concise, but maybe something that could express the base value easily would be good too. Since there's no upper case '0' or '1' we could use '0Bn:d' -- which would make int('0B2:10') == int('0B8:76') == int('0B10:98') == int('0B16:fe') == -2 '0b' could be a synonym for '0B2:' and '0h' for '0B16:' Perhaps there could be string formatting to match, e.g., '%.b' # or B for uppercase. So '%.2b'%3 => '011' and '%04.16B'%-3 => 'FFFD' and if you wanted to create literals, you would write '0b2:%.2b'%3 => '0b2:011' and '0b16:%04.16B'%-3 => '0b16:FFFD' respectively. Etc., etc. Oops, that ... acc += digits.index(c)*B**i above should have been ... acc += digits.index(c.lower())*B**i It's obviously not optimized, and there may be bugs, but this should at least communicate the idea (a little modified from Aug 2003 ideas ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-28 Thread Bengt Richter
On Sun, 26 Dec 2004 12:17:42 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> I take it you are referring to regular python dictionaries, > >Correct. So I'll skip over the sections talking about alternate lookup >strategies in my reply. Co

Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-29 Thread Bengt Richter
On Wed, 29 Dec 2004 22:47:55 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote: >said> > >Bengt Richter wrote: >> A second time a key may be hashed is when it is used as a lookup key. This >> can be a reference to >> the identical key object first used, or

Re: Other notes

2004-12-29 Thread Bengt Richter
ence rules of the macro-rewritten source. Which might cover a fair amount of useful ground. Needs to be explored though. E.g., x .op1. y .op2. z => op2(op1(x, y), z) But you could override with parens in the ordinary way: x .op1. (y .op2. z) => op1(x, op2(y, z)) But 2 * x + 3 .op1. y => 2 * x + op1(3, y) Etc. Well, something to think about ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Other notes

2004-12-29 Thread Bengt Richter
t;> You also need to worry about binding order. At the very least, you >> can specify that all new operators bind left to right. But that might >> not be what you want. >> >Associativity and precedence will also have to affect the parsing of the >code, of course. Overall this would be a very ambitious change. > My suggestion if implemented with left-right priority would be easy to implement (I think ;-) And you could always override order with parens. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Other notes

2004-12-29 Thread Bengt Richter
On Thu, 30 Dec 2004 03:37:38 GMT, Andrew Dalke <[EMAIL PROTECTED]> wrote: >Bengt Richter: >> OTOH, there is precedent in e.g. fortran (IIRC) for named operators of the >> form .XX. -- e.g., .GE. for >= so maybe there could be room for both. > >> Hm, you c

Re: Other notes

2004-12-29 Thread Bengt Richter
On Thu, 30 Dec 2004 03:55:12 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: [.. buncha stuff alzheimersly based on x.attr not being parsed as x.attr ;-/ ] > from rational import rat as RAT > > if x .RAT. y > 1 .RAT. 3: do_it() > >or > your turn ;-) > Andrew got there

Re: Other notes

2004-12-29 Thread Bengt Richter
On Thu, 30 Dec 2004 04:46:25 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: [...] >Ok, well, that's happened to me before ;-) >We'll have to find a way to make it illegal, but it's not likely to be quite >as clean. > >x ..OP y >x ./OP y >

Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-30 Thread Bengt Richter
On Thu, 30 Dec 2004 17:36:57 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> Essentially syntactic sugar to avoid writing id(obj) ? (and to get a little >> performance >> improvement if they're written in C). I can't believe this thr

Re: Securing a future for anonymous functions in Python

2004-12-30 Thread Bengt Richter
stand. BTW, there are old threads where this and other formats were discussed. I am still partial to the full anonymous def with nesting indentation rules. Syntactic sugar could be provided for useful abbreviations (that could possibly be expanded by the tokenizer -- re which possibilities I haven't seen any discussion than my own recent post, BTW), but I'd like the full capability. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: standard IDE in python 3000 (or beyond)? *semi-newbie*

2004-12-30 Thread Bengt Richter
t stuff seemed to me comparable. I think there are Delphi/python projects, but I haven't pursued them. > > I wish there *were* something equivalent. If Jim Hugunin can persuade >Microsoft to fully support Python in Visula Studio .NET they'd have at >least one more customer. MSVS is very seductive. But so is open source independence ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Securing a future for anonymous functions in Python

2004-12-30 Thread Bengt Richter
erve a valuable purpose >without quite as much risk of code pollution. There's always the temptation to be enforcer when being persuader is not the easiest ;-) (BTW, again, by closure, do you really mean deferred-action-thingie?) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Securing a future for anonymous functions in Python

2004-12-30 Thread Bengt Richter
On Thu, 30 Dec 2004 17:39:06 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: > >> On Thu, 30 Dec 2004 15:15:51 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote: >> >>>Mimicking function-def indentation inside of another function's a

Re: how can I put a 1Gb file in a zipfile??

2005-03-21 Thread Bengt Richter
lot of ground ISTM. One could argue pro and con about supporting virtual mounts into both unix and windows-style paths. >import zipfile >z =3D zipfile.ZipFile("/tmp/test.zip", "w", zipfile.ZIP_DEFLATED) >make_4gb_file("/tmp/big") >z.write("/tmp/big") >z.close() ># Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: generating audio signals

2005-03-21 Thread Bengt Richter
the specs for any .wav file (i.e., sampling frequency, bytes per sample, channels, etc.) I don't recall at the moment whether you have to deal with signed or offset amplitude values, but it won't be hard. This won't play the sounds though. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: beeping portably

2005-03-21 Thread Bengt Richter
be you can make one just writing to some /dev/somethingorother, and conditionally set up the appropriate thing for limited platform-appropriateness if not independence. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: generating audio signals

2005-03-21 Thread Bengt Richter
ne function call - wave.Wave_read.getparams() >import wave >wave.open("filename","b") >wave.Wave_read.getparams() > Yeah, I know ;-) I expected the OP to discover that really quick, and enjoy an early tidbit of success, maybe printing the parameters in a pretty format

Re: simultaneous copy to multiple media

2005-03-21 Thread Bengt Richter
bility of temporarily memory-resident readonly file data buffers? I guess it would vary, and you could lose or gain by single or multifile source strategy, depending ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Python limericks (was Re: Text-to-speech)

2005-03-21 Thread Bengt Richter
ur blocks express which doth our code transparently dress, delighting the many who view while confounding a relative few ... and rightly conferring to Guido much fame, though Guido van Rossum is only one name. There's a "this" to import for a hint why so many contribute a stint. The beauty, the Zen, the generous ethos attract, But it's not deniable it's a definite fact that that really's not explaining it all: It's a good bet they're having a ball ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: missing? dictionary methods

2005-03-22 Thread Bengt Richter
than particular useful methods. Maybe Pypy will be an easier place to experiment with these kinds of things. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: (noob alert) why doesn't this work?

2005-03-22 Thread Bengt Richter
tagdict = dict((pair[0].strip().lower(), pair[1].strip()) for pair in (line.split('=', 1) for line in os.popen(cmd).readlines()) if len(pair)==2) args = [tagdict.get(tag, '??') for tag in 'artist, album, year, number, genre'.split()] self.wav2mp3(flac, *args) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Re: problems with  character

2005-03-22 Thread Bengt Richter
7;) 'Latin-1:?\xaf\n' >>> Now this is in an NT4 console windows with code page 437: >>> u'Latin-1:\xc2\xbb\n'.encode('cp437','replace') 'Latin-1:?\xaf\n' >>> import sys >>> sys.stdout.write(u'Latin-1:\xc2\xbb\n'.encode('cp437','replace')) Latin-1:?» Notice that the interactive output does a repr that creates the \xaf, but the character is available and can be written non-repr'd via sys.stdout.write. For the heck of it: >>> sys.stdout.write(u'Latin-1:\xc2\xbb\n'.encode('cp437','xmlcharrefreplace')) Latin-1:» I don't know if this is going to get through to your screen ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Python limericks (was Re: Text-to-speech)

2005-03-22 Thread Bengt Richter
On Tue, 22 Mar 2005 03:42:05 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: [...] >A fan of Monty and all was Guido, >which inluenced much of what he'd do. ... Oy. Re-reading => DAPR (Day After Posting Remorse) ;-/ Oh well. Regards, Bengt Richter -- http://mail.python.org/mailman/l

Re: .pth files?

2005-03-22 Thread Bengt Richter
dgy. > >Any clarifications or recommendations? > >Thanks! > I haven't looked at all the ("about 23") hits, but have you tried googling for pth site:python.org/doc ? The first hit looks promising. (BTW, for your next python question, try some relevant words in place of "pth" before posting ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: sorting a dictionary?

2005-03-23 Thread Bengt Richter
>compressing the middle down to > > tmp = [(v,k) for (k,v) in mydict.items()].sorted().reversed() > They added them, but not as list methods: >>> mydict = {'the':358, 'they':29, 'went':7, 'said':65} >>> for v,k in reversed(sorted((v,k) for k,v in mydict.items())): print k,v ... the 358 said 65 they 29 went 7 Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: typo in the library reference?

2005-03-23 Thread Bengt Richter
On Wed, 23 Mar 2005 05:13:45 -0800, Scott David Daniels <[EMAIL PROTECTED]> wrote: [...] >and only now noticed the smiley after it. What is the typogram for >"I feel like an idiot?" I sometimes use variations of *<8^P ;-) Regards, Bengt Richter -- http://mail.python.or

Re: Read from the last line of a file?

2005-03-23 Thread Bengt Richter
yield last # zero-length file has no lines break pos -= bufsize assert pos>=0, 'should not fail' f.seek(pos) lines = (f.read(bufsize)+lines[0]).split(linesep) else: yield lines.pop() + endline endline = '\n' --- Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Changing the value of a for loop index on the fly

2005-03-23 Thread Bengt Richter
some elements of the list, I'm wondering >if it's somehow possible to change the value of "i" to 0 in order not to >get an index error. Any other ideas? >Thanks in advance. > > Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Changing the value of a for loop index on the fly

2005-03-23 Thread Bengt Richter
On Thu, 24 Mar 2005 02:48:28 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: >On Wed, 23 Mar 2005 23:27:54 +0100, "Gabriel F. Alcober" <[EMAIL PROTECTED]> >wrote: > >>Hi! There goes a newbie trouble: >> >>for i in range(0, len(

Re: Python for a 10-14 years old?

2005-03-24 Thread Bengt Richter
ningly beautiful sister who gets all the attention. Or they may identify with their gift and become insufferable narcissistic egotists as a refuge from human isolation and emotional starvation. Or they may become wonderful human beings after all, happy stewards of what becomes a gift to humanity, not just an advantage to exploit meanly. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: An Abridged Python Tutorial

2005-03-24 Thread Bengt Richter
On Thu, 24 Mar 2005 08:37:29 -0800, Michael Spencer <[EMAIL PROTECTED]> wrote: >An Abridged Python Tutorial > very nice ! Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: How to get rid of FutureWarning: hex/oct constants...

2005-03-24 Thread Bengt Richter
t; is a unary minus expression using an absolute value forced by the inadequacy of the literal representation syntax. IOW, IMO '-' + hex_literal_of(abs(x)) is not a decent hex_literal_of(-x) !! Urk and argh... Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: How to get rid of FutureWarning: hex/oct constants...

2005-03-24 Thread Bengt Richter
On Fri, 25 Mar 2005 03:35:29 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: >On Thu, 24 Mar 2005 23:21:39 -, Grant Edwards <[EMAIL PROTECTED]> wrote: > >>How do I get rid of the following warning? >> >> .py:233: FutureWarning: hex/oct constants > sys.maxint w

Re: Version Number Comparison Function

2005-03-25 Thread Bengt Richter
ION overhead is unacceptable? What if we had something like @sticky('fixup') # evaluate binding only first time def cmpver(a , b): def fixup ... ? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Suggesting a new feature - "Inverse Generators"

2005-03-25 Thread Bengt Richter
ong line, long line, long lineand this is shortand this is short > Here is a long line, long line, long lineand this is short > >>> Nice, but I think "record" is a bit opaque semantically. How about group_id or generate_incrementing_unique_id_for_each_group_to_group_by or such? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Suggesting a new feature - "Inverse Generators"

2005-03-25 Thread Bengt Richter
antically. >> How about group_id or >> generate_incrementing_unique_id_for_each_group_to_group_by or such? >> >> Regards, >> Bengt Richter > >Agreed, it's an issue. I think the most natural name is groupby - but that >would cause more trouble. What do

Re: Python 2.4 | 7.3 The for statement

2005-03-25 Thread Bengt Richter
ise StopIteration ... >>> for x in (x for x in xrange(10) if until(x==3)): print x, ... 0 1 2 actually, that until would read better as "notyet" after the "if" Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: regular expression

2005-03-25 Thread Bengt Richter
27;:', '3.') >'3:' >!--! > >any thoughts? > Brute force the exceptional case that happens at the start of the line? >>> import re >>> pattern = re.compile(r'^[.]|(?!\d)[.](?!\d)&

Re: str vs dict API size (was 'Re: left padding zeroes on a string...')

2005-03-25 Thread Bengt Richter
5: reversed 5: super 6: property 6: slice 7: xrange 9: bool 10: object 10: type 16: buffer 19: tuple 22: file 22: open 30: frozenset 33: dict 35: list 38: float 39: complex 44: set 46: int 46: long 53: unicode 56: str Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: regular expression

2005-03-25 Thread Bengt Richter
On Fri, 25 Mar 2005 23:54:32 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> On Sat, 26 Mar 2005 02:07:15 GMT, aaron <[EMAIL PROTECTED]> wrote: >>>>>>pattern.sub(':', '375 mi. south of U.C.B is 3.4 degrees warm

Re: Turn of globals in a function?

2005-03-26 Thread Bengt Richter
y assignment > >>>>b(False): >*** name error here *** > UIAM it should do this if you import b as above. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: How to get rid of FutureWarning: hex/oct constants...

2005-03-27 Thread Bengt Richter
On Sun, 27 Mar 2005 12:48:46 +0200, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> >>> hex(-2*0x4000+0x40047a80) >> __main__:1: FutureWarning: hex()/oct() of negative int will return a signed >&

Re: "static" variables in functions (was: Version Number Comparison Function)

2005-03-29 Thread Bengt Richter
oing the C++ way: piling feature upon feature, adding bells >> and whistles while ignoring or damaging its core design. > >If the core design were better, many "new features" in Python could >have been rendered unnecessary. > Do you have specific recommendations that mi

Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-29 Thread Bengt Richter
t;> for x in int(range(1,8,2)): print x, ... 1 3 5 7 >>> for x in int('123x'): print x, ... 1 2 3 Traceback (most recent call last): File "", line 1, in ? File "", line 7, in ValueError: invalid literal for int(): x Hm, ... ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Finding attributes in a list

2005-03-29 Thread Bengt Richter
te(kw) ... def __repr__(self): return ''%getattr(self, 'name', '(anonymous)') ... >>> players = [ ... Player(name='joe', defense=8, attacking=5, midfield=6), ... Player(name='bob', defense=5, attacking=9, midfield=6), ... Player(name='sam', defense=6, attacking=7, midfield=10)] >>> players [, , ] >>> import operator >>> [p.name for p in sorted(players, key=operator.attrgetter('attacking'), >>> reverse=True)] ['bob', 'sam', 'joe'] And then he could create a Team class which might have players as an internal list, and provide methods for modifying the team etc., and generating various reports or calculating and/or retrieving data. Not to mention properties for dynamically caclulated attributes etc ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: How to execute a cmd line program without invoking console window?

2005-03-29 Thread Bengt Richter
from a python program that does not _itself_ have a console window, look into running _that_ using the pythonw.exe (note "w") interpreter instead of the python.exe interpreter, as others have mentioned. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Optimisation Hints (dict processing and strings)

2005-03-30 Thread Bengt Richter
] UIAM that should build a temporary safe list only of the keys selected for deletion. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Suggesting methods with similar names

2005-03-30 Thread Bengt Richter
o(object): ... so we can implement smart help as a decorator? I.e., the above decorator syntax would be a non-intrusive way of spelling class Foo(object): __metaclass__ = classdeco ... (haven't thought about cascaded decorators in this context ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Little Q: how to print a variable's name, not its value?

2005-03-31 Thread Bengt Richter
o name(). What should you get for name(7)? There might be no name. To get an idea, try to write a C routine to do it, being passed a pointer to a memory location allocated with malloc. What name should it return? How should it find a name? If you are willing to prefix your names with the name of a special namespace whenever you refer to them, so it would be name(ns.a) >>> 'a', that could be be done. You can do about anything through descriptor magic and overriding __get/setattr/ibute__ and spell things in a way that totally abuses the design intents of Python ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Stylistic question about inheritance

2005-03-31 Thread Bengt Richter
implementation, I guess it will save some editing to include it at the start (unless you intended to define old-style classes and factor the base class inheritance revisions into some global metaclass hack later (not even really sure that's reliably possible, but pretty sure it woul

Re: Controling the ALU

2005-03-31 Thread Bengt Richter
gt;what is actually executing the instructions that _are_ Python. Unless "the" CPU is elsewhere and OP is talking about an ALU on some circuit board/ICE thing that he has an interface to that he didn't mention ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: assignments - want a PEP

2005-03-31 Thread Bengt Richter
By default the __assign__ method does nothing at all but can be >implemented by custom classes. > >def __assign__(self,own_name): ># do somtehing with me and my name > >Instead of changing the behaviour of the current assignment operator >"=" one could think

Re: Little Q: how to print a variable's name, not its value?

2005-03-31 Thread Bengt Richter
You're welcome. But I started programming with flexowriter punched paper tape before I got to punch cards, so either the prognosis is hopeful or maybe you should take what I write with a grain or two of salt. Probably both ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: System bell

2005-04-01 Thread Bengt Richter
W in an NT4 console window, print '\a' beeps via the PC internal speaker (like winsound.Beep). Running the bash shell of msys, echo -e '\a' also beeps via the PC speaker. These are not affected by any volume control that I know of. But running py2.3 idle, print '\a' d

Re: New to programming question

2005-04-01 Thread Bengt Richter
gt;>> guess() Guess my name: Jack Guess my name: Bob Guess my name: Ben You're right! >>> guess() Guess my name: Jack Guess my name: Ben You're right! >>> guess() Guess my name: Kermit Guess my name: Ms Piggy Guess my name: Ernie No more tries for you!!! >>> guess(1) Guess my name: Einstein No more tries for you!!! >>> guess() Guess my name: Ben You're right! Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: StopIteration in the if clause of a generator expression

2005-04-01 Thread Bengt Richter
e clearly, using Peter's stop: >>> def show(x): print x,; return x ... >>> def stop(): raise StopIteration ... >>> 2 in (x for x in xrange(5) if show(x)<4 or stop()) 0 1 2 True >>> 7 in (x for x in xrange(5) if show(x)<4 or stop()) 0 1 2 3 4 False BTW I notice that this also nicely shortcuts when the 2 is found. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Case-insensitive dict, non-destructive, fast, anyone?

2005-04-01 Thread Bengt Richter
27;} Ok, the idea: I wonder if a dict with a general override hook for hashing all keys would be useful. E.g., a dict.__keyhash__ that would take key as arg and default as now returning key.__hash__() but that you could override. Seems like this could potentially be more efficient than key wrappers, and would also make it so you wouldn't have to chase all the affected methods in doing an idict like the above (e.g., get, setdefault, update etc. etc.) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Case-insensitive dict, non-destructive, fast, anyone?

2005-04-01 Thread Bengt Richter
On Fri, 01 Apr 2005 23:04:42 GMT, "Raymond Hettinger" <[EMAIL PROTECTED]> wrote: >[Bengt Richter] >> I wonder if a dict with a general override hook for hashing all keys would be >useful. >> E.g., a dict.__keyhash__ that would take key as arg and default as no

Re: Lambda: the Ultimate Design Flaw

2005-04-01 Thread Bengt Richter
;ideal? >-- >Aahz ([EMAIL PROTECTED]) <*> http://www.pythoncraft.com/ > >"The joy of coding Python should be in seeing short, concise, readable >classes that express a lot of action in a small amount of clear code -- >not in reams of trivial code that bores the reader to death." --GvR Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: [Newbie] Search-and-delete text processing problem...

2005-04-01 Thread Bengt Richter
ppen if there is NO break, so line does not start with any delStarts name theOutFile.write(line) # write line out if not starting badly (You could do that with a oneliner too, but it gets silly ;-) If you have a LOT of names to check for, it could pay you to figure a way to split off the name from the fron of a lines, and check if that is in a set instead using a delStart list. If you do use delStart, put the most popular names at the front. ># > >I know I could do it in Word fairly easily, but I'd like to learn the Python >way to do things. Have fun. > >Thanks for any advice. > HTH (nothing tested, sorry ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: unittest vs py.test?

2005-04-02 Thread Bengt Richter
ry >it out or read the docs than discuss it to death on a newsgroup. >The learning curve is minimal. > > Is there a package that is accessible without svn? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Docorator Disected

2005-04-02 Thread Bengt Richter
ine 1, in ? File "", line 3, in decobomb Exception: Did it bomb the existing function? >>> vars(foo).keys() [] Nope, seems that was a new foo that got bombed and then not bound to replace the old foo. >>> foo.bomb Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute 'bomb' >I'm not sure this is 100%, or if there are other ways to view it, but >it seems to make sense when viewed this way. I like annotated code walk-throughs. But as others have pointed out, it's still a bit buggy ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Performance issue

2005-04-02 Thread Bengt Richter
rd)), []).append(word))) Then for wlen, adic in d.items(): pickle_file_name = 'anagram_%s'% wlen # pickle adic and write it out to the file ... Then the anagram utility can look for the appropriate pickle file per word length, (i.e., 'anagram_%s'%len(word.strip())) and just load it to anadict and print anadict(''.join(sorted(word.strip().lower())). That's a sketch. Untested!! Gotta go ;-/ Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Decorator Dissection

2005-04-02 Thread Bengt Richter
'maverick' Or >>> @str ... def foo(): pass ... >>> foo '' Note the quotes ;-) >>> type(foo) Just being picky about absolute statements ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: redundant imports

2005-04-02 Thread Bengt Richter
space). (Execfile inside a function or class definition needs careful control, but can be done). >depreciated in Python, because it leads to problems figuring out where >a specific variable came from. In C, it creates a problem called "name >space pollution". This is the case when a file1.c gets all the symbols >for some_header.h, even though it doesn't include/need those symbols, >because some header file1.c included needed a symbol from >some_header.h. This is especially galling if the pollution collides >with some_header2.h that file1.c actually needs. > Of course in C you could write some #ifxxx kludges to control inclusion of named things from a given header file somewhat. But name space pollution is a pox, to be sure ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: instance name

2005-04-02 Thread Bengt Richter
.myName() ... one two three We don't have to access instance by names like instance_1, if we didn't make them with bindings like that. E.g., egoes is a name bound to a list of Ego instances, so we can get at the second (counting from index 0) instance thus, and change it's name from the outside, since we know it's stored as an attribute called 'name': >>> egoes[1].name = 'Zeppo' >>> for ego in egoes: print ego.myName() ... one Zeppo three HTH Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Finding attributes in a list

2005-04-02 Thread Bengt Richter
6), ('sam', 5, 8), ('linda', 8, 6)] If you had huge input lists, you could avoid the terporary tuple list using >>> import itertools >>> iplayers = list(itertools.starmap(Player, itertools.izip(names, attack, >>> defense))) >>> for player in iplayers: print player.name, player.attack, player.defense ... bob 7 6 sam 5 8 linda 8 6 You can look into __slots__ if you want to have objects but need reduced memory footprint. But don't worry about optimizing 'til you can prove you need it, unless just for fun ;-) Ok. That's enough relief for me. Got other stuff ... Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Docorator Disected

2005-04-02 Thread Bengt Richter
UNCTION1 9 RETURN_VALUE The (6) just calls whatever the result of the preceding was >>> dis.dis(compiler.compile('foo(2)(6)','','eval')) 1 0 LOAD_NAME0 (foo) 3 LOAD_CONST 1 (2) 6 CALL_FUNCTION1 9 LOAD_CONST 2 (6) 12 CALL_FUNCTION1 15 RETURN_VALUE HTH Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Docorator Disected

2005-04-04 Thread Bengt Richter
o make another fee and call it without even storing it: >>> foo()(1) (1, '[Mon Apr 04 22:33:40 2005][Mon Apr 04 22:33:40 2005]') [...] >Today I believe I have the correct view as I've said this morning. I >could be wrong yet again. I hope not though I might have

<    2   3   4   5   6   7   8   9   10   >