Re: unittest vs py.test?

2005-03-31 Thread Raymond Hettinger
test is based on a proven model and the code is mature. unittest module updates come up in distinct releases, often months or years apart. py.test is subject to constant update by subversion. Personally, I like the continuous updates, but it could be unsettling if you're depending

Re: StopIteration in the if clause of a generator expression

2005-04-01 Thread Raymond Hettinger
ite a pure python equivalent for list: def lyst(s): it = iter(s) result = [] try: while 1: result.append(it.next()) except StopIteration:# guess who trapped StopIter return result Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: unittest vs py.test?

2005-04-01 Thread Raymond Hettinger
e, some will adopt another, and the world will > become fragmented. Worry is a natural thing for someone with "panix" in their email address ;-) FWIW, the evolution of py.test is to also work seemlessly with existing tests from the unittest module. the world diversifies, the worl

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

2005-04-01 Thread Raymond Hettinger
f.lower()) def __eq__(self, other): return self.lower() == other.lower() >>> d = {} >>> d[S('ThE')] = 'quick' >>> d[S('the')] 'quick' >>> d {'ThE': 'quick'} Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

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

2005-04-01 Thread Raymond Hettinger
[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 now returning key.__hash__() > but that you could override. Seems like this could potentially be more efficient than key wrap

Re: Help with splitting

2005-04-01 Thread Raymond Hettinger
Right. attrgetter gets but does not call. If unicode isn't an issue, then the lambda can be removed: >>> [''.join(g) for k, g in groupby(' test ing ', str.isspace)] [' ', 'test', ' ', 'ing', ' '] Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

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

2005-04-01 Thread Raymond Hettinger
> >Taken together, these six attributes/methods could cover many wished for > >features for the 10% of the cases where a regular dictionary doesn't provide the > >best solution. > You think as much as 10% ? Rounded up from 9.6 ;-) More important than the percentage is the clarity of the resultin

Re: StopIteration in the if clause of a generator expression

2005-04-01 Thread Raymond Hettinger
> I assumed that all standard sequence consumers (including list, of course) would intercept > the StopIteration of a sequence given them in the form of a generator expression, so your > lyst example would have an analogue for other sequence consumers as well, right? > I.e., there's not a hidden li

Re: unittest vs py.test?

2005-04-01 Thread Raymond Hettinger
#x27;m a little puzzled why folks so often consider this > particularly "heavy". unittest never felt heavy to me until I used py.test. Only then do you realize how much boilerplate is needed with unittest. Also, the whole py.test approach has a much simpler object model. BTW, th

Re: unittest vs py.test?

2005-04-02 Thread Raymond Hettinger
rt people: enough to make me want to take a > closer look at it to see what the fuss is about. :-) FWIW, py.test scales nicely. Also, it takes less time to try it out or read the docs than discuss it to death on a newsgroup. The learning curve is minimal. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: unittest vs py.test?

2005-04-02 Thread Raymond Hettinger
[Peter Hansen] > This is pretty, but I *want* my tests to be contained > in separate functions or methods. In py.test, those would read: def test1(): assert a == b def test2(): raises(Error, func, args) Enclosing classes are optional. Raymond -- http://mail.python.org/mailman/listi

Re: unittest vs py.test?

