Re: empty classes as c structs?

2005-02-05 Thread Michael Spencer
Steven Bethard wrote: Nick Coghlan wrote: class attr_view(object): def __init__(self, data): self.__dict__ = data I think the idea definitely deserves mention as a possible implementation strategy in the generic objects PEP, with the data argument made optional: That's basically wh

Re: Read-only class properties

2005-07-10 Thread Michael Spencer
Bengt Richter wrote: ... > > class Foo(object): > class __metaclass__(type): > def __setattr__(cls, name, value): > if type(cls.__dict__.get(name)).__name__ == 'Descriptor': > raise AttributeError, 'setting Foo.%s to %r is not allowed' > %(name, value) >

Rich Graphics?

2005-07-27 Thread Chris Spencer
I'm trying to write a Gui in Python for manipulating rich graphical representations, similar to something like Inkscape. I've tried tkinter, wxPython, pyGtk, and while they all do traditional widgets well enough, none of them really handle anti-aliased, transparent, transformed shapes typical o

Persistent XMLRPC Connection

2005-08-14 Thread Chris Spencer
I noticed the SimpleXMLRPCServer/ServerProxy creates a new socket for remote procedure call. I've written a simple IP based authentication scheme for the Server, and I'd like to include the port in the authentication, which is currently not possible since the port keeps changing. I've looked a

Socket Troubles

2005-08-28 Thread Chris Spencer
I've written a simple class to manage P2P socket connections. However, whenever I try to receive data, the socket raises an exception with the error message (11, 'Resource temporarily unavailable'). My code's fairly straight-forward, with much of it right out of the Python docs, so I'm not sur

Re: Socket Troubles

2005-08-28 Thread Chris Spencer
Chris Spencer wrote: > I've written a simple class to manage P2P socket connections. However, > whenever I try to receive data, the socket raises an exception with the > error message (11, 'Resource temporarily unavailable'). > > My code's fairly straight-fo

Re: Socket Troubles

2005-08-28 Thread Chris Spencer
Michael Sparks wrote: > Chris Spencer wrote: > > At one point in your code you do this: > self._socket.setblocking(0) > > This says "if we can't recieve or send data without blocking, fail rather > than succeed". One of the failure modes is t

Lossless Number Conversion

2005-08-28 Thread Chris Spencer
Is there any library for Python that implements a kind of universal number object. Something that, if you divide two integers, generates a ratio instead of a float, or if you take the square root of a negative, generates a complex number instead of raising an exception? Lisp has something like

Re: redefining a function through assignment

2005-09-08 Thread Michael Spencer
Daniel Britt wrote: > Hello All, > I am new to Python so if there is an obvious answer to my question please > forgive me. Lets say I have the following code in mod1.py > > class test: > def func1(self): > print 'hello' > > > Now lets say I have another file called main.py: > > import mod1 >

Re: unusual exponential formatting puzzle

2005-09-21 Thread Michael Spencer
Neal Becker wrote: > Like a puzzle? I need to interface python output to some strange old > program. It wants to see numbers formatted as: > > e.g.: 0.23456789E01 > > That is, the leading digit is always 0, instead of the first significant > digit. It is fixed width. I can almost get it with

Re: unusual exponential formatting puzzle

2005-09-21 Thread Michael Spencer
Michael Spencer wrote: > Neal Becker wrote: > >>Like a puzzle? I need to interface python output to some strange old >>program. It wants to see numbers formatted as: >> >>e.g.: 0.23456789E01 >> >>That is, the leading digit is always 0, instead of t

Re: How do I convert arithemtic string (like "2+2") to a number?

2005-02-06 Thread Michael Spencer
John J. Lee wrote: "Adomas" <[EMAIL PROTECTED]> writes: Well, a bit more secure would be eval(expression, {'__builtins__': {}}, {}) or alike. Don't believe this without (or even with ;-) very careful thought, anyone. Google for rexec. John This module provides a more systematic way to set up res

Re: empty classes as c structs?

2005-02-06 Thread Michael Spencer
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: Hmm... interesting. This isn't the main intended use of Bunch/Struct/whatever, but it does seem like a useful thing to have... I wonder if it would be worth having, say, a staticmethod of Bunch that produced such a view, e.g.: class

