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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: def pfunc(inputfields, operation): "Parameterized computation of a new field" # For example, append a field th

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: 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: 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: 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: 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: 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: 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: 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 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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 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: 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: 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: 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
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
[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
[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 >

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

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

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

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: 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: hash()

2005-12-05 Thread Raymond Hettinger
[John Marshall] > For strings of > 1 character, what are the chances > that hash(st) and hash(st[::-1]) would return the > same value? Python's string hash algorithm is non-commutative, so a collision with a reversed string is not likely. The exact answer depends on the population of strings bein

Re: Underscores in Python numbers

2005-11-19 Thread Raymond Hettinger
Gustav HÃ¥llberg wrote: > I tried finding a discussion around adding the possibility to have > optional underscores inside numbers in Python. This is a popular option > available in several "competing" scripting langauges, that I would love > to see in Python. > > Examples: > 1_234_567 > 0xdead_

Re: exception raised by nested iterator being ignored by for loop

2005-11-19 Thread Raymond Hettinger
the whole wrapper as a generator: import gzip def wrapper(filename) : if filename[-3:] == ".gz" : fh = gzip.GzipFile(filename, "r") else : fh = open(filename, "r") for line in fh: if line[:1] != "t": # filter out lines s

Re: which feature of python do you like most?

2005-11-08 Thread Raymond Hettinger
> which feature of python do you like most? Indentation -- http://mail.python.org/mailman/listinfo/python-list

Re: random number generator thread safety

2005-11-08 Thread Raymond Hettinger
> > Thread-safety has nothing to do with preserving entropy or guarding > > against attack. All of the entropy in an MT sequence is contained in > > the seed (upto 624 bytes) and that entropy is preserved through all > > subsequent calls. > > I think the concern is that there can be a thread switc

Re: random number generator thread safety

2005-11-08 Thread Raymond Hettinger
Mike Brown wrote: > I have questions about thread safety in the 'random' module. > > When using the random.Random class (be it Mersenne Twister or Wichmann-Hill > based), is it sufficiently thread-safe (preserving entropy and guarding > against attack) to just have each thread work with its own ran

Re: Idle bytecode query on apparently unreachable returns

2005-10-11 Thread Raymond Hettinger
[Tom Anderson]: > What puzzles me, though, are bytecodes 17, 39 and 42 - surely these aren't > reachable? Does the compiler just throw in a default 'return None' > epilogue, with routes there from every code path, even when it's not > needed? If so, why? Since unreachable code is never executed, t

Re: Moronicity Xha Lee, Jargonizer

2005-09-29 Thread Raymond Hettinger
James Stroud wrote: > There needs to be an email filter that, when a thread is begun by a specific > user . . . it cans every > message in that thread. The tried-and-true solution is both simple and civil, "Don't feed the trolls." Raymond -- http://mail.python.org/mailman/listinfo/python-list

RE: [Python-Dev] python optimization

2005-09-15 Thread Raymond Hettinger
[Neal Becker] > >>I don't know to what extent these kind of optimizations are available to > >>cpython. For example, are constant calculations removed from loops? [Brett Cannon] > > If you mean ``2+3``, then yes. [Greg Ewing] > Actually, no. Constant folding *could* be done, but it currently i

Re: Unexpected Behavior Iterating over a Mutating Object

2005-09-13 Thread Raymond Hettinger
[Dave Hansen] > It seems when an item is 'remove'd from data, the rest of the list > 'shifts' over one, so what was 'next' now occupies the slot of the > 'remove'd item. When the next 'item' is selected from 'data', the > _desired_ 'next' item is skipped. So when 'data' has several > consecutive

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: 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: Proposed PEP: New style indexing, was Re: Bug in slice type

2005-08-26 Thread Raymond Hettinger
Bryan Olson wrote: > The conclusion is inescapable: Python's handling of negative > subscripts is a wart. Indexing from the high end is too useful > to give up, but it should be specified by the slicing/indexing > operation, not by the value of the index expression. > > > PPEP (Proposed Python Enha

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: Why does min(A, B) not raise an error if A, B actually can't be compared?

2005-08-26 Thread Raymond Hettinger
[Claudio Grondi] > The still open question for me then is: > Why does min() not raise an error in case > there is no comparison function definition > for the feeded objects available? Actually, there is a comparison function for class instances. Unfortunately, the default method is not very usefu

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: Speed quirk: redundant line gives six-fold speedup

2005-08-25 Thread Raymond Hettinger
Mark Dickinson wrote: > I have a simple 192-line Python script that begins with the line: > > dummy0 = 47 > > The script runs in less than 2.5 seconds. The variable dummy0 is never > referenced again, directly or indirectly, by the rest of the script. > > Here's the surprise: if I remove or comme

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: Py_DECREF Question:

2005-08-15 Thread Raymond Hettinger
[Jeremy Moles] > When I add an object created locally to a mapping or sequence (that will > be returned from a function into an running instance of the Python > interpreter), I need to call Py_DECREF on the object, right? It depends on the the function or macro, but usually the answer is Yes. The

Re: Dictionary inheritance

2005-08-12 Thread Raymond Hettinger
[Talin] > I want to make a dictionary that acts like a class, in other words, > supports inheritance: If you attempt to find a key that isn't present, > it searches a "base" dictionary, which in turn searches its base, and so on. Perhaps the chainmap() recipe will meet your needs: http://aspn.

Re: Reliable destruction

2005-08-04 Thread Raymond Hettinger
[EMAIL PROTECTED] > My questions are: > 1) under normal conditions (no exceptions) is there a guarantee, that > __del__ of > all instruments is called at the end of measurement()? > > 2) if an exception is thrown, will all instruments be deleted if the > error > occurs in run() ? > (only the instru

Re: Art of Unit Testing

2005-08-03 Thread Raymond Hettinger
Christoph Zwerschke wrote: > I wasn't aware of the py lib so far. The > possibility to create fixtures at the three different scopes is exactly > what I was looking for. > > Anyway, I think it would be nice to have that feature in the standard > lib unittest as well. It should not be too hard to ad

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: can list comprehensions replace map?

2005-07-28 Thread Raymond Hettinger
[Paolino] > Well, for my little experiences use cases in which the lists have different > lengths are rare, but in those cases I don't see the reason of not being > able > to zip to the longest one.What is really strange is that I have to use > map(None,) for that,instead of another zip-like fu

Re: can list comprehensions replace map?

2005-07-27 Thread Raymond Hettinger
[David Isaac] > > I have been generally open to the proposal that list comprehensions > > should replace 'map', but I ran into a need for something like > > map(None,x,y) > > when len(x)>len(y). I cannot it seems use 'zip' because I'll lose > > info from x. How do I do this as a list comprehensio

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: 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: 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? Or do you have to pull them out to > unit test them, which basically means I will never use nested functions. Several commons use cases (closures and factory functions) ultimately expose the inner function through the return value. If that is the

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: 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: 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/python-l

Re: Efficiently Split A List of Tuples

2005-07-18 Thread Raymond Hettinger
[Ron Adam] > Currently we can implicitly unpack a tuple or list by using an > assignment. How is that any different than passing arguments to a > function? Does it use a different mechanism? It is the same mechanism, so it is also only appropriate for low volumes of data: a, b, c = *args

Re: list implementation

2005-07-17 Thread Raymond Hettinger
[sj] > I believe the type "list" is implemented as an array of pointers. Yes. > Thus, random access is an O(1) operation while insertion/deletion is an > O(n) operation. Yes. > 2. Implementing list as an array is part of language specification or > implementation-dependent? Implementation de

Re: Efficiently Split A List of Tuples

2005-07-17 Thread Raymond Hettinger
[Richard] > I know I can use a 'for' loop and create two new lists > using 'newList1.append(x)', etc. Is there an efficient way > to create these two new lists without using a slow for loop? If trying to optimize before writing and timing code, then at least validate your assumptions. In Python,

Re: Efficiently Split A List of Tuples

2005-07-17 Thread Raymond Hettinger
> Variant of Paul's example: > > a = ((1,2), (3, 4), (5, 6), (7, 8), (9, 10)) > zip(*a) > > or > > [list(t) for t in zip(*a)] if you need lists instead of tuples. [Peter Hansen] > (I believe this is something Guido considers an "abuse of *args", but I > just consider it an elegant use of zip() co

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: Filtering out non-readable characters

2005-07-16 Thread Raymond Hettinger
Wow, that was the most thorough answer to a comp.lang.python question since the Martellibot got busy in the search business. -- http://mail.python.org/mailman/listinfo/python-list

Re: Generating a list of None

2005-07-16 Thread Raymond Hettinger
[Bengt Richter] > how about (untested) > > def get_options(opts): > """Return True or False if an option is set or not""" > return [1 for val in vars(opts).values() if val is not None] and True or > False While we're tossing around hacks and coding atrocities, we should note that:

Re: set and frozenset unit tests?

2005-07-14 Thread Raymond Hettinger
[Jacob Page] > there are two minor things I > don't see documented that caught me by surprise: > > * Since the <=, <, >, and >= operators raise an exception if the > right-hand operand is not a set or frozenset, it seemed reasonable to > me to assume that == and != should, too. However, the test

Re: breaking out of nested loop

2005-07-13 Thread Raymond Hettinger
[rbt] > What is the appropriate way to break out of this while loop if the for > loop finds a match? > > while 1: > for x in xrange(len(group)): > try: > mix = random.sample(group, x) > make_string = ''.join(mix) > n = md5.new(make_string) >

Re: Inconsistency in hex()

2005-07-12 Thread Raymond Hettinger
[Steven D'Aprano] > > hex() of an int appears to return lowercase hex digits, and hex() of a > > long uppercase. [Terry Reedy] > Already bug-reported and fixed for 2.5 (to use lowercase, I believe). > http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1224347 Score another

Re: tuple.index(item)

2005-07-11 Thread Raymond Hettinger
f a patch to add this would be accepted. Probably checking > Sourceforge for past patches would give an answer, since it seems likely > someone has already tried. Executive summary: Guido likes it the way it is. Someday, he may change his mind. Probably not. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficiency of using long integers to hold bitmaps

2005-07-10 Thread Raymond Hettinger
[Jeff Melvaine] > I note that I can write expressions like "1 << 100" and the result is stored > as a long integer, which means it is stored as an integer of arbitrary > length. I may need to use a large number of these, and am interested to > know whether the storage efficiency of long integers i

Re: removing list comprehensions in Python 3.0

2005-07-09 Thread Raymond Hettinger
[Raymond Hettinger] > > It is darned inconvenient to get an iterator when you really > > need a list, when you want to slice the result, when you want to see a > > few elements through repr(), and when you need to loop over the > > contents more than once. [George Sakkis]

Re: removing list comprehensions in Python 3.0

2005-07-09 Thread Raymond Hettinger
[Steven Bethard] > I would hope that in Python 3.0 list comprehensions and generator > expressions would be able to share a large amount of implementation, and > thus that the speed differences would be much smaller. But maybe not... Looking under the hood, you would see that the implementations

Re: Defending Python

2005-07-09 Thread Raymond Hettinger
. So, I would recommend Python to these folks as an easily acquired extra skill. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: removing list comprehensions in Python 3.0

2005-07-09 Thread Raymond Hettinger
learning is that there is a place for both. It is darned inconvenient to get an iterator when you really need a list, when you want to slice the result, when you want to see a few elements through repr(), and when you need to loop over the contents more than once. Raymond Hettinger -- http

Re: precision problems in base conversion of rational numbers

2005-07-06 Thread Raymond Hettinger
> > For a simple example, convert both 10247448370872321 and > > 10247448370872319 from base ten to 4 digits of hex. The calculations > > need to be carried out to 15 places of hex (or 17 places of decimal) > > just to determine whether the fourth hex digit is a 7 or 8: > > > > >>> hex(1024744

Re: frozenset question

2005-07-06 Thread Raymond Hettinger
Will McGugan wrote: > Are there any benefits in using a frozenset over a set, other than it > being immutable? No. The underlying implementation is identical with set. The only difference is the addition of a hash method and absence of mutating methods. Everything else is the same. Raymond -

Re: precision problems in base conversion of rational numbers

2005-07-06 Thread Raymond Hettinger
[Terry Hancock] > > Needless to say, the conventional floating point numbers in Python > > are actually stored as *binary*, which is why there is a "decimal" > > module (which is new). > > > > If you're going to be converting between bases anyway, it probably > > makes little difference whether you

Re: f*cking re module

2005-07-06 Thread Raymond Hettinger
> There's really not a single good re tutorial or documentation >I could found! With * being a greedy operator, your post's subject line matches, "firetrucking" which, of course, has nothing to do with regular expressions, or python.org's re how-to guide, or Amazon's 18 books on the subject, or th

Re: Lisp development with macros faster than Python development?..

2005-07-06 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote: > The problem is that questions like 'What lang is fastest to develop > in?' > are hard to answer definitively. FWIW, Google's answer to that question is C++, Java, and Python. For any given problem, any of the three are acceptable. Each programmer or engineering team ge

<    1   2   3   4   5   6   7   8   >