Re: Filtering out non-readable characters

2005-07-17 Thread Raymond Hettinger
to be None and then run as if an identity string had been provided. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficiently Split A List of Tuples

2005-07-17 Thread Raymond Hettinger
e-up very well (with each Python implementation having its own limits on how far you can push this idiom). Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficiently Split A List of Tuples

2005-07-17 Thread Raymond Hettinger
xecute the operation itself. Executive summary: Python's for-loops are both elegant and fast. It is a mistake to habitually avoid them. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: list implementation

2005-07-17 Thread Raymond Hettinger
ON001370 http://docs.python.org/lib/module-collections.html Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficiently Split A List of Tuples

2005-07-18 Thread Raymond Hettinger
c = *args # three elements, no problem f(*xrange(100)) # too much data, not scalable, bad idea Whenever you get the urge to write something like the latter, then take it as cue to be passing iterators instead of unpacking giant tuples. Raymond -- http://mail.python.or

Re: Environment Variable

2005-07-18 Thread Raymond Hettinger
[Vivek Chaudhary] > Is it possible to set an environment variable in python script whose > value is retained even after the script exits. There is an indirect approach: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159462 Raymond -- http://mail.python.org/mailman/listinfo/

Re: Python Programming Contest

2005-07-19 Thread Raymond Hettinger
[Brian Quinlan] > I'm doing to judge the solutions based on execution speed. It sucks but > that is the easiest important consideration to objectively measure. . . . > I'm always looking for feedback, so let me know what you think or if you > have any ideas for future problems. I'm curious about

Re: dictionary that discards old items

2005-07-22 Thread Raymond Hettinger
[Will McGugan] > I need a collection class that behaves like a dictionary but when it > reaches 'n' items it discards the oldest item so that the length never > goes above 'n'. (Its for caching search results) import collections class Cache(dict): def __init__(self, n, *args, **kwds):

Re: unit test nested functions

2005-07-23 Thread Raymond Hettinger
n attribute of f . . . Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: list implementation

2005-07-23 Thread Raymond Hettinger
> > [sj] > >> Thus, random access is an O(1) operation while insertion/deletion is an > >> O(n) operation. [Raymond Hettinger] > > Yes. [Heikki Orsila aka host.invalid] > Unfortunately no. Check Terry Reeds answer. Random access is O(1), > insertion/deletion

Re: unit test nested functions

2005-07-23 Thread Raymond Hettinger
> > [Andy] > >>How can you unit test nested functions? [Raymond Hettinger] > > For whitebox testing, you could make an inner function visible by > > binding it to the enclosing function's attribute namespace. > > > >def f(x): > >

Re: dictionary that discards old items

2005-07-24 Thread Raymond Hettinger
[Raymond Hettinger] > >class Cache(dict): > >def __init__(self, n, *args, **kwds): > >self.n = n > >self.queue = collections.deque() > >dict.__init__(self, *args, **kwds) [Bengt Richter] > Minor comment: There is a potential name co

Re: can list comprehensions replace map?

2005-07-27 Thread Raymond Hettinger
er languages. In contrast, the existing behavior of zip() is quite useful. It allows some of the input sequences to be infinite: zip(itertools.count(1), open('myfile.txt')) Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: can list comprehensions replace map?

2005-07-28 Thread Raymond Hettinger
arked the trail; don't ignore the signs unless you really know where you're going. Raymond "... and soon you'll feel right as rain." -- from The Matrix -- http://mail.python.org/mailman/listinfo/python-list

Re: python-dev summary for 2005-07-01 to 2005-07-15

2005-07-31 Thread Raymond Hettinger
> This is the seventh summary written by the python-dev summary cabal of > Steve Bethard, Tim Lesher, and Tony Meyer. Thanks guys. The work is excellent and appreciated. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Art of Unit Testing