2005-04-03 Thread Raymond Hettinger
[Peter Hansen] > (I'm not dissing py.test, and intend to check it > out. Not to be disrepectful, but objections raised by someone who hasn't worked with both tools equate to hot air. > I'm just objecting to claims that unittest > somehow is "heavy", when those claiming that it > is seem to think

Re: StopIteration in the if clause of a generator expression

2005-04-03 Thread Raymond Hettinger
my bet is that they will live on. The more likely change is that in Py3.0 list comps will no longer expose the loop variable outside the loop. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: StopIteration in the if clause of a generator expression

2005-04-04 Thread Raymond Hettinger
[Steven Bethard] > and I often find myself alternating > between the two when I can't decide which one seems more Pythonic. Both are pythonic. Use a genexp when you need a generator and use a listcomp when you need a list. Raymond Hettinger -- http://mail.python.org/mailman/list

Re: StopIteration in the if clause of a generator expression

2005-04-04 Thread Raymond Hettinger
> > Use a genexp when you need a generator > > and use a listcomp when you need a list. [Steven Bethard] > So do I read this right in preferring > [ for in ] > over > list( for in ) Yes! Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: sparse sets of integers?

2005-04-04 Thread Raymond Hettinger
n.activestate.com/ASPN/Cookbook/Python/Recipe/230113 Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: StopIteration in the if clause of a generator expression

2005-04-05 Thread Raymond Hettinger
> > [Steven Bethard] > > > So do I read this right in preferring > > > [ for in ] > > > over > > > list( for in ) [Raymond Hettinger] > > Yes! [Simon Brunning] > Why? (Serious question. I'm sure that you have a good reason -

Re: Propagating poorly chosen idioms

2005-04-05 Thread Raymond Hettinger
. I hope they don't lose it as the package evolves to include doctests and such. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: sorting a list and counting interchanges

2005-04-06 Thread Raymond Hettinger
ution anyway: >>> phase = 1 >>> def mycmp(x, y): global phase phase = -phase return cmp(x, y) >>> sorted('abracadabra', cmp=mycmp) ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r'] >>> phase -1 Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: sorting a list and counting interchanges

2005-04-06 Thread Raymond Hettinger
[RickMuller] > I have to sort a list, but in addition to the sorting, I need to > compute a phase factor that is +1 if there is an even number of > interchanges in the sort, and -1 if there is an odd number of > interchanges. It occurs to me that the previously posted comparison count won't do it.

Re: sorting a list and counting interchanges

2005-04-06 Thread Raymond Hettinger
[Jordan Rastrick] > Unless I'm mistaken, this doesnt quite work, because it switches the > parity of phase every time a comparison is made, rather than every time > a swap is made. So: > > # > phase = 1 > def mycmp(x,y): >global phase >c = cmp(x,y) >if c > 0: # i.e. a swap will be perf

Re: sorting a list and counting interchanges

2005-04-06 Thread Raymond Hettinger
[John Machin] > 2. Without a definition that refers only to to the input and output, > one would have to say that "interchange" implies "event" and so the > number of interchanges would depend on the sorting method. As the dataset contains no duplicates, the parity will be the same irrespective of

Re: Why does StringIO discard its initial value?

2005-04-10 Thread Raymond Hettinger
> Is this the > expected behavior Yes. > , and why it isn't mentioned in the docs if so? Per your request, the docs have been updated. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

RE: [Python-Dev] args attribute of Exception objects

2005-04-12 Thread Raymond Hettinger
bjects: >>> class Boom(Exception): pass >>> x = 10 >>> if x != 5: raise Boom("Value must be a five", x) Traceback (most recent call last): File "", line 2, in -toplevel- raise Boom("Value must be a five", x) Boom: ('Value must be a five', 10) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Why does StringIO discard its initial value?

2005-04-12 Thread Raymond Hettinger
ther than letting it be a guide to good code. If there were something wrong with the API, Guido would have long since fired up the time machine and changed the timeline so that all would be as right as rain ;-) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Python 2.4 killing commercial Windows Python development ?

2005-04-12 Thread Raymond Hettinger
[Robin Becker] > People have mentioned the older v6 build scripts/tools still work. Last time I > tried they seemed a bit out of date. I routinely use the current CVS to build Py2.4 and Py2.5 with MSC6. It is effortless and I've had no problems. Raymond Hettinger -- http://mail

Re: New-style classes, iter and PySequence_Check

2005-04-14 Thread Raymond Hettinger
rforms an __iter__ lookup, fill the slot with something that does that lookup. Raymond Hettinger E = mc**2 # Einstein E = IR # Ohm's law therefore IR = mc**2 # Raymond's grand unified theory -- http://mail.python.org/mailman/listinfo/python-list

Re: New-style classes, iter and PySequence_Check

2005-04-14 Thread Raymond Hettinger
[Bengt Richter] > I'm not sure, but I think it may be expedient optimization practicality beating purity. It is more a matter of coping with the limitations of the legacy API where want to wrap a sequence iterator around __getitem__ in sequences but not in mappings. > > I haven't walked the r

Re: Behaviour of str.split

2005-04-18 Thread Raymond Hettinger
a person's intuition seems to lead them to guess that the behavior will be different than it actually is. Unfortunately, one person's intuition is often at odds with another's. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Removing dictionary-keys not in a set?

2005-04-18 Thread Raymond Hettinger
> >>> for k in s1-s2: > ... del d1[k] > ... FWIW, if s2 is not already a set object, it need not be transformed before using it. Instead, write: for k in set(d1).difference([1,3,5]): del d1[k] If you prefer to work with dictionaries instead of sets, then adapt the existing code for symmetric_difference_update() in sets.py. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Why Python does *SLICING* the way it does??

2005-04-19 Thread Raymond Hettinger
<[EMAIL PROTECTED]> > Many people I know ask why Python does slicing the way it does. Half open intervals are just one way of doing things. Each approach has its own merits and issues. Python's way has some useful properties: * s == s[:i] + s[i:] * len(s[i:j]) == j-i # if s is long eno

Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Raymond Hettinger
ething with lst[i] After going to all that trouble, you might as well also get the value at that position: for i, x in enumerate(lst): do something with lst[i] also known as x Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Raymond Hettinger
st[i] also known as x > > No you wouldn't, enumerate always starts with 0. You don't get it. Your proposed list-like class indicates its start index. enumerate() can be made to detect that start value so that the above code always works for both 0-based and 1-based arrays. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: time.strftime in 2.4.1 claims data out of range when not

2005-04-22 Thread Raymond Hettinger
0, 0, 6, 135, -1) >>> strftime("%Y-%m-%d", _) '2005-05-15' This somewhat circular technique sticks with the documented API but allows you to access all of the time module's options (like accessing the locale's names for days of the week and months of the year). Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Micro-PEP: str.translate(None) to mean identity translation