Re: empty classes as c structs?

2005-02-07 Thread Michael Spencer
Nick Coghlan wrote: Steven Bethard wrote: It was because these seem like two separate cases that I wanted two different functions for them (__init__ and, say, dictview)... I see this, but I think it weakens the case for a single implementation, given that each implementation is essentially one me

Re: empty classes as c structs?

2005-02-07 Thread Michael Spencer
Steven Bethard wrote: Do you mean there should be a separate Namespace and Bunch class? Or do you mean that an implementation with only a single method is less useful? The former. If the former, then you either have to repeat the methods __repr__, __eq__ and update for both Namespace and Bunch,

Re: turing machine in an LC

2005-02-08 Thread Michael Spencer
Jeremy Bowers wrote: I can't figure out how to write a TM in a Python List Comprehension without one of either "variable binding" (so we can store the last symbol list and manipulate it in the next iteration) or "recursive function" (to express the whole tape as a recursive function), both of whic

Re: turing machine in an LC

2005-02-08 Thread Michael Spencer
Jeremy Bowers wrote: On Tue, 08 Feb 2005 17:36:19 +0100, Bernhard Herzog wrote: Now you *can* get at the previous state and write a state-transition expression in perfectly legal Python. What do you know, generator comprehensions are Turing Complete and list comprehensions aren't. I wouldn't have

Re: turing machine in an LC

2005-02-08 Thread Michael Spencer
Jeremy Bowers wrote: That's not a generator expression, that's a generator function. Nobody contests they can reference earlier states, that's most of their point :-) Are you sure? I just wrote my examples in functions to label them Here's your example with this method: >>> import itertools as it

Re: turing machine in an LC

2005-02-08 Thread Michael Spencer
Jeremy Bowers wrote: OK then, I still don't quite see how you can build a Turing Machine in one LC, but an LC and one preceding list assignment should be possible, although the resulting list from the LC is garbage; Not necessarily garbage - could be anything, say a copy of the results: >>> resul

A ListComp that maintains its own state (Was: Re: turing machine in an LC)

2005-02-08 Thread Michael Spencer
Jeremy Bowers <[EMAIL PROTECTED]> writes: On Tue, 08 Feb 2005 17:36:19 +0100, Bernhard Herzog wrote: Nick Vargish <[EMAIL PROTECTED]> writes: "Xah Lee" <[EMAIL PROTECTED]> writes: is it possible to write python code without any indentation? Not if Turing-completeness is something you desire. Ber

Re: A ListComp that maintains its own state (Was: Re: turing machine in an LC)

2005-02-08 Thread Michael Spencer
Carl Banks wrote: Pay attention, chief. I suggested this days ago to remove duplicates from a list. from itertools import * [ x for (x,s) in izip(iterable,repeat(set())) if (x not in s,s.add(x))[0] ] ;) Sorry, I gave up on that thread after the first 10 Million* posts. Who knows what other pe

Re: A ListComp that maintains its own state

2005-02-09 Thread Michael Spencer
Bernhard Herzog wrote: Michael Spencer <[EMAIL PROTECTED]> writes: So, here's factorial in one line: # state refers to list of state history - it is initialized to [1] # on any iteration, the previous state is in state[-1] # the expression also uses the trick of list.append() =>

Re: listerator clonage

2005-02-12 Thread Michael Spencer
Cyril BAZIN wrote: Hello, I want to build a function which return values which appear two or more times in a list: This is very similar to removing duplicate items from a list which was the subject of a long recent thread, full of suggested approaches. Here's one way to do what you want: >>> l

Re: Hack with os.walk()

2005-02-12 Thread Michael Spencer
Frans Englich wrote: Hello, Have a look at this recursive function: def walkDirectory( directory, element ): element = element.newChild( None, "directory", None ) # automatically appends to parent element.setProp( "name", os.path.basename(directory)) for root, dirs, files in os.walk(

Re: check if object is number