2005-08-03 Thread Raymond Hettinger
Once() is trivially coded using a global or class variable to restrict running to a single occasion. If that seems unpleasant, then encapsulate the logic in a subclass of TestCase, in a decorator, or in a metaclass. If you want better, try py lib's py.test module which is both more mini

Re: Reliable destruction

2005-08-04 Thread Raymond Hettinger
lly poll resources and shut them off if they are not in use -- loosely translated as having a security guard turn-off any coffee-pots that were left on by frazzled programmers as they leave at odd hours of the night. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Dictionary inheritance

2005-08-12 Thread Raymond Hettinger
eet your needs: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305268 Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Py_DECREF Question:

2005-08-15 Thread Raymond Hettinger
ly asking so I can cleanup any craziness in my code before I try > and release pyiw (the Python bindings for Wireless Networking in Linux). > I really want it to be as clean as possible before showing anyone > else. :) I'm sure your users will appreciate the devotion to quality. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Sandboxes

2005-08-20 Thread Raymond Hettinger
> Googling for information on securing Python in a "sandbox" seems > indicate that there are some built in features, but they aren't really > trustworthy. Is that correct? > > For my purposes, I really just want to let users run in a sandbox, with > access to only the language, manipuate a few publ

Re: Speed quirk: redundant line gives six-fold speedup