2005-04-30 Thread Raymond Hettinger
me. I'll put this in for you. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Python education survey

2011-12-19 Thread Raymond Hettinger
Do you use IDLE when teaching Python? If not, what is the tool of choice? Students may not be experienced with the command-line and may be running Windows, Linux, or Macs. Ideally, the tool or IDE will be easy to install and configure (startup directory, path, associated with a particular version

Re: Python education survey

2011-12-22 Thread Raymond Hettinger
On Dec 21, 9:57 am, Nathan Rice wrote: > +1 for IPython/%edit using the simplest editor that supports syntax > highlighting and line numbers.  I have found that > Exploring/Prototyping in the interpreter has the highest ROI of > anything I teach people. Thank you Nathan and all the other responde

Re: Differences creating tuples and collections.namedtuples

2013-02-18 Thread raymond . hettinger
On Monday, February 18, 2013 6:09:16 AM UTC-8, John Reid wrote: > I'm aware how to construct the namedtuple and the tuple. My point was > that they use different syntaxes for the same operation and this seems > to break ipython. I was wondering if this is a necessary design feature > or perhaps jus

Re: Memoization and encapsulation

2005-12-30 Thread Raymond Hettinger
Steven D'Aprano wrote: > I was playing around with simple memoization and came up with something > like this: > > _cache = {} > def func(x): > global _cache > if _cache.has_key(x): > return _cache[x] > else: > result = x+1 # or a time consuming calculation... >

Re: Memoization and encapsulation

2005-12-30 Thread Raymond Hettinger
Steven D'Aprano wrote: > I was playing around with simple memoization and came up with something > like this: > > _cache = {} > def func(x): > global _cache > if _cache.has_key(x): > return _cache[x] > else: > result = x+1 # or a time consuming calculation... >

Re: itertools.izip brokeness

2006-01-04 Thread Raymond Hettinger
as not been previously reported, nor have there any related feature requests, nor was the use case contemplated in the PEP discussions: http://www.python.org/peps/pep-0201 ). Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: itertools.izip brokeness

2006-01-04 Thread Raymond Hettinger
-clauses in a for-loop. OTOH, this approach is at odds with the notion of side-effect free functional programming and the purported benefits of that programming style. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Real-world use cases for map's None fill-in feature?

2006-01-08 Thread Raymond Hettinger
Does an outer-join have anything to do with lock-step iteration? Is this a fundamental looping construct or just a theoretical wish-list item? Does Python need itertools.izip_longest() or would it just become a distracting piece of cruft? Raymond Hettinger FWIW, the OP's use cas

Do you have real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
undamental looping construct or just a theoretical wish-list item? IOW, does Python really need itertools.izip_longest() or would that just become a distracting piece of cruft? Raymond Hettinger P.S. FWIW, the OP's use case involved printing files in multiple columns: for f, g in itertools.izip

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
[Alex Martelli] > I had (years ago, version was 1.5.2) one real-world case of map(max, > seq1, seq2). The sequences represented alternate scores for various > features, using None to mean "the score for this feature cannot be > computed by the algorithm used to produce this sequence", and it was >

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
[Anders Hammarquist]: > I had a quick look through our (Strakt's) codebase and found one example. Thanks for the research :-) > The code is used to process user-designed macros, where the user wants > to append data to strings stored in the system. Note that all data is > stored as lists of what

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
Duncan Booth wrote: > One example of padding out iterators (although I didn't use map's fill-in > to implement it) is turning a single column of items into a multi-column > table with the items laid out across the rows first. The last row may have > to be padded with some empty cells. ANALYSIS ---

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote: > The other use case I had was a simple file diff. > All I cared about was if the files were the same or > not, and if not, what were the first differing lines. > This was to compare output from a process that > was supposed to match some saved reference > data. Because of

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
> Alternately, the need can be met with existing tools by pre-padding the > iterator with enough extra values to fill any holes: > > it = chain(iterable, repeat('', group_size-1)) > result = izip_longest(*[it]*group_size) Typo: That should be izip() instead of izip_longest() -- http://m

Re: Do you have real-world use cases for map's None fill-in feature?

2006-01-10 Thread Raymond Hettinger
[Bengt Richter] > What about some semantics like my izip2 in > http://groups.google.com/group/comp.lang.python/msg/3e9eb63a1ddb1f46?hl=en > > (which doesn't even need a separate name, since it would be backwards > compatible) > > Also, what about factoring sequence-related stuff into being met

Re: Do you have real-world use cases for map's None fill-in feature?

2006-01-10 Thread Raymond Hettinger
[Raymond Hettinger] > > I am evaluating a request for an alternate version of itertools.izip() > > that has a None fill-in feature like the built-in map function: > > > > >>> map(None, 'abc', '12345') # demonstrate map's None fill-in

Re: Real-world use cases for map's None fill-in feature?

2006-01-10 Thread Raymond Hettinger
[Raymond] > > Both approaches require a certain measure of inventiveness, rely on > > advanced tricks, and forgo readability to gain the raw speed and > > conciseness afforded by a clever use of itertools. They are also a > > challenge to review, test, modify, read, or explain to others. [Peter O

Re: Do you have real-world use cases for map's None fill-in feature?

2006-01-10 Thread Raymond Hettinger
[Raymond] > >ISTM, these cures are worse than the disease ;-) [Bengt] > Are you reacting to my turgidly rambling post, or to > > >>> from ut.izip2 import izip2 as izip > >>> it = izip('abc','12','ABCD') > >>> for t in it: print t > ... > ('a', '1', 'A') > ('b', '2', 'B') > > Then after a bac

Re: Augmented generators?

2006-01-10 Thread Raymond Hettinger
Andrew Koenig wrote: > Can anyone think of an easy technique for creating an object that acts like > a generator but has additional methods? Perhaps the enable_attributes() recipe will help: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/164044 The recipe imbues generators with clas

Re: Bug in struct.pack?

2006-01-11 Thread Raymond Hettinger
[Alex Stapleton] > from struct import pack > >>> pack("B", 1) > '\x01' > >>> pack("BB", 0, 1) > '\x00\x01' > >>> pack("BI", 0, 1) > '\x00\x00\x00\x00\x01\x00\x00\x00' > >>> calcsize("BI") > 8 > >>> calcsize("BB") > 2 > > Why does an unsigned char suddenly become 4 bytes long when you > include

Re: Real-world use cases for map's None fill-in feature?

2006-01-12 Thread Raymond Hettinger
[David Murmann] > i'd like izip > to change, too. The zip() function, introduced in Py2.0, was popular and broadly useful. The izip() function is a zip() substitute with better memory utilization yet almost identical in how it is used. It is bugfree, successful, fast, and won't change. The map(

Re: Real-world use cases for map's None fill-in feature?

2006-01-12 Thread Raymond Hettinger
[EMAIL PROTECTED] > > > How well correlated in the use of map()-with-fill with the > > > (need for) the use of zip/izip-with-fill? [raymond] > > Close to 100%. A non-iterator version of izip_longest() is exactly > > equivalent to map(None, it1, it2, ...). [EMAIL PROTECTED] > If I use map() > I c

Re: flatten a level one list

2006-01-12 Thread Raymond Hettinger
[Robin Becker] > Is there some smart/fast way to flatten a level one list using the > latest iterator/generator idioms. > > The problem arises in coneverting lists of (x,y) coordinates into a > single list of coordinates eg > > f([(x0,y0),(x1,y1),]) --> [x0,y0,x1,y1,] Here's one way: >>>

Re: How to remove subset from a file efficiently?

2006-01-12 Thread Raymond Hettinger
[fynali] > I have two files: > > - PSP320.dat (quite a large list of mobile numbers), > - CBR319.dat (a subset of the above, a list of barred bumbers) # print all non-barred mobile phone numbers barred = set(open('CBR319.dat')) for num in open('PSP320.dat'): if num not in b

Re: Freezing

2006-01-12 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote: > add a freeze operation, to freeze lists, > sets and dicts (etc), so they can be used as keys. I'm curious whether you've had an actual use for dictionaries as keys. Likewise, how about frozensets? Have you had occasion to use them as keys? They were created to support

Re: Real-world use cases for map's None fill-in feature?

2006-01-12 Thread Raymond Hettinger
[Aahz] > I've counted 63 cases of ``map(None, ...`` in my company's code base. > You're probably right that most of them could/should use zip() instead; > I see at least a few cases of > > map(None, field_names, values) > > but it's not clear what the expectation is for the size of the two list

Re: How to remove subset from a file efficiently?

2006-01-12 Thread Raymond Hettinger
AJL wrote: > How fast does this run? > > a = set(file('PSP320.dat')) > b = set(file('CBR319.dat')) > file('PSP-CBR.dat', 'w').writelines(a.difference(b)) Turning PSP into a set takes extra time, consumes unnecessary memory, eliminates duplicates (possibly a bad thing), and loses the origin

Re: How can I make a dictionary that marks itself when it's modified?

2006-01-12 Thread Raymond Hettinger
[EMAIL PROTECTED] > It's important that I can read the contents of the dict without > flagging it as modified, but I want it to set the flag the moment I add > a new element or alter an existing one (the values in the dict are > mutable), this is what makes it difficult. Because the values are > mu

Re: Real-world use cases for map's None fill-in feature?

2006-01-12 Thread Raymond Hettinger
[Paul Rubin] > ISTR there's also a plan to eliminate map in Python 3.0 in favor of > list comprehensions. That would get rid of the possibility of using > map(None...) instead of izip_longest. This needs to be thought through. Not to fear. If map() eventually loses its built-in status, it will

Re: How to remove subset from a file efficiently?

2006-01-14 Thread Raymond Hettinger
> > b = set(file('/home/sajid/python/wip/stc/2/CBR333')) > > > > file('PSP-CBR.dat,ray','w').writelines(itertools.ifilterfalse(b.__contains__,file('/home/sajid/python/wip/stc/2/PSP333'))) > > > > -- > > $ time ./cleanup_ray.py > > > > real0m5.451s > > user0m4.496

Re: proposal: another file iterator

2006-01-15 Thread Raymond Hettinger
Paul Rubin wrote: > I find pretty often that I want to loop through characters in a file: > > while True: > c = f.read(1) > if not c: break > ... > > or sometimes of some other blocksize instead of 1. It would sure > be easier to say something like: > >for c in f.iterbytes():

Re: Decimal ROUND_HALF_EVEN Default

2006-01-16 Thread Raymond Hettinger
LordLaraby wrote: > If 'bankers rounding' is HALF_ROUND_EVEN, what is HALF_ROUND_UP? I > confess to never having heard the terms. The terms are defined in the docs for the Context object: http://docs.python.org/lib/decimal-decimal.html The rounding option is one of: --

Re: random shuffles

2006-07-21 Thread Raymond Hettinger
Boris Borcic wrote: > does > > x.sort(cmp = lambda x,y : cmp(random.random(),0.5)) > > pick a random shuffle of x with uniform distribution ? > > Intuitively, assuming list.sort() does a minimal number of comparisons to > achieve the sort, I'd say the answer is yes. But I don't feel quite > confo

Re: Jumping over in the class hierarchy

2006-08-01 Thread Raymond Hettinger
Pupeno wrote: > I want to jump over a method in the class hierarchy, that is: If I have > class A(object), clas B(A), class C(B) and in C, I want a method to do > exactly what A does but not what B does in its reimplementation, would it > be correct to do: super(A, super(B, self)).method() in C ?

Re: enumerate improvement proposal

2006-10-31 Thread Raymond Hettinger
James Stroud wrote: > I think that it would be handy for enumerate to behave as such: > > def enumerate(itrbl, start=0, step=1): >i = start >for it in itrbl: > yield (i, it) > i += step I proposed something like this long ago and Guido has already rejected it. Part of the reason

Re: multi split function taking delimiter list

2006-11-14 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote: > Hi, I'm looking for something like: > > multi_split( 'a:=b+c' , [':=','+'] ) > > returning: > ['a', ':=', 'b', '+', 'c'] > > whats the python way to achieve this, preferably without regexp? I think regexps are likely the right way to do this kind of tokenization. The s

Re: itertools.count() as built-in

2006-05-29 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote: > Is there any chance of itertools.count() ever becoming one of the > built-in functions? That's unlikely. The goal is to have fewer builtins rather than more. Utility and frequency are not the only considerations; otherwise glob.glob, sys.stderr, print.pprint, copy.copy,

Re: split a line, respecting double quotes

2006-07-10 Thread Raymond Hettinger
Sion Arrowsmith wrote: > >>> csv.reader(StringIO.StringIO('a b c "d "" e"'), delimiter=' ').next() > ['a', 'b', 'c', 'd " e'] > isn't far off. > > On the other hand, it's kind of a stupid solution. IMO, this solution is on the right track. FWIW, the StringIO wrapper is unnecessary. Any iterable wi

Re: "filtered view" upon lists?

2006-09-12 Thread Raymond Hettinger
unction=None): self._actual_list = actual_list self._filter_function = filter_function ### Example calls a = range(10) b = ListView(a, lambda x: x%2==0) print list(b), len(b), b[2], b[:3] a[:] = range(10,20) print list(b), len(b), b[2], b[:3] Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Inconsistency in dictionary behaviour: dict(dict) not calling __setitem__

2006-12-12 Thread Raymond Hettinger
[Almad] > I discovered this behaviour in dictionary which I find confusing. In > SneakyLang, I've tried to extend dictionary so it visits another class > after something is added: > > class RegisterMap(dict): > def __setitem__(self, k, v): > dict.__setitem__(self, k,v) > self[k]

Re: How to subclass sets.Set() to change intersection() behavior?

2006-12-12 Thread Raymond Hettinger
[mkppk] > I have kind of strange change I'd like to make to the sets.Set() > intersection() method.. > > Normally, intersection would return items in both s1 and s2 like with > something like this: s1.intersection(s2) . . . > - the lists I am working with are small, like 1-10 items each from set

Re: trees

2006-12-18 Thread Raymond Hettinger
vertigo wrote: > What library/functions/classes could i use to create trees ? Start with random.seed, login as root, use svn to download the trunk and branches, when Spring arrives, the leaves will fill-in ;-) Or just use lists as Fredrik suggested. Or look at an example in the cookbook: http://

Re: Sorting on multiple values, some ascending, some descending

2007-01-03 Thread Raymond Hettinger
dwelden wrote: > I have successfully used the sort lambda construct described in > http://mail.python.org/pipermail/python-list/2006-April/377443.html. > However, how do I take it one step further such that some values can be > sorted ascending and others descending? Easy enough if the sort values

Re: Efficient Find and Replace

2006-01-27 Thread Raymond Hettinger
[David Hirschfield] > for i,v in enumerate(L): > if v == X: > L[i] = Y Here's an alternate solution using a replacement dictionary: M = {X:Y} for i, v in enumerate(L): L[i] = M.get(v, v) The replacement dictionary directly supports generalization to multiple substitution pa

Re: Efficient Find and Replace

2006-01-28 Thread Raymond Hettinger
> > > for i,v in enumerate(L): > > > if v == X: > > > L[i] = Y > > > > Here's an alternate solution using a replacement dictionary: > > > > M = {X:Y} > > for i, v in enumerate(L): > > L[i] = M.get(v, v) [Fredrik Lundh] > but that's 2-3 times slower than the OP's corrected cod

Re: Using bytecode, not code objects

2006-01-28 Thread Raymond Hettinger
[Fabiano Sidler] > I'm looking for a way to compile python source to bytecode instead of > code-objects. Is there a possibility to do that? The reason is: I want > to store pure bytecode with no additional data. > > The second question is, therefore: How can I get the correct values > for a given b

Re: newbie: working iwth list of tuples

2006-01-28 Thread Raymond Hettinger
[falcon] > I am fairly new to Python (less than a week). My goal is to write a > small prototype of a database. Rather than build it using the typical > method where one provides selection, projection, aggregation, union, > intersection, etc. functions, I would like to do it in a more > 'function

Re: newbie: working iwth list of tuples

2006-01-29 Thread Raymond Hettinger
[Raymond Hettinger] > Parameterized filter, extract, and reduce functions can be handled in a > like manner. Just for grins, here is a more worked-out example: def pfunc(inputfields, operation): "Parameterized computation of a new field" # For example, append a field th

Re: Decoupling the version of the file from the name of the module.

2006-01-29 Thread Raymond Hettinger
[EMAIL PROTECTED] > I'm a newbie experimenting with Python. I want to incrementally develop > a module called 'circle'. . . . > Basically I want to decouple the version of my file from the name of > the module. > > Is there a *simple* way out of this dilemma. In the client code, use an import/as

Re: newbie: working iwth list of tuples

2006-01-29 Thread Raymond Hettinger
[Raymond Hettinger] > > Parameterized filter, extract, and reduce functions can be handled in a > > like manner. > > Just for grins, here is a more worked-out example: See the ASPN Cookbook recipe for a version with doctests and a couple bug-fixes: http://aspn.activestate

Re: Print dict in sorted order

2006-01-29 Thread Raymond Hettinger
[Kamilche] > I have a code snippet here that prints a dict in an arbitrary order. > (Certain keys first, with rest appearing in sorted order). I didn't > want to subclass dict, that's error-prone, and overkill for my needs. I > just need something that returns a value like dict.__str__, with a key

Re: Print dict in sorted order

2006-01-29 Thread Raymond Hettinger
> from itertools import count, izip > > def dict2str(d, preferred_order = ['gid', 'type', 'parent', 'name']): > last = len(preferred_order) > rank = dict(izip(preferred_order, count())) > pairs = d.items() > pairs.sort(key=lambda (k,v): rank.get(k, (last, k, v))) > return '{%s}'

Re: StringIO proposal: add __iadd__

2006-01-29 Thread Raymond Hettinger
[Paul Rubin] > here, "temp_buf += v" is supposed to be the same as "temp_buf.write(v)". > So the suggestion is to add a __iadd__ method to StringIO and cStringIO. > > Any thoughts? The StringIO API needs to closely mirror the file object API. Do you want to change everything that is filelike to ha

Re: finding the intersection of a list of Sets

2006-01-31 Thread Raymond Hettinger
[Peter Otten] > >>> sets = map(set, "abc bcd cde".split()) > >>> reduce(set.intersection, sets) > set(['c']) Very nice. Here's a refinement: >>> sets.sort(key=len) >>> reduce(set.intersection, sets[1:], sets[0]) set(['c']) -- http://mail.python.org/mailman/listinfo/python-list

Re: determinant

2006-01-31 Thread Raymond Hettinger
[Tuvas] > I am trying to find a nice function that quickly determines the > determanant in python. Anyone have any recommendations? I've heard > about numpy, but I can't get it to work (It doesn't seem to like the > import Matrix statement...). Thanks! http://aspn.activestate.com/ASPN/Cookbook/Pyt

Re: StringIO proposal: add __iadd__

2006-01-31 Thread Raymond Hettinger
[Raymond Hettinger] > > The StringIO API needs to closely mirror the file object API. > > Do you want to change everything that is filelike to have += > > as a synonym for write()? [Paul Rubin] > Why would they need that? Polymorphism > StringIO objects have getvalue

Re: finding the intersection of a list of Sets

2006-01-31 Thread Raymond Hettinger
That should have been: >>> sets.sort(key=len) >>> reduce(set.intersection, sets) The only refinement was the pre-sort based on set length. -- http://mail.python.org/mailman/listinfo/python-list

Re: Calling a string as a function.

2006-02-02 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote: > I'm completely new to python, so sorry for my ignorence. > How does one go about converting a string, for instants one received through > tcp, into something that can be called as a function? > I'm trying to have what the user sends to the computer through the network, >

Re: Reverse of map()?

2006-02-05 Thread Raymond Hettinger
[Alex Martelli] > map(apply, fn_list, ...) may work, but I doubt it's going to be either > simple or speedy since the ... must be replaced with as many copies of > Args and Kwds as there are functions in fn_list, e.g.: > > map(apply, fn_list, len(fn_list)*(Args,), len(fn_list)*(Kwds)) The repeat()

Re: Using bytecode, not code objects

2006-02-06 Thread Raymond Hettinger
Fabiano Sidler wrote: > 2006/1/29, Fabiano Sidler <[EMAIL PROTECTED]>: > > 28 Jan 2006 22:02:45 -0800, Raymond Hettinger <[EMAIL PROTECTED]>: > > > But if you want to make your life unnecessarily hard, you can hack the > > > compiler module just upstre

Re: datetime object from string

2006-02-06 Thread Raymond Hettinger
Douglas Douglas wrote: > Hi everybody. > > I need to create a datetime object from a string like "20/01/2005 15:10:01". I > know the mxDateTime module can do this with the DateTimeFrom method, but I was > wondering if is possible to do this using only the standard library. > > I read the datetime o

Re: * 'struct-like' list *

2006-02-06 Thread Raymond Hettinger
[Ernesto] > I'm still fairly new to python, so I need some guidance here... > > I have a text file with lots of data. I only need some of the data. I > want to put the useful data into an [array of] struct-like > mechanism(s). The text file looks something like this: > > [BUNCH OF NOT-USEFUL DAT

Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
re was a pithy Tim Peters quotation to the effect that he was unpersuaded by language proposals predicated on some hypothetical average programmer not being smart enough to understand something that the rest of us find to be basic. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
[EMAIL PROTECTED] > In my programs I have seen that there is another practical difference > between version 1 and 3: > (1) mylist[:] = [] > (3) mylist = [] > If you create a big mylist again and again many times, the version 1 > uses the memory more efficiently (probably less work for the garbage >

Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
> I'm a fairly average programmer (better than average compared to my > immediate colleagues). I've read every tutorial I can get my hands > on, but I have no _memory_ of ever coming across the del keyword, let > alone that it is fundamental to Python, My thought is that get/set/del are fundamen

<    1   2   3   4   5   6   7   8   >