2005-02-12 Thread Michael Spencer
Steven Bethard wrote: Peter Hansen wrote: Of course, most of the other definitions of "is a number" that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. Or maybe not. (Pretty much all of them will call an arange a number

Re: check if object is number

2005-02-12 Thread Michael Spencer
Steven Bethard wrote: Michael Spencer wrote: Steven Bethard wrote: Peter Hansen wrote: Of course, most of the other definitions of "is a number" that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. How about

Re: Hack with os.walk()

2005-02-12 Thread Michael Spencer
Tim Peters wrote: [Frans Englich] ... [snip] class HasPath: def __init__(self, path): self.path = path def __lt__(self, other): return self.path < other.path class Directory(HasPath): def __init__(self, path): HasPath.__init__(self, path) self.files = []

Re: Iterator / Iteratable confusion

2005-02-13 Thread Michael Spencer
Francis Girard wrote: """ Example 8 Running after your tail with itertools.tee The beauty of it is that recursive running after their tai

Re: builtin functions for and and or?

2005-02-13 Thread Michael Spencer
Roose wrote: Yeah, as we can see there are a million ways to do it. But none of them are as desirable as just having a library function to do the same thing. I'd argue that since there are so many different ways, we should just collapse them into one: any() and all(). That is more in keeping wit

Re: Iterator / Iteratable confusion

2005-02-13 Thread Michael Spencer
"Francis Girard" <[EMAIL PROTECTED]> wrote in message an "iterator" doesn't have to support the "__iter__" method Terry Reedy wrote: Yes it does. iter(iterator) is iterator is part of the iterater protocol for the very reason you noticed... But, notwithstanding the docs, it is not essential t

Re: builtin functions for and and or?

2005-02-13 Thread Michael Spencer
Roose wrote: Previous discussion on this topic: http://groups-beta.google.com/group/comp.lang.python/msg/a76b4c2caf6c435c Michael OK, well then. That's really the exact same thing, down to the names of the functions. So what ever happened to that? I don't recall: probably http://www.google.c

Re: nested lists as arrays

2005-02-14 Thread Michael Spencer
naturalborncyborg wrote: Hi, I'm using nested lists as arrays and having some problems with that approach. In my puzzle class there is a swapelement method which doesn't work out. What "doesn't work out"? On casual inspection that method seems to "work": >>> p = Puzzle(2) >>> p.elements[0][0] =

Re: nested lists as arrays

2005-02-14 Thread Michael Spencer
Terry Reedy wrote: <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] def setRandomState(self): # container for the elements to pick from container = [1,2,3,4,5,6,7,8,-1] # create elements of puzzle randomly i = 0 j = 0 while i <= self.dim-1: whil

Re: Iterator / Iteratable confusion

2005-02-15 Thread Michael Spencer
Michael Spencer wrote: But, notwithstanding the docs, it is not essential that iter(iterator) is iterator Terry Reedy wrote: > iter(iterator) is iterator is part of the iterater protocol > [...]I interpret [your post] as saying three things: 1. "There is more than one possible de

Re: Can __new__ prevent __init__ from being called?

2005-02-15 Thread Michael Spencer
Peter Hansen wrote: Felix Wiemann wrote: Sometimes (but not always) the __new__ method of one of my classes returns an *existing* instance of the class. However, when it does that, the __init__ method of the existing instance is called nonetheless, so that the instance is initialized a second time

Re: renaming 'references' to functions can give recursive problems

2005-02-16 Thread Michael Spencer
peter wrote: Hello, nice solution: but it puzzles me :) can anyone tell me why ---correct solution def fA(input): return input def newFA(input, f= fA): return f(input) fA = newFA is correct and: -infinite loop- def fA(input): return input d

Re: sampling items from a nested list

2005-02-16 Thread Michael Spencer
Steven Bethard wrote: So, I have a list of lists, where the items in each sublist are of basically the same form. It looks something like: ... Can anyone see a simpler way of doing this? Steve You just make these up to keep us amused, don't you? ;-) If you don't need to preserve the ordering, wo

Re: Iterator / Iteratable confusion

2005-02-16 Thread Michael Spencer
Terry Reedy wrote: "Michael Spencer" <[EMAIL PROTECTED]> wrote in message We are both interested in the murky edges at and beyond conventional usage. ... I am quite aware that multiple iterators for the same iterable (actual or conceptual) can be useful (cross products, for exa

Re: Iterator / Iteratable confusion

2005-02-16 Thread Michael Spencer
Adam DePrince wrote: How is a spencerator [an iterator that doesn't return itself unmodified on iter] > different than itertools.tee? Taking your question literally, it changes the behavior of an itertools.tee object 'tee', so that iter(tee) returns tee.__copy__(), rather than tee itself. It wa

Re: renaming 'references' to functions can give recursive problems

2005-02-16 Thread Michael Spencer
peter wrote: brain reset and understood thx a lot for all your answers Peter Now that you've got reset, you might want to consider an alternative solution: def fA(input): return input oldfA = fA # Hold a reference to the the old function def newFA(input): "Do something new" return oldfA

Re: sampling items from a nested list

2005-02-16 Thread Michael Spencer
Michael Spencer wrote: >>> def resample2(data): ... bag = {} ... random.shuffle(data) ... return [[(item, label) ... for item, label in group ... if bag.setdefault(label,[]).append(item) ... or len(bag[la

Re: sampling items from a nested list

2005-02-16 Thread Michael Spencer
Steven Bethard wrote: Michael Spencer wrote: Steven Bethard wrote: So, I have a list of lists, where the items in each sublist are of basically the same form. It looks something like: ... Can anyone see a simpler way of doing this? Steve You just make these up to keep us amused, don'

Re: check if object is number

2005-02-17 Thread Michael Spencer
Christos TZOTZIOY Georgiou wrote: On Sat, 12 Feb 2005 16:01:26 -0800, rumours say that Michael Spencer <[EMAIL PROTECTED]> might have written: Yup, that's basically what I'm doing right now. The question was really how to define that adapter function. =) Steve OK -

Re: Alternative to standard C "for"

2005-02-17 Thread Michael Spencer
James Stroud wrote: It seems I need constructs like this all of the time i = 0 while i < len(somelist): if oughta_pop_it(somelist[i]): somelist.pop(i) else: i += 1 There has to be a better way... Do you have to modify your list in place? If not, just create a copy with the filtered ite

Re: How to wrap a class's methods?

2005-02-17 Thread Michael Spencer
Grant Edwards wrote: On 2005-02-17, Steven Bethard <[EMAIL PROTECTED]> wrote: py> class C(object): ... def f(self, *args): ... print "f:", args ... def g(self, *args): ... print "g:", args ... py> class D(C): ... pass ... py> class Wrapper(object): ... def __init__(

Re: How to wrap a class's methods?

2005-02-17 Thread Michael Spencer
John Lenton wrote: On Thu, Feb 17, 2005 at 07:32:55PM +, Grant Edwards wrote: I'd usually put big fat warnings around this code, and explain exaclty why I need to do things this way... As a low-tech alternative, what about sourcecode generation, since you are targetting a python module? Thi

Re: Solution for architecure dependence in Numeric ?

2005-02-18 Thread Michael Spencer
"Johannes Nix|Johannes.Nix"@uni-oldenburg.de wrote: Hi, I have a tricky problem with Numeric. Some time ago, I have generated a huge and complex data structure, and stored it using the cPickle module. Now I want to evaluate it quickly again on a workstation cluster with 64-Bit Opteron CPUs - I have

Re: Style guide for subclassing built-in types?

2005-02-23 Thread Michael Spencer
[EMAIL PROTECTED] wrote: Kent Johnson wrote: [EMAIL PROTECTED] wrote: p.s. the reason I'm not sticking to reversed or even reverse : suppose the size of the list is huge. reversed() returns an iterator so list size shouldn't be an issue. What problem are you actually trying to solve? Kent Oh, you

Re: [perl-python] generic equivalence partition

2005-02-24 Thread Michael Spencer
David Eppstein wrote: In article <[EMAIL PROTECTED]>, "Xah Lee" <[EMAIL PROTECTED]> wrote: given a list aList of n elements, we want to return a list that is a range of numbers from 1 to n, partition by the predicate function of equivalence equalFunc. In the worst case, this is going to have to

Re: accessor/mutator functions

2005-02-25 Thread Michael Spencer
[EMAIL PROTECTED] wrote: When I look at how classes are set up in other languages (e.g. C++), I often observe the following patterns: 1) for each data member, the class will have an accessor member function (a Get function) 2) for each data member, the class will have a mutator member function (a S

Re: accessor/mutator functions

2005-02-25 Thread Michael Spencer
[EMAIL PROTECTED] wrote: If the class had two attributes--x and y--would the code look like something lik this: class C(object): def __init__(self): self.__x = 0 self.__y = 0 def getx(self): return self.__x def setx(self, x):

Re: Converting HTML to ASCII

2005-02-25 Thread Michael Spencer
gf gf wrote: [wants to extract ASCII from badly-formed HTML and thinks BeautifulSoup is too complex] You haven't specified what you mean by "extracting" ASCII, but I'll assume that you want to start by eliminating html tags and comments, which is easy enough with a couple of regular expressions:

Re: Converting HTML to ASCII

2005-02-25 Thread Michael Spencer
Mike Meyer wrote: It also fails on tags with a ">" in a string in the tag. That's well-formed but ill-used HTML. True enough...however, it doesn't fail too horribly: >>> striptags("""the text""") "'>the text" >>> and I think that case could be rectified rather easily, by stripping an

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

2005-03-01 Thread Michael Spencer
Steven Bethard wrote: Nick Coghlan wrote: > Hmm, it might be nice if there was a UserList.ListMixin that was the > counterpart to UserDict.DictMixin 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 List

Re: reuse validation logic with descriptors

2005-03-01 Thread Michael Spencer
David S. wrote: This still fails to work for instances variables of the class. That is if I use your property in the following: py> ...class Flags(object): ...def __init__(self): ... a = singlechar ... you should write that as: class Flags(object): a = singlechar def

Re: Is it possible to specify the size of list at construction?

2005-03-01 Thread Michael Spencer
Anthony Liu wrote: I cannot figure out how to specify a list of a particular size. For example, I want to construct a list of size 10, how do I do this? A list does not have a fixed size (as you probably know) But you can initialize it with 10 somethings > >>> [None]*10 [None, None, None, None, N

Re: Is it possible to specify the size of list at construction?

2005-03-01 Thread Michael Spencer
Anthony Liu wrote: Yes, that's helpful. Thanks a lot. But what if I wanna construct an array of arrays like we do in C++ or Java: myArray [][] Basically, I want to do the following in Python: myArray[0][1] = list1 myArray[1][2] = list2 myArray[2][3] = list3 here you have to be careful to create N

Re: Best way to make a list unique?

2005-03-08 Thread Michael Spencer
Delaney, Timothy C (Timothy) wrote: Michael Hoffman wrote: For those who don't know, these implement a hash set/map which iterates in the order that the keys were first added to the set/map. I would love to see such a thing. I've proposed this on python-dev, but the general feeling so far is agai

Re: Best way to make a list unique?

2005-03-09 Thread Michael Spencer
Marc Christiansen wrote: Michael Spencer <[EMAIL PROTECTED]> wrote: Nice. When you replace None by an object(), you have no restriction on the elements any more: Thanks for the suggestion, Marc. Note that if there is no need to access the middle of the collection, then the implementat

Re: Is there a short-circuiting dictionary "get" method?

2005-03-09 Thread Michael Spencer
Dave Opstad wrote: In this snippet: d = {'x': 1} value = d.get('x', bigscaryfunction()) the bigscaryfunction is always called, even though 'x' is a valid key. Is there a "short-circuit" version of get that doesn't evaluate the second argument if the first is a valid key? For now I'll code around

Re: looking for case insesitive dictionary

2005-03-09 Thread Michael Spencer
Andy Leszczynski wrote: so e.g. x={} x['a']=1 x['A']=2 print x['a'] #prints 2 Thx, A. http://www.google.com/search?&q=python+case+insensitive+dictionary Michael -- http://mail.python.org/mailman/listinfo/python-list

Re: Iterate using tuple as index

2005-03-10 Thread Michael Spencer
James Stroud wrote: Hello, Its not obvious to me how to do this. I would like to iterate using a tuple as an index. Say I have two equivalently sized arrays, what I do now seems inelegant: for index, list1_item in enumerate(firstlist): do_something(list1_item, secondlist[index]) I would like s

Re: instantiate new objects

2005-03-10 Thread Michael Spencer
Felix Steffenhagen wrote: [snip] > In: http://www.informatik.uni-freiburg.de/~steffenh/bayes.py > [bayes.test gives different results each time it is called] Without looking in the slightest at what you are implementing or how, this implies that state is maintained between calls to test The quest

[Python-Dev] Re: Adding any() and all()

2005-03-10 Thread Michael Spencer
Guido van Rossum wrote: See my blog: http://www.artima.com/forums/flat.jsp?forum=106&thread=98196 Do we even need a PEP or is there a volunteer who'll add any() and all() for me? Surely these can be written easily with existing constructs: def any(S): return reduce(lambda x, y: bool(x or y), fi

Re: __getitem__ on new-style classes

2005-03-10 Thread Michael Spencer
[EMAIL PROTECTED] wrote: What i'm trying to do is tie special methods of a "proxy" instance to another instance: ... new style classes: def test2(): print "test2" class Container(object): def __init__( self, data ): self.data = data # self.__dict__["__getitem__"] = self.data.__ge

Re: a RegEx puzzle

2005-03-11 Thread Michael Spencer
Charles Hartman wrote: I'm still shaky on some of sre's syntax. Here's the task: I've got strings (never longer than about a dozen characters) that are guaranteed to be made only of characters 'x' and '/'. In each string I want to find the longest continuous stretch of pairs whose first characte

Re: S-exression parsing

2005-03-11 Thread Michael Spencer
George Sakkis wrote: The S-expression parser below works, but I wonder if it can be simplified; it's not as short and straightforward as I would expect given the simplicity of S-expressions. Can you see a simpler non-recursive solution ? How about this (minus your error checking)? def parseS(expr

Re: Wishlist item: itertools.flatten

2005-03-11 Thread Michael Spencer
Ville Vainio wrote: "Christos" == TZOTZIOY writes: >> For quick-and-dirty stuff, it's often convenient to flatten a sequence >> (which perl does, surprise surprise, by default): >> >> [1,2,[3,"hello",[[4 -> >> >> [1, 2, 3, 'hello', 4] Christos> See Python Libr

Re: novice question

2005-03-11 Thread Michael Spencer
Leeds, Mark wrote: I have a dictionary grp that has lists for each element ( excuse my terminology if it's incorrect). So gname might be automobiles, finance, construction etc and grp[gname] is a list and this list has elements that are strings such as ["AAA","BBB","AAA","CCC"] Is there a quick way

Re: Adapting code to multiple platforms

2005-03-11 Thread Michael Spencer
Jeffrey Barish wrote: class super: '''All the generic stuff goes here''' Better not to call the class super: it's a built-in type class linux_subclass(super): def func(self): '''linux-specific function defined here''' class windows_subclass(super): def func(self): '''win

Re: Turning String into Numerical Equation

2005-03-12 Thread Michael Spencer
Brian Kazian wrote: Thanks for the help, I didn't even think of that. I'm guessing there's no easy way to handle exponents or logarithmic functions? I will be running into these two types as well. "Artie Gold" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] eval will handle exponent

Re: pyasm 0.2 - dynamic x86 assembler for python

2005-03-13 Thread Michael Spencer
_CONST(1) BINARY_SUBTRACT() ROT_THREE() POP_TOP() DUP_TOP() LOAD_CONST(1) BINARY_SUBTRACT() ROT_THREE() ROT_TWO() POP_TOP() POP_TOP() return # ByteCode.py

Re: Wishlist item: itertools.flatten

2005-03-14 Thread Michael Spencer
Leif K-Brooks wrote: Michael Spencer wrote: if hasattr(item,"__iter__"): # Avoids iterating over strings That's probably the cleanest way to avoid strings, but it's unfortunately not a good idea IMHO. Many objects (IndexedCatalog's Result objects are what

Re: Determining the length of strings in a list

2005-03-14 Thread Michael Spencer
[EMAIL PROTECTED] wrote: I have a dictionary. Each key contains a list. I am using the contents of the list to build a portion of a command line. However, before I can build the command line, I have to make sure that the command isn't too long. Depending on how you join the list items, you may ju

Re: Turning String into Numerical Equation

2005-03-14 Thread Michael Spencer
Giovanni Bajo wrote: Michael Spencer wrote: * this means that, eval("sys.exit()") will likely stop your interpreter, and there are various other inputs with possibly harmful consequences. Concerns like these may send you back to your original idea of doing your own expression parsi

Re: Turning String into Numerical Equation

2005-03-15 Thread Michael Spencer
Giovanni Bajo wrote: Steven Bethard wrote: I use something along these lines: def safe_eval(expr, symbols={}): return eval(expr, dict(__builtins__=None, True=True, False=False), symbols) import math def calc(expr): return safe_eval(expr, vars(math)) That offers only notional security: >>> ca

Re: code for Computer Language Shootout

2005-03-15 Thread Michael Spencer
Jacob Lee wrote: There are a bunch of new tests up at shootout.alioth.debian.org for which Python does not yet have code. I've taken a crack at one of them, a task to print the reverse complement of a gene transcription. Since there are a lot of minds on this newsgroup that are much better at optim

Re: code for Computer Language Shootout

2005-03-15 Thread Michael Spencer
Jacob Lee wrote: On Tue, 15 Mar 2005 21:38:48 -0800, Michael Spencer wrote: string.translate is a good idea. Note you can handle upper-casing and translation in one operation by adding a mapping from lower case to the complement i.e., table = string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsr

Re: code for Computer Language Shootout

2005-03-16 Thread Michael Spencer
F. Petitjean wrote: Le Tue, 15 Mar 2005 23:21:02 -0800, Michael Spencer a écrit : def output(seq, linelength = 60): if seq: iterseq = iter(seq) while iterseq: print "".join(islice(iterseq,linelength)) I suppose you mean : print ""

Re: Turning String into Numerical Equation

2005-03-16 Thread Michael Spencer
Giovanni Bajo wrote: Michael Spencer wrote: In fact, I believe my solution to be totally safe, That's a bold claim! I'll readily concede that I can't access func_globals from restricted mode eval (others may know better). But your interpreter is still be vulnerable to DOS-st

Re: code for Computer Language Shootout

2005-03-16 Thread Michael Spencer
Steven Bethard wrote: Michael Spencer wrote: def output(seq, linelength = 60): if seq: iterseq = iter(seq) while iterseq: print "".join(islice(iterseq,linelength)) Worth noting: "while iterseq" only works because for this case, you have a

Re: generic text read function

2005-03-17 Thread Michael Spencer
John Hunter wrote: "les" == les ander <[EMAIL PROTECTED]> writes: les> Hi, matlab has a useful function called "textread" which I am les> trying to reproduce in python. les> two inputs: filename, format (%s for string, %d for integers, les> etc and arbitary delimiters) Builing on J

Re: Interface support?

2005-03-17 Thread Michael Spencer
Steve wrote: Is it possible to design interfaces that classes must implement in Python? There are some well-known 'independent' implementations of interfaces: Zope Interfaces :http://www.zope.org/Wikis/Interfaces/FrontPage - a separable component of the much larger app server

Re: Pre-PEP: Dictionary accumulator methods

2005-03-18 Thread Michael Spencer
Raymond Hettinger wrote: I would like to get everyone's thoughts on two new dictionary methods: +1 count ? appendlist The proposed names could possibly be improved (perhaps tally() is more active and clear than count()). IMO 'tally' is exactly the right method name One issue is with negative incre

Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Michael Spencer
Raymond Hettinger wrote: I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self[key] += qty except KeyError: self[key] = qty def appendlist(self, key, *values):

Re: Building Time Based Bins

2005-03-19 Thread Michael Spencer
MCD wrote: Hello, I'm new to python and this group and am trying to build some bins and was wondering if any of you could kindly help me out. I'm a bit lost on how to begin. I have some text files that have a time filed along with 2 other fields formatted like this >> 1231 23 56 1232 25 79 1234 26

Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Michael Spencer
Kay Schluehr wrote: Maybe also the subclassing idea I introduced falls for short for the same reasons. Adding an accumulator to a dict should be implemented as a *decorator* pattern in the GoF meaning of the word i.e. adding an interface to some object at runtime that provides special facilities. U

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

2004-12-17 Thread Michael Spencer
Bengt Richter wrote: On Fri, 17 Dec 2004 02:06:01 GMT, Steven Bethard <[EMAIL PROTECTED]> wrote: Michael Spencer wrote: ... conv = "".join(char.lower() for char in text if char not in unwanted) Probably a good place to use str.replace, e.g. conv = text.lower() for char in u

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

2004-12-16 Thread Michael Spencer
Steve Holden wrote: Mark Devine wrote: Actually what I want is element 'class-map match-all cmap1' from list 1 to match 'class-map cmap1 (match-all)' or 'class-map cmap1 mark match-all done' in list 2 but not to match 'class-map cmap1'. Each element in both lists have multiple words in them. If a

Re: Securing a future for anonymous functions in Python

2004-12-30 Thread Michael Spencer
us functions, but that is another topic Michael Spencer -- http://mail.python.org/mailman/listinfo/python-list

Re: Overloaded Constructors?!?

2005-03-20 Thread Michael Spencer
[EMAIL PROTECTED] wrote: [trying to create a single Python class with the equivalent of the following overloaded constructors] wxFoldWindowItem(wxWindow *wnd, int flags = wxFPB_ALIGN_WIDTH, int ySpacing = wxFPB_DEFAULT_YSPACING, int leftSpacing = wxFPB_DEFAULT_LE

Re: Building Time Based Bins

2005-03-21 Thread Michael Spencer
MCD wrote: Thanks Alessandro... I'll have to try that as well. I have a modified working version of John's code (thanks John!). I'm able to output the bins by 5min intervals, sum one of the fields, and get the high and low of each field. So far I'm really happy with how it works. Thank you to every

Re: Building Time Based Bins

2005-03-21 Thread Michael Spencer
MCD wrote: Hi Michael, thanks for responding. I actually don't use a method to get each bin... That's because you picked the wrong suggestion ;-) No, seriously, you can do it easily with this approach: the bin outputs are nested in the loop. Here's my code: data_file = open('G:\file.txt') DUMM

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

2005-03-22 Thread Michael Spencer
How about a category for executable limericks? Here's one to get the ball rolling: # voice only the alphanumeric tokens from itertools import repeat for feet in [3,3,2,2,3]: print " ".join("DA-DA-DUM" for dummy in [None] for foot in repeat("metric", feet)) Michael P.S. I know 'three' doesn

Re: Building Time Based Bins

2005-03-22 Thread Michael Spencer
MCD wrote: I've mostly been racking my brain with this bit of code: newtm = ((klock + 4) // 5 * 5 ) % 2400 You might want to take another look at the first reply I sent you: it contains a function that does this: def groupkey(data): """Groups times by 5 min resolution. Note this version does

An Abridged Python Tutorial

2005-03-24 Thread Michael Spencer
An Abridged Python Tutorial There are tips for the novice and tricks that will add to your programming kicks. But the cardinal rule that you must learn at school is that spaces and tabs never mix. If there's syntax you don't understand, assistance is always at hand: a glance at the cook

Re: Python for a 10-14 years old?

2005-03-24 Thread Michael Spencer
Simon Brunning wrote: On 23 Mar 2005 21:03:04 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: Is there something out there like "Python for kids" which would explain *basic* programming concepts in a way which is accessible and entertaining for kids aged 10-14 (that about where her brain is rig

Black Magic - Currying using __get__

2005-03-24 Thread Michael Spencer
Wow - Alex Martelli's 'Black Magic' Pycon notes http://www.python.org/pycon/2005/papers/36/pyc05_bla_dp.pdf include this gem: > Functions 'r descriptors > def adder(x, y): return x + y > add23 = adder.__get__(23) > add42 = adder.__get__(42) > print add23(100), add42(1000) > 123 1042 This me

Re: Python docs [was: function with a state]

2005-03-24 Thread Michael Spencer
Paul L. Du Bois wrote: Xah Lee wrote: I think i'll just post... [ snipped ] That is a very good analysis. Can you submit a documentation patch? I would, but I'm too lazy to contribute. That doesn't mean I'm not thankful for your efforts, though! p Or if not a doc patch, how about a limerick? M

Re: Suggesting a new feature - "Inverse Generators"

2005-03-25 Thread Michael Spencer
Tim Hochberg wrote: Jordan Rastrick wrote: itertools.groupby enables you to do this, you just need to define a suitable grouping function, that stores its state: For example, if short lines should be appended to the previous line: from itertools import groupby linesource = """\ Here is a long lin

<    1   2   3   4   5   >