2005-08-25 Thread Raymond Hettinger
robes to find a global value). When the extra value was added, it likely resized the table four-fold and redistributed the hash values into fewer consecutive positions. Raymond P.S. To analyze it further, start with something like this: >>> len(set(hash('dummy%d' %i) & 31 fo

Re: Why does min(A,B) behave different for lists and for classes?

2005-08-26 Thread Raymond Hettinger
Claudio Grondi wrote: > Is there any deeper reason I don't understand > explaining why does min(A,B) behave different > for classes than for lists? Yes, the sort order for lists is determined by their contents. With your example, the lists have identical contents, so min() returns the first minim

Re: Why does min(A, B) not raise an error if A, B actually can't be compared?

2005-08-26 Thread Raymond Hettinger
is not very useful in your case. It works a bit like this: def __cmp__(self, other): return cmp(id(self), id(other)) This is mildly useful as it allows distinct objects to have an ordering relation. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Speed quirk: redundant line gives six-fold speedup

2005-08-26 Thread Raymond Hettinger
[Raymond Hettinger] > > With respect to > > distribution, it should be noted that string hash values are decidely > > non-random and your variable names likely congested consecutive spaces > > in a nearly full table (resulting in seven times as many search probes &g

Re: Proposed PEP: New style indexing, was Re: Bug in slice type

2005-08-26 Thread Raymond Hettinger
See PEP 322 for discussion and examples: http://www.python.org/peps/pep-0322.html Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: pickling the objects returned by array.array()

2005-09-02 Thread Raymond Hettinger
John Machin wrote: > Looks like arrays are NOW (2.4.1) pickleable but not unpickleable Please file a bug report and assign to me. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: issue with string.Template

2005-09-11 Thread Raymond Hettinger
ame tuple vs scalar issue. > So, take this as a bug report if the behavior is not intended and > as a feature request if the current behaviour is the intended > one ;) Feel free to post a SF report. If Barry wants to alter the behavior, it is easy enough to do: try: retur

Re: Unexpected Behavior Iterating over a Mutating Object

2005-09-13 Thread Raymond Hettinger
or.' It is intended. The behavior is defined as above (a series of indexed lookups). BTW, the usual ways to deal with this are to: 1. iterating from the right using: for item in reversed(data) 2. making a copy of the original list before iterating 3. creating a new result list: data = [x for x in data if 'DEL' not in x] Raymond -- http://mail.python.org/mailman/listinfo/python-list

RE: [Python-Dev] python optimization

2005-09-15 Thread Raymond Hettinger
Sep 15 2005, 00:51:34) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(): return 2+3 >>> import dis >>> dis.dis(f) 2 0 LOAD_CONST 3 (5) 3 RETURN_VALUE Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: "Collapsing" a list into a list of changes

2005-02-09 Thread Raymond Hettinger
end up with [0,1,2,3,2,4,5]. >>> import itertools >>> [k for k, v in itertools.groupby(lst)] [0, 1, 2, 3, 2, 4, 5] Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: listerator clonage

2005-02-12 Thread Raymond Hettinger
for elem in s: bag[elem] = bag.get(elem, 0) + 1 print [elem for elem, count in bag.iteritems() if count>1] Raymond Hettinger P.S. Extra credit problem: make the itertools solution output values in the order seen. -- http://mail.python.org/mailman/listinfo/python-list

Re: [PATCH] Re: frozenset() without arguments should return a singleton

2005-02-12 Thread Raymond Hettinger
ribly opposed to the idea. I just find the case for it to be somewhat weak. Also, I'm not sure it warrants the effort, the code clutter, or introducing issues like having a semantic difference between the result of frozenset() and the result of frozenset([]). Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: [PATCH] Re: frozenset() without arguments should return a singleton

2005-02-13 Thread Raymond Hettinger
ods, both set() and frozenset() share the same underlying code and data structure. In this respect, they differ from list() and tuple() which have no shared code and has two substantially different data structures. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Which module is "set " in?

2005-02-26 Thread Raymond Hettinger
If you're living in a pre 2.2 world without iterators and generators, you're really missing out. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: ListMixin (WAS: How do you control _all_ items added to a list?)

2005-03-01 Thread Raymond Hettinger
[Nick Coghlan] > > Hmm, it might be nice if there was a UserList.ListMixin that was the > > counterpart to UserDict.DictMixin [Steven Bethard] > I've thought this occasionally too. One of the tricky issues though is > that often you'd like to define __getitem__ for single items and have > ListM

Re: shuffle the lines of a large file

2005-03-07 Thread Raymond Hettinger
en('corpus.uniq'): print >> out, '%.14f %s' % (random(), line), >>> out.close() sort corpus.decorated | cut -c 18- > corpus.randomized Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Secondary list sorting comparison expression

2005-03-08 Thread Raymond Hettinger
list.sort(lambda a, b: cmp((a[i], a[j], a[k]), (b[i], b[j], b[k]))) In Py2.4, the key= option offers an alternative to cmp which is simpler and faster: def sort_by_key(list, i, j, k): list.sort(key = lambda a : (a[i], a[j], a[k])) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Itertools wishlists

2005-03-12 Thread Raymond Hettinger
nd how to combine them. The time and skill seems to rise exponentially with the number of tools in the module. So, it would be a mistake to add a few obscure, rarely used tools because that would impact the usability of the existing toolset. 'nuff said, mister whatever happened to batteries i

Re: Itertools wishlists

2005-03-13 Thread Raymond Hettinger
u need that to be flattened one level, it would have been better to do all the splits at once: # split on tabs, spaces, and newlines r = map(float, open('namefile').read().split()) Generalizing the two results, it may be fair to say that the desire to flatten is a code smell

Re: Itertools wishlists

2005-03-14 Thread Raymond Hettinger
else: iterstack.pop() # only remove iterator when it is exhausted Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: iterable terminology (for language lawyers)

2005-03-16 Thread Raymond Hettinger
ee also iterator, sequence, and generator. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: code for Computer Language Shootout

2005-03-16 Thread Raymond Hettinger
. So, consider reversing ';>' to '>;'. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: iterable terminology (for language lawyers)

2005-03-16 Thread Raymond Hettinger
not fail. Knowing that fact is the key to a complete and deep understanding of monglation ;-) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Itertools wishlists

2005-03-16 Thread Raymond Hettinger
nd how to integrate them with other Python code. IMO, most of the recipes are more useful in this capacity than as immediate solutions to particular problems. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: code for Computer Language Shootout

