Re: numbers to string
Robert Kern wrote: from numpy import * y = [116, 114, 121, 32, 116, 104, 105, 115] a = array(y, dtype=uint8) z = a.tostring() z 'try this' Very nice! Thanks also to Paul and Travis! Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
return same type of object
Instances of MyClass have a method that returns another instance. Ignoring the details of why I might wish to do this, I could return MyClass() or return self.__class__() I like that latter better. Should I? Should I do something else altogether? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: return same type of object
Bruno wrote: This is usually known as a 'factory method'. You do realise that both solutions are *not* strictky equilavent, do you? Your point I believe is that after inheritance the factory method in the subclass will still return MyClass() but will return an instance of the subclass if I return self.__class__() Right. You did not comment further so I take it your view is that each is fine, pick the one that gives the behavior you want. But Steve suggests going with the latter. Here is an (very crude) argument for going with the latter: if you know you want an instance of MyClass(), you can do that directly, but if you do this via a factory method, then (after inheritance) the action of the factory method becomes obscured. Does that make any sense? Thanks, Alan Isaac of the factory -- http://mail.python.org/mailman/listinfo/python-list
numbers to string
y [116, 114, 121, 32, 116, 104, 105, 115] z=''.join(chr(yi) for yi in y) z 'try this' What is an efficient way to do this if y is much longer? (A numpy solution is fine.) Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
item access time: sets v. lists
Is it expected for access to set elements to be much slower than access to list elements? Explanation? Thanks, Alan Isaac t1=timeit.Timer(for i in set(xrange(1)):pass,) t2=timeit.Timer(for i in list(xrange(1)):pass,) t1.timeit(1000) 9.806250235714316 t2.timeit(1000) 3.9823075279120701 -- http://mail.python.org/mailman/listinfo/python-list
Re: loop beats generator expr creating large dict!?
Alan Isaac wrote: The current situation is: use a loop because the obvious generator approach is not efficient. Fredrik Lundh [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] not efficient compared to what ? I already guess that I've missed your point, but to prove it... I was referring to the beginning of this thread where George noted that palettes = dict((w,set(w)) for w in words) runs slower than palettes={} for w in words: palettes[w]=set(w) The reason seems obvious: the otiose tuple creation, but there is no more efficient syntax to use with 'dict'. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: item access time: sets v. lists
Paul M. wrote: Random access to item in list/set when item exists set - 0.000241650824337 list - 0.0245168031132 Random access to item in list/set when item does not exist set - 0.000187733357172 list - 0.522086186932 OK, that's a much better set of answers including to questions I did not even know I wanted to ask until I saw your post. But, how to explain the above?? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
yet another groupsofn function (newbie entertainment)
I have not seen this posted and I kind of like it. Shared for entertainment value only. Alan Isaac PS Easily adapted if the residual group is not desired. def groupsofsize(iterable,size): itr = iter(iterable) c=count() for k,it in groupby(itr,lambda x:c.next()//size): yield tuple(y for y in it) -- http://mail.python.org/mailman/listinfo/python-list
Re: loop beats generator expr creating large dict!?
Does George's example raise the question: why do dictionaries not implement efficient creation for two common cases? - Making a dict from two sequences of the same length. - Making a dict from a sequence and a function (as in George's example in this thread). The current situation is: use a loop because the obvious generator approach is not efficient. Something seems wrong here... Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
SimpleParse installer available for 2.5
This is important for my move to Python 2.5, so I thought others might want to know... Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: what's new missing
Alan Isaac [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Where does one get the What's New document for Python 2.5? http://docs.python.org/dev/whatsnew/whatsnew25.html pretends to hold it, but the links are corrupt. OK, here it is: http://docs.python.org/whatsnew/whatsnew25.html Sorry for the noise. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
newbie division question
Suppose x and y are ints in moduleA. If I put from __future__ import division in moduleA then x/y will produce the truediv result. If I put from __future__ import division in moduleB and from moduleB import * in module A then x/y will NOT produce the truediv result (in moduleA). Why? And is there some way to avoid importing from __future__ in module after module? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie division question
Alan Isaac wrote: Suppose x and y are ints in moduleA. If I put from __future__ import division in moduleA then x/y will produce the truediv result. If I put from __future__ import division in moduleB and from moduleB import * in module A then x/y will NOT produce the truediv result (in moduleA). [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The statement from __future__ import division in ModuleB influences the byte codes generated when ModuleB is compiled. It doesn't influence the byte code generated in ModuleA. Start python with the -Qnew option. That is pretty good, but it affects every module I use, not just my (selected) modules. Thanks, Alan PS Any news on when true division will be the default? -- http://mail.python.org/mailman/listinfo/python-list
Re: best small database?
Thanks to all for the suggestions and much else to think about. Summarizing: Those who were willing to consider a database suggested: anydbm Gadfly SQLite (included with Python 2.5) Schevo Some preferred using the file system. The core suggestion was to choose a directory structure along with special naming conventions to indicate relationships. Not all who suggested this said how to store info about the files. One suggestion was: Store the info in a text file and read the entire file into memory and do linear searches. Python can search 100's of items in a list faster than you can even begin an SQL query. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
best small database?
I have no experience with database applications. This database will likely hold only a few hundred items, including both textfiles and binary files. I would like a pure Python solution to the extent reasonable. Suggestions? Thank you, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
change property after inheritance
Suppose a class has properties and I want to change the setter in a derived class. If the base class is mine, I can do this: http://www.kylev.com/2004/10/13/fun-with-python-properties/ Should I? (I.e., is that a good solution?) And what if I cannot change the base class? How to proceed then? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: change property after inheritance
Le mercredi 06 septembre 2006 16:33, Alan Isaac a écrit : Suppose a class has properties and I want to change the setter in a derived class. If the base class is mine, I can do this: http://www.kylev.com/2004/10/13/fun-with-python-properties/ Should I? (I.e., is that a good solution?) Maric Michaud [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Why not ? This ontroduce the notion of public getter a la C++/Java while the property is overloadable by itself (as below), but it's correct design IMHO. More support for lambda, it seems... Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
methods and functions, instances and classes
When I create an instance of a class, are the class's functions *copied* to create the methods? Or are method calls actually calls of the class's functions? I am sure this is both obvious and FAQ, but I did not find a clear answer (e.g. here http://docs.python.org/tut/node11.html#SECTION001134 , a lot turns on the meaning of 'equivalent'.) Thank you, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
replace deepest level of nested list
I have a list of lists, N+1 deep. Like this (for N=2): [[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11' ,'b11']]] I want to efficiently produce the same structure except that the utlimate lists are replaced by a chosen (by index) item. E.g., [['r00','r01'],['r10','r11']] N is not known ahead of time. Suggestions? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: methods and functions, instances and classes
Alan Isaac wrote: When I create an instance of a class, are the class's functions *copied* to create the methods? Or are method calls actually calls of the class's functions? Diez B. Roggisch [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On the class functions. You can make every instance have it's own methods, though - but only explicitly. Could you please elaborate on that last sentence? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: replace deepest level of nested list
Thanks to both Roberto and George. I had considered the recursive solution but was worried about its efficiency. I had not seen how to implement the numpy solution, which looks pretty nice. Thanks! Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: methods and functions, instances and classes
Alan Isaac wrote: are method calls actually calls of the class's functions? Bruno Desthuilliers [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Depends on how the method was associated to the instance (you can set methods on a per-instance property), but in the general case (functions defined in the class body), yes. [much useful stuff snipped] Thanks! Alan -- http://mail.python.org/mailman/listinfo/python-list
TNEF decoder
I'm aware of http://cheeseshop.python.org/pypi/pytnef/ but it uses the tnef utility, and I'd like a pure Python solution (along the lines of http://www.freeutils.net/source/jtnef/ ). Is there one? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Mahogany mail
Somewhat OT: Just wondering if anyone is doing something cool with the Python support in Mahogany mail. If so, please describe it or post some code. Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: How to draw line on Image?
Daniel Mark [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I want to draw some shapes, such as lines, circles on an image. http://www.pythonware.com/library/pil/handbook/psdraw.htm hth, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: text editor suggestion?
http://www.american.edu/econ/notes/soft.htm#EDITORS has some relevant discussion and suggestions. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
__contains__ vs. __getitem__
I have a subclass of dict where __getitem__ returns None rather than raising KeyError for missing keys. (The why of that is not important for this question.) I was delighted to find that __contains__ still works as before after overriding __getitem__.So even though instance['key'] does not raise KeyError, I still get (as desired) 'key' in instance == False. Looking forward: Can I count on this independence of __getitem__ and __contains__? I would like to understand whether it will be safe to count on this behavior. Thank you, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: __contains__ vs. __getitem__
Alan Isaac wrote: I have a subclass of dict where __getitem__ returns None rather than raising KeyError for missing keys. (The why of that is not important for this question.) Bruno Desthuilliers [EMAIL PROTECTED] wrote: Well, actually it may be important... What's so wrong with d.get('key') that you need this behaviour ? I want to use the mapping with string interpolation. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
import from containing folder
Suppose I have inherited the structure PackageFolder/ __init__.py mod1.py mod2.py SubPackageFolder/ __init__.py mod3.py and mod3.py should really use a function in mod2.py. *Prior* to Python 2.5, what is the best way to access that? (Please assume that move it is not the answer.) Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: import from containing folder
Simon Forman wrote: I would assume (but I haven't checked) that this should work as long as delmepy (in your case PackageFolder) was somewhere on sys.path. Sorry that was not clear: I do not want to make any assumptions about this particular package being on sys.path. (I want a relative import, but cannot assume 2.5.) Thanks, Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: import from containing folder
Alan wrote: I do not want to make any assumptions about this particular package being on sys.path. (I want a relative import, but cannot assume 2.5.) I should mention that to get around this I have been using sys.path.append(os.path.split(sys.argv[0])[0]) in the script I care most about. It works, but seems like a hack. Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: using names before they're defined
Suppose I have inherited the structure PackageFolder/ __init__.py mod1.py SubPackageFolder/ __init__.py mod2.py mod3.py When mod1 is run as a script, I desire to import either mod2 or mod3 but not both conditional on an option detected by the 'main()' function in mod1. Whichever is imported will be imported as, say, 'use_mod', and code in mod1 will refer to use_mod. Problem: classes in mod1 that refer to 'use_mod' of course raise a NameError, since the import does not take place until 'main()' is run. So, what is the right way to implement my desire? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
property __doc__
To access the doc string of a property, I have to use the class not an instance. Why? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Legitimate use of the is comparison operator?
(I was using *small* integers). Fredrik Lundh [EMAIL PROTECTED] wrote: small integers is what the phrase small integers in the small integers and small integers parts of my reply referred too, of course. But aren't *small* integers likely to be smaller than small integers? Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing PNG with pure Python
Em Sex, 2006-06-09 às 12:30 -0400, Alan Isaac escreveu: It's your code, so you get to license it. But if you wish to solicit patches, a more Pythonic license is IMHO more likely to prove fruitful. Felipe Almeida Lessa [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Pythonic license? That's new to me. I can figure out what a Python-like license is, but I'm clueless about a Pythonic license. http://www.panikon.com/phurba/alteng/i.html hth, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing PNG with pure Python
Johann C. Rocholl [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] What license would you suggest? I recommend that you choose the license that will best achieve your long run goals for the code. As I understand them, and as I understand your application and software development, this implies something like the MIT license: http://www.opensource.org/licenses/mit-license.php I believe that the MIT license maximizes the likelihood that a small scale application will receive useful patches, as long as you actively incorporate patches. You may reach other conclusions for many reasons ... Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
Rob Cowie [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] alpha = ['a','b','c','d'] #shortened for brevity alpha2 = ['a','b','c','d'] alpha3 = ['a','b','c','d'] def generator(): for char in alpha: for char2 in alpha2: for char3 in alpha3: yield char + char2 + char3 Basically fine, but you only need one string. E.g., alpha = abcd used three times. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
alpha = string.lowercase x=(a+b+c for a in alpha for b in alpha for c in alpha) -- http://mail.python.org/mailman/listinfo/python-list
Re: Request new feature suggestions for my PDF conversion toolkit - xtopdf
vasudevram [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] http://sourceforge.net/projects/xtopdf Serendipity: I was just looking for this functionality. Thanks! So here is an idea for a great enhancement: rst - PDF The good news: the project is all Python, so you will only have to write a writer! (But to make this great: support stylesheets!) Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy bug
Boris Borcic [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] after a while trying to find the legal manner to file numpy bug reports, since it's a simple one, I thought maybe a first step is to describe the bug here. Then maybe someone will direct me to the right channel. So, numpy appears not to correctly compute bitwise_and.reduce and bitwise_or.reduce : instead of reducing over the complete axis, these methods only take the extremities into account. Illustration : from numpy import * bitwise_or.reduce(array([8,256,32,8])) 8 import numpy numpy.__version__ '0.9.8' Platform : Win XP SP2, Python 2.4.2 Most bug reports start on the numpy list, I believe. (See above.) Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
FreeImagePy and PIL
I am just starting to think about image processing. What are the overlaps and differences in intended functionality between FreeImagePy and PIL? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
argmax
1. Why is there no argmax built-in? (This would return the index of the largest element in a sequence.) 2. Is this a good argmax (as long as I know the iterable is finite)? def argmax(iterable): return max(izip( iterable, count() ))[1] 3. If this is the only place in a module where I need count and izip, should I import them at the module level or at the level of the function? What are the considerations here? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: argmax
Thanks for all the replies. A couple of comments. 1. I think the usefulness of an argmax built-in can be assessed by looking at other languages (and e.g. at numpy). So I do not buy the not needed argument as presented. More like haven't got around to it, I'm thinking. 2. The particular use case this time is strategy choice. The desired strategy (i.e., index) is the one with the highest payoff. 3. Thanks to George, and to Peter for noticing a subtle difference in the implementations. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs are *MISUNDERSTOOD*, end of discussion. (Re: Tabs versus Spaces in Source Code)
Andy Sy wrote: Don't be evil - always configure your editor to convert tabs to true spaces. achates [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Yet another space-indenter demonstrates that problem actually lies with people who think that tab == some spaces. Exactly. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: simultaneous assignment
John Salerno [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Is there a way to assign multiple variables to the same value, but so that an identity test still evaluates to False? Make sure the value is not a singleton. Assign them one at a time. w=1000 x=1000 w==x True w is x False w=2 x=2 w==x True w is x True Hope that helps, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric, vectorization
RonnyM [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] e.g. y = [ 1, 2, 3, 4, 5, 6 ,7 ,8, 9 ] ybar = [ 1, (1 + 3)*.5,(2 + 4)*.5,(3 + 5)*.5,..., (n-1 + n+1)*.5 ], n = 1,...len(y) -1 How do I make a vectorized version of this, I will prefer not to utilize Map or similar functions, but numeric instead. You treat the first element asymmetrically, so that does not vectorize. The rest does: import numpy as N y=N.arange(1,10) slice1 = slice(0,-2,1) slice2 = slice(2,None,1) ybar = 0.5*(y[slice1]+y[slice2]) ybar array([ 2., 3., 4., 5., 6., 7., 8.]) hth, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: list*list
Diez B. Roggisch [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] it's considered bad style to use range if all you want is a enumeration of indices, as it will actually create a list of the size you specified. Use xrange in such cases. I'm pretty sure this distinction goes away in 2.5. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP PLEASE: What is wrong with this?
Ralph H. Stoos Jr. [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] HELP PLEASE: What is wrong with this?File autotp.py, line 21 ready = raw_input(Ready to proceed ? TYPE (y)es or (n)o: ) ^ Probably the parenthesis you forgot to close on the preceding line ... Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: access mbx files?
Donn Cave, [EMAIL PROTECTED] I suppose it isn't supported by the mailbox module basically because it isn't all that commonly encountered. It may be more common on mail servers, but there it's email net protocol data, POP or IMAP. If Mahogany has been using this format for `local' folders (i.e., via filesystem), I think that may have been kind of poor judgement on the part of its developers. I cannot judge that, although I think I recall the choice was made for reasons of speed. What do you see as the downsides? Just that it is uncommon (and thus questions like my original questions arise)? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and singletons
Alan asked: 2. If I really want a value True will I ever go astray with the test: if a is True: a = True b = 1. c = 1 a is True, b is True, c is True (True, False, False) Ziga Seilnacht [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I think that True and False, although they were added in version 2.3, were not true singeltons until version 2.4. OK, but Python 2.3 yields the same result as above. Ziga wrote: You should finish reading the PEP, see especially this part: - Don't compare boolean values to True or False using == Yes: if greeting: No:if greeting == True: Worse: if greeting is True: I do not think this is relevant to the question I asked, which was how to test for a value of True, if that's what I really want. I think the outcome of this discussion has been: use 'is'. Thanks, Alan -- http://mail.python.org/mailman/listinfo/python-list
access mbx files?
Should I be able to access mail messages in Mahogany mail's mbx format using the Python mailbox module? If so, can someone please post a working example? If not, can you please point me to documentation of the file format or better yet Python code to parse it? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: access mbx files?
Alan Isaac [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Should I be able to access mail messages in Mahogany mail's mbx format using the Python mailbox module? If so, can someone please post a working example? If not, can you please point me to documentation of the file format or better yet Python code to parse it? OK, from what I have been able to learn (not a lot), my original question may boiled down to: has anyone wrapped the cclient library for Python? The answer to that appears to be yes: http://freshmeat.net/projects/python-cclient/ Will I need to pursue this, or is this functionality somewhere in the mailbox module. (And if not, can someone please explain why not?) Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: __slots__
Aahz [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Because __slots__ breaks with inheritance. I believe that was the point of Ziga's example, which I acknowledged as a good one in my reply. So there still appears to be this single reason, which applies if your class may be subclassed. Does this beg the question of whether __slots__ *should* break with inheritance? One other question I did not get answered: is there any simple example of a Pythonic use of __slots__ that does NOT involve the creation of **many** instances. Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparisons and singletons
Ziga Seilnacht [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] a = 1 b = 1 a == b True a is b False Two follow up questions: 1. I wondered about your example, and noticed a = 10 b = 10 a is b True Why the difference? 2. If I really want a value True will I ever go astray with the test: if a is True: a = True b = 1. c = 1 a is True, b is True, c is True (True, False, False) Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: __slots__
Ziga Seilnacht [EMAIL PROTECTED] wrote: If you want to restrict attribute asignment, you should use the __setattr__ special method, see: http://docs.python.org/ref/attribute-access.html That should is what I am asking about. If I understand, in the simplest case, you want me to say something like def __setattr__(self,name,value): if name in myattrlist: object.__setattr__(self,name,value) else: raise AttributeError instead just saying __slots__ = myattrlist I understand that this *is* the prevailing advice. But why? class A(object): ... pass ... class B(A): ... __slots__ = ('spam',) ... b = B() b.eggs = 1 b.eggs 1 A good example of something that could be easily missed, and possibly an answer to my question above. (Although not I think if I am subclassing object.) Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
__slots__
1. Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. So this seemed an interesting restriction to impose in some instances, but I've noticed that this behavior is being called by some a side effect the reliance on which is considered unPythonic. Why? 2. What is a simple example where use of slots has caused subtle problems, as some claim it will? 3. What is a simple example of a Pythonic use of __slots__ that does NOT involved the creation of **many** instances. Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Numerical solver
Laszlo Zsolt Nagy [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I would like to use a numerical solver for a specific problem. Another possibility: http://nlpy.sourceforge.net/ Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: define loop statement?
Benji York [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Here's a flagrant hack: Admiration wins out over revulsion. ;-) Thanks, Alan Isaac PS Here's the motivation. Python closely resembles pseudocode. With a very little LaTeX hacking, it is often possible to write algorithms is Python that typeset as reasonable pseudocode. A simple repetitive loop is a bit of a sticking point. -- http://mail.python.org/mailman/listinfo/python-list
Re: define loop statement?
Alan Isaac wrote: I would like to be able to define a loop statement (nevermind why) so that I can write something like loop 10: do_something instead of for i in range(10): do_something Possible? If so, how? Jeffrey Schwab [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] class Loop: def __init__(self, n): self.n = n def __call__(self): self.n = self.n - 1 return self.n != 0 if __name__ == '__main__': loop = Loop(10) while loop(): print OK OK, that's pretty good. Thanks! Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
define loop statement?
I would like to be able to define a loop statement (nevermind why) so that I can write something like loop 10: do_something instead of for i in range(10): do_something Possible? If so, how? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda (and reduce) are valuable
Alan Isaac wrote: #evaluate polynomial (coefs) at x using Horner's rule def horner(coefs,x): return reduce(lambda a1,a2: a1*x+a2,coefs) It just cannot get simpler or more expressive. Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] But is it correct? Yes. Are we merely employing different conventions for the order of coefficients or is that simple and expressive lambda/reduce stuff obscuring an error? It is too simple and expressive to obscure an error. ;-) This is particularly important since coefficient order is not standardized across uses. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda (and reduce) are valuable
Chris Mellon [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] As someone who does a tremendous amount of event-driven GUI programming, I'd like to take a moment to speak out against people using us as a testament to the virtues of lamda. Event handlers are the most important part of event-driven code, and making them real functions with real names is crucial to maintainable code. The only reason to ever use a lamdba in Python is because you don't want to give a function a name, and that is just not a compelling use case for GUI events. Obviously opinions differ. See the discussion at http://www.artima.com/forums/flat.jsp?forum=106thread=98196start=30msRange=15 I find many of the pleas for lambda persuasive as well. For the contribution of lambda to maintainability, see e.g. Gary Robinson's comment at that link. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda (and reduce) are valuable
Jibes against the lambda-clingers lead eventually to serious questions of style in regard to variable namespacing, lifespan, cleanup, and so on: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ad0e15cb6b8f2c32/ Alan Isaac [EMAIL PROTECTED] wrote: #evaluate polynomial (coefs) at x using Horner's rule def horner(coefs,x): return reduce(lambda a1,a2: a1*x+a2,coefs) Cameron Laird [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I *think* you're supporting a claim about the value of lambda with a specific example. Do I have that right? Are you saying that your definition of horner() would suffer greatly without lambda? It is a simple example of how lambda and reduce can be very expressive. Anyone who understands Horner's rule can see at a glance that this code implements it. Anyone who has bothered to learn what lambda and reduce do can see at a glance what the algorithm is. It just cannot get simpler or more expressive. Suffer greatly? Surely not. For suffer greatly you would probably need to turn to people who do a lot of event-driven GUI programming. But suffer, yes. Simplicity and expressiveness are valuable. That is the point. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 7)
Cameron Laird [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Jibes against the lambda-clingers lead eventually to serious questions of style in regard to variable namespacing, lifespan, cleanup, and so on: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ad0e15cb6b8f2c32/ #evaluate polynomial (coefs) at x using Horner's ruledef horner(coefs,x): return reduce(lambda a1,a2: a1*x+a2,coefs)'Nuf said.Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] sufficiently similar I think I understand your points now. But I wanted to match these cases: import operator reduce(operator.add,[],42) 42 reduce(operator.add,[1],42) 43 The idea is that the i-th yield of i-reduce shd be the result of reduce on seq[:i] with the given initializer. That said, for the applications I first intended, yes it is sufficiently similar. For now, I'll stick with the version below. Thanks, Alan def ireduce(func, iterable, init=None): iterable = iter(iterable) if init is None: init = iterable.next() yield init else: try: init = func(init, iterable.next()) yield init except StopIteration: yield init for item in iterable: init = func(init, item) yield init -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I think that the test for an empty iterator makes ireduce() unintuitive. OK. I misunderstood you point. But that is needed to match the behavior of reduce. reduce(operator.add,[],42) 42 Thanks, Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP over TLS
Carl Waldbieser [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Does anyone know of any good examples for writing client side code to upload files over a secure FTP connection? http://trevp.net/tlslite/ Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I'd rather have a second look whether the test is really needed. That's too obscure of a hint. Can you be a bit more explicit? Here's an example (below). You're saying I think that most of it is unnecessary. Thanks, Alan def ireduce(func, iterable, init=None): iterable = iter(iterable) if init is None: init = iterable.next() yield init else: try: first = iterable.next() init = func(init, first) yield init except StopIteration: yield init for item in iterable: init = func(init, item) yield init -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Michael Spencer wrote: This can be written more concisely as a generator: [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] If iterable has no elements, I believe the behaviour should be [init], there is also the case of init=None that needs to be handled. Right. So it is more concise only by being incomplete, right? What other advantages might it have? otherwise, that is more or less what I wrote for my scanl/scanl1. I didn't see a post with that code. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Michael Spencer [EMAIL PROTECTED] wrote in message news:mailman.1054.1132707811.18701.python- This can be written more concisely as a generator: import operator def ireduce(func, iterable, init): ... for i in iterable: ... init = func(init, i) ... yield init OK, this might do it. But is a generator better? (I assume accuracy is the same, so what about speed?) def ireduce(func, iterable, init=None): if not init: iterable = iter(iterable) init = iterable.next() yield init elif not iterable: yield init for item in iterable: init = func(init, item) yield init Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] - allows arbitrary iterables, not sequences only - smaller memory footprint if sequential access to the items is sufficient Sure; I meant aside from that. - fewer special cases, therefore - less error prone, e. g. + does your implementation work for functions with f(a, b) != f(b, a)? See news:[EMAIL PROTECTED] + won't users be surprised that cumreduce(f, [1]) == cumreduce(f, [], 1) != cumreduce(f, [0]) == cumreduce(f, [], 0) THANKS! Of course nothing can beat a plain old for loop in terms of readability and -- most likely -- speed. OK. Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Of course nothing can beat a plain old for loop in terms of readability and -- most likely -- speed. Here are two versions, meant to be comparable. Thanks, Alan Isaac def cumreduce(func, seq, init = None): cr = seq[:] if not(init is None): if seq: cr[0] = func(init,seq[0]) else: cr = [init] for idx in range(1,len(seq)): cr[idx] = func(cr[idx-1],seq[idx]) return cr def ireduce(func, iterable, init=None): if init is None: iterable = iter(iterable) init = iterable.next() yield init elif not iterable: yield init for item in iterable: init = func(init, item) yield init -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Peter Otten [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] You are in for a surprise here: You got that right! def empty(): ... for item in []: ... yield item ... bool(empty()) True Ouch. bool(iter([])) True # python 2.3 and probably 2.5 bool(iter([])) False # python 2.4 Double ouch. I was relying on Python 2.4 behavior. What is the reasoning behind the changes? (Can you offer a URL to a discussion?) So, is the only way to test for an empty iterable to see if it can generate an item? I found this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413614 Seems like a reason to rely on sequences ... Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a flat list to a list of tuples
Duncan Booth [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] aList = ['a', 1, 'b', 2, 'c', 3] it = iter(aList) zip(it, it) [('a', 1), ('b', 2), ('c', 3)] That behavior is currently an accident. http://sourceforge.net/tracker/?group_id=5470atid=105470func=detailaid=1121416 Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] He seems to want scanl Yes. But it's not in Python, right? (I know about Keller's version.) Robert Kern wrote: Define better. More accurate? Less code? Good point. As Bonono (?) suggested: I'd most like a solution that relies on a built-in to give me both of those. (Pretty is good too.) Like SciPy's cumsum. Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: best cumulative sum
Alan Isaac wrote: Like SciPy's cumsum. Colin J. Williams [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Doesn't numarray handle this? Sure. One might say that numarray is in the process of becoming scipy. But I was looking for a solution when these are available. Something like: def cumreduce(func, seq, init = None): Return list of cumulative reductions. Example use: cumreduce(operator.mul, range(1,5),init=1) [1, 2, 6, 24] :author: Alan Isaac :license: public domain if not seq: cr = [init]*bool(init) else: cr = [seq[0]] * len(seq) if init: cr[0] = func(cr[0],init) for idx in range(1,len(seq)): cr[idx] = func(cr[idx-1],seq[idx]) return cr -- http://mail.python.org/mailman/listinfo/python-list
best cumulative sum
What's the good way to produce a cumulative sum? E.g., given the list x, cumx = x[:] for i in range(1,len(x)): cumx[i] = cumx[i]+cumx[i-1] What's the better way? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
grep
What's the standard replacement for the obsolete grep module? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: calling matlab
hrh1818 [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] There is a module named pymat avvailable from http://sourceforge.net/projects/pymat that provides a limited set of functions for intertfacing Python to Matlab. I think that pymat was superceded by mlabwrap http://mlabwrap.sourceforge.net/ Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: grep
Fredrik Lundh [EMAIL PROTECTED] wrote:: def grep(pattern, *files): search = re.compile(pattern).search for file in files: for index, line in enumerate(open(file)): if search(line): print :.join((file, str(index+1), line[:-1])) grep(grep, *glob.glob(*.py)) I was afraid the re module was the answer. ;-) Use of enumerate is a nice idea. Thanks. Alan -- http://mail.python.org/mailman/listinfo/python-list
extract PDF pages
While pdftk is awesome http://www.accesspdf.com/pdftk/ I am looking for a Python solution. Just for PDF page extraction. Any hope? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Permutation Generator
Casey Hawthorne [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] It's hard to make complete permutation generators, Knuth has a whole fascicle on it - The Art of Computer Programming - Volume 4 Fascicle 2 - Generating All Tuples and Permutations - 2005 Can you elaborate a bit on what you mean? Given a list of unique elements, it is easy enough to produce a complete permutation generator in Python, in the sense that it yields every possible permuation. (See my previous post.) So you must mean something else? Cheers, Alan Isaac PS If the elements are not unique, that is easy enough to deal with too, as long as you say what you want the outcome to be. -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP over SSL (explicit encryption)
Eric Nieuwland [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I'm having a look at FTP/S right now. That's a little more complicated, but it seems doable. If I succeed, I guess I'll donate the stuff as an extension to ftplib. Just found this: http://trevp.net/tlslite/ I haven't even had time to try it, but I thought you'd want to know. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP over SSL (explicit encryption)
http://www.lag.net/paramiko/ Alan Isaac [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(20) sock.connect((hostname, port)) my_t = paramiko.Transport(sock) my_t.connect(hostkey=None ,username=username, password=password, pkey=None) my_chan = my_t.open_session() my_chan.get_pty() my_chan.invoke_shell() my_sftp = paramiko.SFTP.from_transport(my_t) Now my_sftp is a paramiko sftp_client. See paramiko's sftp_client.py to see what it can do. When it rains it pours. wxSFTP http://home.gna.org/wxsftp/ uses paramiko and provides a GUI. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Permutation Generator
Talin [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I wanted to share this: a generator which returns all permutations of a list: Try this instead: def permuteg(lst): return ([lst[i]]+x for i in range(len(lst)) for x in permute(lst[:i]+lst[i+1:])) \ or [[]] Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP over SSL (explicit encryption)
David Isaac wrote: I am looking for a pure Python secure ftp solution. Does it exist? Andrew MacIntyre [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I recall coming across an extension package (pretty sure it wasn't pure Python anyway, certainly not for the SSL bits) with SFTP - I think the name was Paramiko or something like that. Unfortunately that's SSH2 only. It is indeed pure Python http://www.lag.net/paramiko/ However it requires the PyCrypto module. http://www.amk.ca/python/code/crypto Can you briefly outline how to use this as a client to upload and down files from a server using SFTP? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
FTP over SSL (explicit encryption)
I am looking for a pure Python secure ftp solution. Does it exist? I would have thought that the existence of OpenSSL would imply yes but I cannot find anything. ftplib does not seem to provide any secure services. I know about fptutil http://codespeak.net/mailman/listinfo/ftputil but that does not seem to provide any secure services. (Btw, Matt Croydon's intro is helpful for newbies: http://postneo.com/stories/2003/01/01/beyondTheBasicPythonFtplibExample.html ) I know about M2Crypto http://sandbox.rulemaker.net/ngps/m2/ but that requires installing SWIG and OpenSSL. (If someone tells me they have found this trivial under Windows, I am willing to try ... ) I would have thought that this was a common need with a standard Python solution, so I suspect I'm overlooking something obvious. Hoping, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP over SSL (explicit encryption)
Eric Nieuwland [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Do you want SFTP or FTP/S? The latter. I'm having a look at FTP/S right now. That's a little more complicated, but it seems doable. If I succeed, I guess I'll donate the stuff as an extension to ftplib. Great! Please post a link as soon as it is usable! Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
MultiFile object does not iterate
Why is a MultiFile object not an iterator? For example if mfp = multifile.MultiFile(fp)I cannot dofor line in mfp: do_somethingRelated:MultiFile.next seems badly named.(Something like next_section would be better.)Is this just historical accident or am I missing the point?Thanks,Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
can list comprehensions replace map?
Newbie question: 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 comprehension? (Or, more generally, what is the best way to do this without 'map'?) Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning histogram-like data for items in a list
Ric Deez [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have a list: L1 = [1,1,1,2,2,3] How can I easily turn this into a list of tuples where the first element is the list element and the second is the number of times it occurs in the list (I think that this is referred to as a histogram): For ease of reading (but not efficiency) I like: hist = [(x,L1.count(x)) for x in set(L1)] See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277600 Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Software needed
niXin [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Can anyone direct me to where I can find free software to do the following: Document Management Software --- 1. Written in PHP or Python 2. scanning feature - where I can scan a document http://furius.ca/nabu/ ? -- http://mail.python.org/mailman/listinfo/python-list
tuple.index(item)
Why don't tuples support an index method? It seems natural enough ... Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
default values of function parameters
Alan Isaac wrote: Default parameter values are evaluated once when the function definition is executed. Where are they stored? ... Where is this documented? Forgive any poor phrasing: I'm not a computer science type. At http://www.network-theory.co.uk/docs/pytut/tut_26.html we read: The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. But the default values of function parameters seem rather like a static attributes of a class. Is that a good way to think of them? If so, are they somehow accessible? How? Under what name? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: evaluated function defaults: stored where?
Alan Isaac wrote: Default parameter values are evaluated once when the function definition is executed. Where are they stored? ... Where is this documented? Forgive any poor phrasing: I'm not a computer science type. At http://www.network-theory.co.uk/docs/pytut/tut_26.html we read: The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. But the default values of function parameters seem rather like a static attributes of a class. Is that a good way to think of them? If so, are they somehow accessible? How? Under what name? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
evaluated function defaults: stored where?
Default parameter values are evaluated once when the function definition is executed. Where are they stored? (A guess: in a dictionary local to the function.) Where is this documented? As a Python newbie I found this behavior quite surprising. Is it common in many other languages? Is it unsurprising if I look at it right? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
mbx repair script: Python vs perl
I'm looking for the Python equivalent of the perl script and module described at http://comments.gmane.org/gmane.mail.imap.uw.c-client/707 Any hope? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: mbx repair script
Donn Cave [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] All mbx files start with a 2048 byte header, and a valid header can be copied to another file and still be valid. For example, if the damaged file still has 2048 bytes of header, 1. Find or create another mbx file spud. 2. Copy header:$ dd if=spud count=4 newbx 3. Copy old file: $ dd if=oldbx skip=4 newbx 4. change ownership and permission to match oldbx. This did not work for me. Should it? I thought the header contained information tightly tied to the rest of the content (to speed search etc) so that e.g., byte counts could matter. Can you point me to documentation of the mbx format? Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter weirdness item count
phil [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Using Tkinter Canvas to teach High School Geometry with A LOT of success. Can you post a link to your code. I'd like to see what you are doing. Thx, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
mbx repair script
I'm looking for a Python script to repair the mbx header for a mail file where only the header is corrupted. Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list