2005-03-16 Thread Raymond Hettinger
n the standard library =), is a better > solution than duplicating the code (or the function call) to translate, > reverse, and format the string. While the use of groupby() is brilliant, I prefer the previous version as a demonstration of beautiful, general purpose, plain Python code running at full-speed. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: computing a weighted sum

2005-03-17 Thread Raymond Hettinger
map() is only for situations where the data is already in tuple form. If it inputs are already distinct, imap() is the preferred form. FWIW, the answer was already in the docs (itertools recipes): def dotproduct(vec1, vec2): return sum(imap(operator.mul, vec1, vec2)) Raymond Hettinger

Re: list of unique non-subset sets

2005-03-17 Thread Raymond Hettinger
;,'l']) > L=[s1,s2,s3,s4,s5] > --- > cleaned-up list should contain s1, s3, s5 This should do the trick: result = [] for s1 in L: for s2 in result: if s1 <= s2: break else: result.append(s1) print result Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: list of unique non-subset sets

2005-03-17 Thread Raymond Hettinger
"Kent Johnson" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Raymond Hettinger wrote: > > [EMAIL PROTECTED] > > > >>I have many set objects some of which can contain same group of object > >>while others can be subset of the other.

Pre-PEP: Dictionary accumulator methods

2005-03-18 Thread Raymond Hettinger
if key not in d: d.key = {subkey:value} else: d[key][subkey] = value Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: list of unique non-subset sets

2005-03-18 Thread Raymond Hettinger
> > How do you define "largest" ? ;-) > I guess you could sum(map(len, setlist)) as a measure, but what if that makes > a tie between two setlists (as I think it could, in general)? With multiple outputs satisfying the constraints, I would suspect that there is something wrong with the original spec (not as a stand-alone problem, but as component of a real application). Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-18 Thread Raymond Hettinger
ey:value} else: d[key][subkey] = value Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: survey of modules to be added to stdlib

2005-03-18 Thread Raymond Hettinger
> psyco - Armin Rigo This is platform specific. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-18 Thread Raymond Hettinger
[Jeff Epler] > Maybe something for sets like 'appendlist' ('unionset'?) I do not follow. Can you provide a pure python equivalent? Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-18 Thread Raymond Hettinger
to True or False: any(x >= 42 for x in data) If you wanted an identify function, that simplifies to just: any(data) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-18 Thread Raymond Hettinger
ce and provide a better designed tool rather than just a name change. > Just my 2 Eurocents, I raise you by a ruble and a pound ;-) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-18 Thread Raymond Hettinger
to the key should be emphasised more. Hence valadd or such? How about countkey() or tabulate()? Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Raymond Hettinger
full statement: d.setdefault(k, []).append(v). My thought is that setdefault() is rarely used by itself. Instead, it is typically part of a longer sentence whose intent and meaning is to accumulate or build-up. That meaning is not well expressed by the current idiom. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

any() and all() Was: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Raymond Hettinger
a little less elegant: False not in (x >= 42 for x in data) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

any() and all() Was: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Raymond Hettinger
y while retaining the original value. IOW, your re-write is incorrect: >>> L = ['the', 'quick', 'brownish', 'toad'] >>> max(L, key=len) 'brownish' >>> max(len(x) for x in L) 8 Remain calm. Keep the fait

Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Raymond Hettinger
27;t mind writing out the plain Python for this one if it only comes up once in a blue moon. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Raymond Hettinger
contain strong cues that remind you of addition and of building a list. For the first, how about addup(): d = {} for word in text.split(): d.addup(word) Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Raymond Hettinger
[Ivan Van Laningham] > What about adding another method, "setincrement()"? . . . > Not that there's any real utility in that. That was a short lived suggestion ;-) Also, it would entail storing an extra value in the dictionary header. That alone would be a killer.

Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Raymond Hettinger
ility. BTW, there is no need to make the same post three times. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Raymond Hettinger
atomic as this expression can get. Any other steps, added verbiage, new types, extra arguments, or whatnot are an unnecessary waste of brain cells. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Decimal printing without the exponent

2004-11-28 Thread Raymond Hettinger
((0, (1, 0, 1), 1))) > '1.01E+3' > >>> > > how do you make the 2nd example print 1010? The quantize method will convert to any desired exponent (zero in your example): >>> d = (Decimal((0, (1, 0, 1), 1))) >>> d Decimal("1.01E+3") >>> d.quantize(Decimal(1)) Decimal("1010") Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: efficient intersection of lists with rounding

2004-12-03 Thread Raymond Hettinger
nt? Yes: >>> set((x,round(y)) for x,y in a) & set((x,round(y)) for x,y in b) set([(123, 8.0), (123, 2.0), (123, 1.0)]) > I'm using python 2.3. >>> from sets import Set as set >>> set([(x,round(y)) for x,y in a]) & set([(x,round(y)) for x,y in b]) set([(123, 8.0), (123, 2.0), (123, 1.0)]) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Replace string except inside quotes?

2004-12-03 Thread Raymond Hettinger
double quotes? For making changes to Python code, I > would also like to avoid changing text in comments, either the '#' or > '""" ... """' kind. The source for the tokenize module covers all these bases. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Zip with a list comprehension

2004-12-11 Thread Raymond Hettinger
omps and genexps. If you want to go the extra distance, itertools.izip() can offer a performance boost and better memory utilization than zip(). It can be used almost anywhere as long as the app doesn't demand a real list. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Performance (pystone) of python 2.4 lower then python 2.3 ???

2004-12-13 Thread Raymond Hettinger
ist comprehensions got a nice 60% boost on my machine: C:\py24\Lib>\python23\python timeit.py -r9 "[i for i in xrange(1000)]" 100 loops, best of 9: 1.11 msec per loop C:\py24\Lib>\python24\python timeit.py -r9 "[i for i in xrange(1000)]" 1000 loops, best of 9: 417

Re: while 1 vs while True

2004-12-13 Thread Raymond Hettinger
;None' only just became a constant in 2.4. > > I don't know if 'True' and 'False' are in line for similar treatment (there are > obvious backwards compatibility issues in doing so). It is unlike to before Py3.0. Making them constants would break the reams

Re: dot products

2004-12-19 Thread Raymond Hettinger
,y in zip(a,b)) 0.635497577901 sum(imap(mul, a, b)) 0.85894416601 sum(map(mul, a, b)) C:\pydev>python timedot.py 10 2.19490353509 sum(a[i]*b[i] for i in xrange(len(a))) 2.01773998894 sum(x*y for x,y in izip(a,b)) 2.44932533231 sum(x*y for x,y in zip(a,b)) 1.24698871922 sum(imap(mul, a, b)) 1.

Re: List limits

2004-12-20 Thread Raymond Hettinger
all in comparison. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Oddity in 2.4 with eval('None')

2004-12-20 Thread Raymond Hettinger
leton instance of None. That will occur even if you've mucked with None entry in the globals dictionary. Bytecode for eval() doesn't go through the bytecode optimizer so its dictionary lookup is retained (producing the effect in your example). To have made None a literal constant would

Re: dot products

2004-12-20 Thread Raymond Hettinger
a,b)) 1.62 sec:sum(x*y for x,y in zip(a,b)) 0.75 sec:sum(imap(mul, a, b)) 1.04 sec:sum(map(mul, a, b)) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Python 3000, zip, *args and iterators

2004-12-27 Thread Raymond Hettinger
posting present only toy examples -- real use cases have not yet emerged. If some do emerge, I suspect that each problem will have a better solution (using existing tools) than the one being proposed. If so, then adopting the proposal will have the negative effect of leading folks away from the corre

Re: Python 3000, zip, *args and iterators

2004-12-29 Thread Raymond Hettinger
le) ... rows = range(len(data)) ... for col in xrange(len(data[0])): ... args = [data[row][col] for rows in rows] ... yield f(*args) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: convert user input to Decimal objects using eval()?

2005-03-29 Thread Raymond Hettinger
)*Decimal('85')-Decimal('.1234')/Decimal('81.6') --> Decimal("0.01659274509803921568627450980") 1.0/7 --> 0.14285714285714285 Decimal('1.0')/Decimal('7') --> Decimal("0.1428571428571428571428571429") """ Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

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

2005-03-29 Thread Raymond Hettinger
[Jack Diederich] > > itertools to iter transition, huh? I slipped that one in, I mentioned > > it to Raymond at PyCon and he didn't flinch. It would be nice not to > > have to sprinkle 'import itertools as it' in code. iter could also > > become a ty

Re: convert user input to Decimal objects using eval()?

2005-03-30 Thread Raymond Hettinger
> > [Julian Hernandez Gomez] > >> is there a "easy way" to make eval() convert all floating > >> numbers to Decimal objects and return a Decimal? [Raymond Hettinger] > > from decimal import Decimal > > import re > > > > number = > &

Re: Weakrefs to classes that derive from str

2005-03-30 Thread Raymond Hettinger
nalty just to create the possibility of weak referencing. While the design decision is unlikely to change, the docs could certainly be improved. A doc patch would be welcome. FWIW, the work-arounds are to weak-reference instances of UserString or to create a custom class with a has-a relationship in

Re: Write an hexadecimal file

2005-03-30 Thread Raymond Hettinger
;, binascii.unhexlify(_))[0] 3.1415927410125732 Writing to a file is accomplished with the open() function and the file.write() method: f = open('mydata.hex', 'w') f.write('40490fdb') f.close() Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Suggesting methods with similar names

2005-03-30 Thread Raymond Hettinger
inner. When you're done, consider posting the result as an ASPN cookbook recipe. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: author index for Python Cookbook 2?

2005-03-30 Thread Raymond Hettinger
mments, competing recipes, and Alex/Anna's editing). The cookbook is its own microcosm of open source. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: return the last item in a list

2005-03-30 Thread Raymond Hettinger
[David Bear] > I'm looking for an 'easy' way to have the last item in a list returned. Try mylist.pop() or mylist[-1]. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Weakrefs to classes that derive from str

2005-03-30 Thread Raymond Hettinger
, elem1, elem2--] [--tuple header, elem0 ] In contrast, ints and floats floats have no problem because they are always the same size: [--int header, int value--] Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: split an iteration

2005-03-31 Thread Raymond Hettinger
your best bet is to eliminate the initial linear search which is likely consuming most of the clock cycles. Also, I noticed that the code does not reference self. Accordingly, it is a good candidate for being a staticmethod or standalone function. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

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
)). For the performance minded, there could also be a control for dictionary speed/space efficiency: t = TrickyDict() t.maxkeydensity = 40 # resize whenever the dictionary is more than 40% full 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. Raymond -- http://mail.python.org/mailman/listinfo/python-list

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
tage is the clarity of the resulting code and the avoidance of continous reinvention of workarounds. Separating tool features into a basic and an advanced version is common solution to managing option/customization complexity. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: StopIteration in the if clause of a generator expression

2005-04-01 Thread Raymond Hettinger
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. That's a fact. Raymond -- http://mail.python.org/mailman/listinfo/python-list

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/m

Re: unittest vs py.test?

2005-04-03 Thread Raymond Hettinger
self.assertEqual over and over again. The generative tests are especially nice. Until you've exercised both packages, you haven't helped the OP whose original request was: "Is there anybody out there who has used both packages and can give a comparative review?" Raymond -- http://mail.python.org/mailman/listinfo/python-list

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

<    1   2   3   4   5   6   7   8   9   >