(MAC) CoreGraphics module???
Running OS X 10.4 "Tiger". Various references by Apple and others say that there exists a module that gives Quartz bindings, allowing all sort of graphics things in Python. Sure enough, after installing Xcode I have some sample scripts. They all start with from CoreGraphics import * (as do all the examples in two books, both of which say they're talking about Tiger.) I get an ImportError trying to import CoreGraphics. I found a CoreGraphics.py in a folder named Carbon; when I change the script to read import Carbon from Carbon.CoreGraphics import * there's no import error, but all of the Quartz things are NameErrors. I look at CoreGraphics.py, it's just about twenty lines long, defining a few constants with Quartz-sounding names. What gives? I'm supposed to do something else? Someone accidentally deleted all the code from my CoreGraphics.py? (Is there a working CoreGraphics.py around somewhere? I found a file somewhere on the net that was the same as mine except it ended with from CG import * Adding that doesn't change anything.) (Yes, the XCode installation seems to be working fine.) ??? **** David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: (MAC) CoreGraphics module???
On Thu, 01 Nov 2007 19:39:20 -0500, Robert Kern <[EMAIL PROTECTED]> wrote: >David C. Ullrich wrote: >> [why doesn't CoreGraphics work?] > >That's different than the one that is referenced. The one those articles >reference is only available in the Python that came with the system in >/System/Library/Frameworks/Python.framework, not one that you might have >installed from www.python.org into /Library/Frameworks/Python.framework. The >module was made by Apple, and they have not released the source code, so it >cannot be made to work with the www.python.org distribution. usenet is amazing - your reply appears to have been posted a half hour before my question! Thanks. So CoreGraphics is a builtin in Apple-Python, explaining why I didn't find the relevant CoreGraphics.py anywhere on the hard drive, eh? Fine. Now what? Please feel free to bear in mind that I have very little experience with the Mac and with Unix - I'm certain that if I knew what I was doing there I wouldn't need to ask the questions below, sorry. And sorry about the length of this post - there's a second issue that maybe you could explain, that I'd really love to have an explanation for before modifying things. Anyway: Since I didn't do anything special to remove it when I installed the Python-Python, the Apple-Python should still be there, yes? I'd appreciate any advice on how to get things set up the way I'd like. Below when I refer to the MacPython stuff I mean ApplicationLauncher (or however it's spelled, the Mac's at the office and I'm at home) and Idle; the stuff that gives convenient access to Python scripts in the GUI. Note that I don't have any particular reason to want to use the latest version of Python - I was actually getting along fine with 1.5 until very recently. I'd be perfectly happy to set things up so everything used the Apple-Python. (i) If I just uninstalled the Python-Python (how?) would everything (Terminal, the MacPython stuff) automagically find the Apple-Python instead? (ii) If not, what would I have to do to make things use the Apple-Python instead? (And if I have to do something to make that happen, would doing that still work if I just left the Python-Python sitting there?) OR: Is there something special I could do with CoreGraphics scripts and/or how I invoke them so that _they_ would use the Apple-Python while other scripts would just use the Python-Python as now? (A last choice would be a setup where most scripts work as they do now and I somehow make CoreGraphics work from Terminal but not in Finder...) (Hmm, a wild guess: something somewhere is an alias to Python-Python, and I just change that (how?) to an alias to Apple-Python?) I'm a little nervous about making any changes, because something very mysterious happened when I was setting things up the way they are now - since I have no idea what I did to make things work the way they are now I don't know that I could set things up the way they are now again if I had to. If you can explain the following that will be something (I've been meaning to ask about the following sometime, hasn't been important til now when I'm contemplating changing the setup): The history: I get a Mac. I discover that it includes Python, can't figure out how to execute .py files in Finder. I hear about MacPython. I install the "small" MacPython download, that's supposed to just add ApplicationLauncher(?), Idle, etc on top of the existing Python. Works fine _except_ that when I double-click a .py file in Finder it executes with the cwd equal to the root directory instead of the directory where the script is located. Trying to fix that I install the "full" MacPython, including Python itself. Doesn't help, scripts still execute in "/". A few weeks later I decide to try to fix that. The plan is to edit whatever.py, the script that's supposed to run before everything else allowing customizations (always takes me a while to find the magic name in the docs - probably you know the name I mean). The plan is to extract the directory I want from sys.argv and then chdir. And here's the mysterious part: The day I plan on modifying whatever.py I find the problem has fixed itself! When I double- click .py files they execute in the right directory. If you asked what I was smoking I wouldn't blame you. (Not that I really think that's it, but the _only_ thing I can imagine I did that could have led to the change was that perhaps I hadn't yet tried out Idle when things were executing in the wrong directory, and somehow the first time I ran Idle it fixed something for me.) Anyway. You have any idea what was going on there, and/or any idea about what to do to fix that problem if it appears again? Something somewhere changed - what, and how do I change it manually? "defaults writ
Re: (MAC) CoreGraphics module???
On Fri, 02 Nov 2007 14:09:25 -0500, Robert Kern <[EMAIL PROTECTED]> wrote: >David C. Ullrich wrote: >> [...] >> >> So CoreGraphics is a builtin in Apple-Python, >> explaining why I didn't find the relevant >> CoreGraphics.py anywhere on the hard drive, eh? > >Okay, which version of OS X do you have? In 10.3 and 10.4 it used to be here: >/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/CoreGraphics.py I'm using 10.4. Yesterday I checked that there is indeed a /System/Library/Frameworks/Python.framework but I didn't look any deeper because I already "knew" that CoreGraphics.py wasn't there. Come to think of it, it could well be that it's there and I didn't find it because Spotlight didn't want to show me things inside /System? I'll check. (I'll check "soon" - again, I'm at home and the Mac's at the office.) >I notice that in 10.5, it no longer exists, though. > >> [How do I get to the Python I want?] > >Python-Python installed a couple of symlinks into /usr/local/bin and then put >/usr/local/bin in the front of your $PATH environment variable so it gets >picked >up first on the terminal. For my Python-Python 2.5, I have > > python > python2.5 > pythonw > pythonw2.5 > python-config > python2.5-config > >Remove these and then when you type "python" at the terminal, you will get >/usr/bin/python, which points to the Apple-Python. Thanks. Right this second I have no idea _where_ I should go to "remove" that, but I can probably find out. It's in .bashrc or somewhere, I bet, No, don't tell me... > >> OR: Is there something special I could do with >> CoreGraphics scripts and/or how I invoke them >> so that _they_ would use the Apple-Python while >> other scripts would just use the Python-Python >> as now? > >For scripts executed from the terminal, you could start them with a hash-bang >line: > > #!/usr/bin/python > >Use "chmod u+x" on the script, and then you can execute it like any other >program from the terminal. Curiously, I did make one of the sample scripts executable and it still didn't work. I _think_ the hash-bang at the start was usr/bin/python (I did verify yesterday that /usr/bin/python is pointing to ApplePython.) Again, don't tell me... >> [ApplicationLauncher mystery] > >I'm afraid I don't. I don't use ApplicationLauncher. Thanks anyway - this has all been very informatiive. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: (MAC) CoreGraphics module???
On Fri, 2 Nov 2007 13:14:16 +0100, Tommy Nordgren <[EMAIL PROTECTED]> wrote: > >On 2 nov 2007, at 02.10, David C. Ullrich wrote: > >> [Why doesn't CoreGraphics work?] >> -- >> http://mail.python.org/mailman/listinfo/python-list > There are Python wrappers for the Cocoa API. These can be used with >binaries from Python.org. >The name of the module is PyObjC, and can be downloaded from >sourceforge. Ah. I'd read about this in the context of using Python in Xcode applications, which seems like something I definitely want to learn how to do, but it was scheduled for "later"... PyObjC will also allow a person to access Cocoa things from an ordinary Python script? If so, keen. Thanks. >There are binary builds for Python up to version 2.4.1. > For Python 2.5.1, it is necessary to build it yourself, which I've >found out requires modifying setup.py. >(The problem is that setup.py tries to use two modules that's not >installed by default on Tiger) >-- >What is a woman that you forsake her, and the hearth fire and the >home acre, >to go with the old grey Widow Maker. --Kipling, harp song of the >Dane women >Tommy Nordgren >[EMAIL PROTECTED] > > David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: (MAC) CoreGraphics module???
On Fri, 02 Nov 2007 14:09:25 -0500, Robert Kern <[EMAIL PROTECTED]> wrote: >David C. Ullrich wrote: >> [???] > >Okay, which version of OS X do you have? In 10.3 and 10.4 it used to be here: >/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/CoreGraphics.py > >I notice that in 10.5, it no longer exists, though. Um, surely that doesn't mean that there's no CoreGraphics available in 10.5? >>[...] > >For scripts executed from the terminal, you could start them with a hash-bang >line: > > #!/usr/bin/python > >Use "chmod u+x" on the script, and then you can execute it like any other >program from the terminal. Sure enough: As I suspected yesterday morning, the reason that didn't work the first time I tried it is that I'd already "corrected" the import statement to Carbon.CoreGraphics. When I put it back the way it's supposed to be everything's great. Such a happy camper - I now have a pdf consisting of a blank white page with one red circle in the middle! Something I've always wanted - thanks. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: (MAC) CoreGraphics module???
On Sun, 04 Nov 2007 15:56:21 -0600, Robert Kern <[EMAIL PROTECTED]> wrote: >David C. Ullrich wrote: >> On Fri, 02 Nov 2007 14:09:25 -0500, Robert Kern >> <[EMAIL PROTECTED]> wrote: >> >>> David C. Ullrich wrote: >>>> [???] >>> Okay, which version of OS X do you have? In 10.3 and 10.4 it used to be >>> here: >>> /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/CoreGraphics.py >>> >>> I notice that in 10.5, it no longer exists, though. >> >> Um, surely that doesn't mean that there's no CoreGraphics >> available in 10.5? > >The CoreGraphics C library still exists, of course. The Python module they >provided does not. Right - I was referring to the Python module. Why would they do such a thing? (Never mind, I don't imagine you know.) Hmm, I saw somewhere the other day that PyObjC comes with 10.5. Maybe that means there's no longer any point to a separate CoreGraphics.py? David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Speaking Text
Mac OS X has text-to-speech built into the interface. So there must be a way to access that from the command line as well - in fact the first thing I tried worked: os.system('say hello') says 'hello'. Is there something similar in Windows and/or Linux? (If it's there in Linux presumably it only works if there happens to be a speech engine available...) David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Speaking Text
On Wed, 19 Mar 2008 07:41:29 -0500, David C. Ullrich <[EMAIL PROTECTED]> wrote: >Mac OS X has text-to-speech built into the interface. >So there must be a way to access that from the command >line as well - in fact the first thing I tried worked: > >os.system('say hello') > >says 'hello'. > >Is there something similar in Windows and/or Linux? >(If it's there in Linux presumably it only works if there >happens to be a speech engine available...) Thanks for the replies. >David C. Ullrich David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with complex numbers
On Sat, 22 Mar 2008 23:29:10 +0100, Christian Heimes <[EMAIL PROTECTED]> wrote: >Matthias Götz schrieb: >> So can you tell me what's the purpose of Complex.py, >> >> and where can i find the semantic i'am looking for. > >Well, the file is in the Demo folder. It's just a demo how to implement >a naive complex type in Python. > >Why do you think the power of a complex to a complex is not defined? >Raising a complex to a complex power is well defined, Really? One of the problems that used to show up on the master's exams aroung here was to find all the possible values of i**i. >although the >mathematical proof isn't trivial. You have to use the Euler form. Erm, the problem is that the Euler form of a complex number is not well-defined (_unless_ you specify that the argument is between -pi and pi). For example, i = exp(i pi/2) and also i = exp(i 5*pi/2); those two "forms" give different values for i**i. You might say that a complex power of an Euler form for a complex number is well-defined. If you do specify that -pi < argument <= pi, ie you consider the principal-value logarithm, then you get exactly one z**w. But that's not always the z**w that you need for your problem... >Ask >Google for some examples Thanks. >Christian David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
In article <[EMAIL PROTECTED]>, Nan <[EMAIL PROTECTED]> wrote: > Hello, >I just started to use Python. I wrote the following code and > expected 'main' would be called. > > def main(): > print "hello" > > main > > But I was wrong. I have to use 'main()' to invoke main. The python > interpreter does not give any warnings for the above code. Is there > any way/tool to easily detect this kind of errors ? It's valid Python - it's only an error because it doesn't do what you want. The reason you're required to include the parentheses with a function call is that in Python there are _other_ things you might want to do with a function other than call it. For example you can pass a function as a parameter to another function. Silly example: def twice(f): f() f() def main(): print 'hello' twice(main) Before trying it, figure out what would happen if you said twice(main()) . A slightly more interesting example: twice(f) simply calls f twice. double(f) returns a new function; when you call that new function it calls f twice: def double(f): def res(): f() f() return res def main(): print 'hello' The point being that this example shows how sometimes you want those parentheses and sometimes you don't. Either one of the following is a way to call main twice: mainmain = double(main) mainmain() or double(main)() When I said mainmain = double(main) I left off the final parentheses because I didn't want to call mainmain just then, I just wanted to set mainmain to the right thing. > Thanks ! -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: default value in __init__
In article <[EMAIL PROTECTED]>, kenneth <[EMAIL PROTECTED]> wrote: > On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote: > > kenneth wrote: > > > the 'd' variable already contains the 'self.d' value of the first > > > instance and not the default argument {}. > > > > > Am I doing some stupid error, or this is a problem ? > > > > No, it always contains the default argument because default values are > > created just ONE > > TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.. > > . > > > Wow, it's a very "dangerous" behavior ... > > Just to know, is this written somewhere in the python documentation or > one has to discover it when his programs fails to work ;-) ? At least once a week someone discovers this "problem", makes a post about it here, and then someone points to the spot in the documentation where it's explained. Seems to me that people often site the "important warning" in the tutorial. Of course there's no reason anyone would bother going through the tutorial - just for fun I looked in the official Python Reference Manual to see whether they're explicit about this or require the reader to figure it out from something else they say. There's a section titled "7.6 Function definitions". About halfway through that section there's a _bold face_ statement "Default parameter values are evaluated when the function definition is executed.", followed by an explanation of how that can lead to the sort of problem above. So I guess it _is_ awfully dangerous. They should really explain this aspect of the language's behavior to people who don't read the formal definition and also don't work through the tutorial. > Paolo -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: default value in __init__
In article <[EMAIL PROTECTED]>, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > David C. Ullrich a écrit : > > In article > > <[EMAIL PROTECTED]>, > > kenneth <[EMAIL PROTECTED]> wrote: > > > >> On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote: > >>> kenneth wrote: > >>>> the 'd' variable already contains the 'self.d' value of the first > >>>> instance and not the default argument {}. > >>>> Am I doing some stupid error, or this is a problem ? > >>> No, it always contains the default argument because default values are > >>> created just ONE > >>> TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects > >>> .. > >>> . > >> > >> Wow, it's a very "dangerous" behavior ... > >> > >> Just to know, is this written somewhere in the python documentation or > >> one has to discover it when his programs fails to work ;-) ? > > > > At least once a week someone discovers this "problem", makes a > > post about it here, and then someone points to the spot in the > > documentation where it's explained. > > > > Seems to me that people often site the "important warning" in > > the tutorial. Of course there's no reason anyone would bother > > going through the tutorial > > Indeed. No reason at all. > > > - just for fun I looked in the > > official Python Reference Manual to see whether they're explicit > > about this or require the reader to figure it out from something > > else they say. > > > > There's a section titled "7.6 Function definitions". About halfway > > through that section there's a _bold face_ statement > > "Default parameter values are evaluated when the function definition is > > executed.", followed by an explanation of how that can lead to > > the sort of problem above. > > But there's no reason to read the reference manual neither. > > > So I guess it _is_ awfully dangerous. They should really explain > > this aspect of the language's behavior to people who don't read > > the formal definition and also don't work through the tutorial. > > You mean : "to people that don't bother reading the FineManual *nor* > searching the newsgroup / ML archives ?" Yes. Also add "don't read any books". I think I started with some book - the book pointed out the "surprise" you get when you say L = [[0]] * 10 L[0][0] = 1 or something similar. I was probably surprised once by the mutable default parameter thing once but having understood that other example it wasn't hard to see what was happening. > Well... How to say.. Is there any chance these people will read anything > *at all* ? No. That's exactly the point! Basic Python is so transparent that you can start using it without reading anything, just looking at a few examples. _Because_ of that it's their responsibility to ensure that if you look at a few examples you then have a complete understanding of the language. In particular default parameters should work the way the user expects! The fact that different users will expect different things here is no excuse... -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Question
In article <[EMAIL PROTECTED]>, "Aditi Meher" <[EMAIL PROTECTED]> wrote: > Hello > > How to write code to store data into buffer using python? buffer = data > Please reply. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: default value in __init__
In article <[EMAIL PROTECTED]>, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > David C. Ullrich a écrit : > > In article <[EMAIL PROTECTED]>, > > Bruno Desthuilliers <[EMAIL PROTECTED]> > > wrote: > > > >> David C. Ullrich a écrit : > (snip) > >>> Seems to me that people often site the "important warning" in > >>> the tutorial. Of course there's no reason anyone would bother > >>> going through the tutorial > >> Indeed. No reason at all. > >> > >>> - just for fun I looked in the > >>> official Python Reference Manual to see whether they're explicit > >>> about this or require the reader to figure it out from something > >>> else they say. > >>> > >>> There's a section titled "7.6 Function definitions". About halfway > >>> through that section there's a _bold face_ statement > >>> "Default parameter values are evaluated when the function definition is > >>> executed.", followed by an explanation of how that can lead to > >>> the sort of problem above. > >> But there's no reason to read the reference manual neither. > >> > >>> So I guess it _is_ awfully dangerous. They > > Hum... Who are "they", exactly ? > > >>> should really explain > >>> this aspect of the language's behavior to people who don't read > >>> the formal definition and also don't work through the tutorial. > >> You mean : "to people that don't bother reading the FineManual *nor* > >> searching the newsgroup / ML archives ?" > > > > Yes. Also add "don't read any books". > > Indeed. > > > I think I started with some > > book > > As far as I'm concerned, I started with the FineManual(tm)'s tutorial. > > (snip) > > >> Well... How to say.. Is there any chance these people will read anything > >> *at all* ? > > > > No. That's exactly the point! > > Yeps. But I don't think we derive the same conclusions from that point. Erm, I think maybe your irony detector needs a little calibration... > > [...] > > > In particular default parameters should work the way the user > > expects! The fact that different users will expect different > > things here is no excuse... I was worried someone might not realize I was being sarcastic, which is why I threw in this obvious impossibility > If different users expect different - mostly incompatible - things, how > would it be possible to have it working "the way the user expect" ? but I guess it wasn't enough. > Should Python grow some telepathic features to guess the user's > expectations and modifies itself to meet these expectations ?-) -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: default value in __init__
In article <[EMAIL PROTECTED]>, Paul McGuire <[EMAIL PROTECTED]> wrote: > On Oct 14, 1:36 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote: > > >[...] > > > In particular default parameters should work the way the user > > expects! The fact that different users will expect different > > things here is no excuse... > > > Are you being sarcastic? Why would you think that? Seems like a perfectly reasonable request. > Short of "import mindreading", I don't know > how Python would know which behavior a given user would expect. I guess that's why I'm not a programmer - not able to think this sort of thing through properly. Thanks. This explains a lot of other things I've wondered about for years, like why I need to tell the waitress whether I want tea or coffee, why I sometimes need to switch channels on my TV... that's always been what I like about c.l.py, getting answers to questions I haven't even asked. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: etymology of "list comprehension"?
In article <[EMAIL PROTECTED]>, Paul Rubin <http://[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] writes: > > Ah, thanks... and does "comprehension" have any special computer > > science meaning? > > It is from mathematical set theory. If you write something like > >{ p | [some logical expression indicating that p is prime] } > > then that denotes a set (the set of all prime numbers). That every > such formula names a set is called the axiom of comprehension. The > above notation is sometimes called set-builder notation. > > Frege's original system of logic (late 19th century), now called > "naive set theory" had "unrestricted comprehension" which meant > you could say anything at all where the logical expression went. > This made the system inconsistent, because of Russell's paradox > ("c is the class of all classes that are not members of themselves. > So is c a member of itself?"). > > Axiomatic set theory has a restricted axiom of comprehension that > requires the logical expression to be a first order formula with > a certain syntax, to avoid such paradoxes. Not that it matters, but the fix is not by using a first-order formula with a certain syntax. The comprehension itself is not {p | p satisfies some condition}, it's {p in S | p satisfies some condition}, where S is some set. You're not allowed to ask for _everything_ satisfying a certain condition, just for the elements of some given set satisfying the condition. The paradox doesn't come from being allowed to say anything at all. If you write (*) c = {x | ~(x e x)} (where ~ means "not" and "a e b" means "a is an element of b") you get Russell's paradox: if c is an element of c then it follows that c is not an element of c, while if c is not an element of c then it follows that c is an element of c. The problem is not with the formula ~(x e x); given a set S, there's no problem with the set {x in S | ~(x e x)}, for example. "restricted" versus "unrestricted" does not refer to some restriction on that formula - the "restriction" in restricted comprehension is the "x in S" part - we're restricting things to elements of a given set S. Writing informally people often omit the "in S" part when the S in clear from the context. For example, your original {p | p is prime} should officially be {p in N | p is prime}, where N is the set of natural numbers - the first form is often written because the "in N" is implicit in "prime". > Anyway, list comprehensions in programming languages got their > name because of their resemblance to set-builder notation that > invoked the axiom of comprehension. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Introducing Python to others
In article , "Paddy O'Loughlin" wrote: Here's my favorite thing about Python (you'd of course remark that it's just a toy example, doing everything in as dumb but easily understood way as possible): x=[1,2] print x+x class Vector(): def __init__(self, data): self.data = data def __repr__(self): return repr(self.data) def __add__(self, other): return Vector([self.data[0]+other.data[0], self.data[1]+other.data[1]]) x = Vector([1,2]) print x+x > Hi, > As our resident python advocate, I've been asked by my team leader to > give a bit of a presentation as an introduction to python to the rest > of our department. > It'll be less than an hour, with time for taking questions at the end. > > There's not going to be a whole lot of structure to it. First, I'm > going to open up a python terminal and show them how the interpreter > works and a few basic syntax things and then a file .py files (got to > show them that python's indenting structure is not something to be > afraid of :P). I think I'll mostly show things in the order that they > appear in the python tutorial (http://docs.python.org/tutorial/). > > My question to you, dear python-list, is what suggestions do you have > for aspects of python that I should show them to make them maybe think > that python is better than what they are using at the moment. > All of the audience will be experienced (4+ years) programmers, almost > all of them are PHP developers (2 others, plus myself, work in C, know > C#, perl, java, etc.). > Because of this, I was thinking of making sure I included exceptions > and handling, the richness of the python library and a pointing out > how many modules there were out there to do almost anything one could > think of. > Anything else you think could make PHP developers starting think that > python is a better choice? > If I were to do a (very) short demonstration one web framework for the > PHP devs, what should I use? CherryPy (seems to be the easiest), > Django (seems to be the "biggest"/most used), or something else? > > Any other suggestions for a possible "wow" reaction from an audience like > that? > > Thanks, > Paddy -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Introducing Python to others
In article <039360fb-a29c-4f43-b6e0-ba97fb598...@z23g2000prd.googlegroups.com>, Mensanator wrote: > On Mar 26, 11:42 am, "andrew cooke" wrote: > > David C. Ullrich wrote: > > > In article , > > > "Paddy O'Loughlin" wrote: > > > > > Here's my favorite thing about Python (you'd of course > > > remark that it's just a toy example, doing everything > > > in as dumb but easily understood way as possible): > > > > > x=[1,2] > > > > > print x+x > > > > > class Vector(): > > > def __init__(self, data): > > > self.data = data > > > def __repr__(self): > > > return repr(self.data) > > > def __add__(self, other): > > > return Vector([self.data[0]+other.data[0], > > > self.data[1]+other.data[1]]) > > > > > x = Vector([1,2]) > > > > > print x+x > > > > that's cute, but if you show them 2.6 or 3 it's even cuter: > > > > >>> from operator import add > > >>> class Vector(list): > > > > ... def __add__(self, other): > > ... return map(add, self, other) > > ...>>> x = Vector([1,2]) > > >>> x+x > > > > [2, 4] > > > > andrew > > Mind if I ask a question? In DU's code, both operands have to > be instances of the Vector class? Yes, in the code I posted. That code was not meant to be an example of the right way to do anything, just an illustration of how wonderful things like __add__ can be. > >>> x = Vector([1,2]) > >>> x+x > [2, 4] > >>> x+[3,3] > > Traceback (most recent call last): > File "", line 1, in > x+[3,3] > File "", line 7, in __add__ > return SV([self.data[0]+other.data[0],self.data[1]+other.data[1]]) > AttributeError: 'list' object has no attribute 'data' > > > Whereas with your version, "other" just has to be an iterable. > > >>> x = Vector([1,2]) > >>> x+x > [2, 4] > >>> x+[3,3] > [4, 5] > >>> x+(9,9) > [10, 11] > >>> x+{3:4,4:9} > [4, 6] > > Although it does require the same number of elements (because that's > required by map and could be changed if necessary). > > >>> x+[3,3,3] > > Traceback (most recent call last): > File "", line 1, in > x+[3,3,3] > File "", line 3, in __add__ > return map(add,self,other) > TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' > > > What would you have to do to make this work? > > >>> x+x+x # expecting [3,6] > [2, 4, 1, 2] -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Introducing Python to others
In article , Scott David Daniels wrote: > Mensanator wrote: > > On Mar 26, 11:42 am, "andrew cooke" wrote: > >> ... > >> that's cute, but if you show them 2.6 or 3 it's even cuter: > >> > >>>>> from operator import add > >>>>> class Vector(list): > >> ... def __add__(self, other): > >> ... return map(add, self, other) > >> ...>>> x = Vector([1,2]) > >>>>> x+x > >> [2, 4] > > > > What would you have to do to make this work? > > > >>>> x+x+x # expecting [3,6] > > [2, 4, 1, 2] > > > > class Vector(list): > def __add__(self, other): > return type(self)(x + y for x, y in zip(self, other)) Question: I would have thought it would be return type(self)([x + y for x, y in zip(self, other)]) What's this thing that looks like a list comprehension but isn't? Comment: I didn't mean to start a big deal, but as long as it's started: Of course returning that list as in Andrew's example is not what we want. Someone said we should return a Vector instead. That's probably what the demo should do, but in stuff like this that I actually _use_ I tend to do something like what you do here (with very different spelling, since type(self) wouldn't work in the bad old days.) The reason of course being that we want subclasses to return instances of the subclass automatically. On the other hand I have this vague feeling that explicitly inspecting the type like this is "wrong" - I've always wondered whether this is the "right" way to do it. ??? > def __sub__(self, other): > return type(self)(x - y for x, y in zip(self, other)) > def __repr__(self): > return '%s(%s)' % ( > type(self).__name__, list.__repr__(self)) > > x = Vector([1,2]) > x + x + x > > --Scott David Daniels > scott.dani...@acm.org -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Introducing Python to others
In article , "andrew cooke" wrote: > David C. Ullrich wrote: > > In article , > > Scott David Daniels wrote: [...] > >> > >> class Vector(list): > >> def __add__(self, other): > >> return type(self)(x + y for x, y in zip(self, other)) > > > > Question: I would have thought it would be > > > > return type(self)([x + y for x, y in zip(self, other)]) > > > > What's this thing that looks like a list comprehension but isn't? > > it's a generator expression. > http://docs.python.org/3.0/reference/expressions.html#index-3735 Ah, thanks. I see "dict comprehensions" there too - keen. Sometime I gotta get around to actually learning this 2.x stuff. Thought I had an idea how 1.x worked... > andrew -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
SoHo Book Problem
Just curious - has anyone else bought the printed Python 3 Reference Manual published by SoHo Books? Talking about what they call "Part 2" of their Python Documentation. I haven't looked in detail - Part 1 seems fine, but the typesetting in Part 2 is totally screwed up. I mean totally - on more or less every page there are lines that are unreadable because there are words printed on top of each other instead of next to each other! On the one hand I don't see how the problem could be with just my copy. On the other hand I don't see how they could _all_ be like mine - that would mean nobody even _glanced_ at what was coming out of the press. So I'm curious whether anyone else has a copy. (I know it's all online. Some people like _books_...) DU. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: SoHo Book Problem
Never mind (at least tentatively). Later in the day I got an email from the publisher, saying they're going to send me a corrected copy "free". Evidently if you get a bad copy you don't have to complain to the publisher or the retailer, you just have to post a complaint somewhere where Google can see it... DU. In article , "David C. Ullrich" wrote: > Just curious - has anyone else bought the printed > Python 3 Reference Manual published by SoHo Books? > > Talking about what they call "Part 2" of their Python > Documentation. I haven't looked in detail - Part 1 > seems fine, but the typesetting in Part 2 is totally > screwed up. > > I mean totally - on more or less every page there are lines > that are unreadable because there are words printed on top > of each other instead of next to each other! > > On the one hand I don't see how the problem could be with > just my copy. On the other hand I don't see how they could > _all_ be like mine - that would mean nobody even _glanced_ > at what was coming out of the press. So I'm curious whether > anyone else has a copy. > > (I know it's all online. Some people like _books_...) > > DU. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython dialog - do something after ShowModal()?
In article <[EMAIL PROTECTED]>, Iain King <[EMAIL PROTECTED]> wrote: > Hi. I have a modal dialog whcih has a "Browse..." button which pops > up a file selector. This all works fine, but the first thing the user > has to do when they open the dialog is select a file, so I would like > the dialog to automatically call the onBrowse function as soon as the > dialog opens. However, I don't know how to do this. > > dlg.ShowModal() > onBrowse() > > obviously doesn't work, and neither does the reverse. I was hoping > that the dialog would throw some kind of "I have been shown" event, > but it doesn't (as far as I can tell). How do I make the dialog do > something as soon as it's been shown? It's too bad that you found an answer. You _shouldn't_ have your dialog pop up a file-selection box as soon as it's shown! That's not the way dialogs usually work, so you're going to confuse people. Instead, first pop up the file-selection box, and then pop up the dialog (without the Browse button) to do whatever else it does after you've got the filename. > Iain -- http://mail.python.org/mailman/listinfo/python-list
sys.excepthack...
Becoming a fan of wxPython, but I can't stand what it does with error messsages (I can't find a way to dismiss that window with the error message from the keyboard. Seems to be anti-modal - the key strokes that normally kill the active window kill the main window (sitting behind the window with the error message) instead. If the window only had an OK button...) So I want to pop up a modal dialog on error. Tried setting sys.stderr to an object with a write method that pops up a dialog. The problem with that is write() gets called several times per exception - I don't see how to get my new sys.stderr object to figure out when it's time to show the message. So then I found sys.excepthook. The problem with that was that I was too stoopid to figure out how to get a readable error message from the parameters passed to excepthook. Came up with a ridiculous hack involving both sys.stderr and sys.excepthook. Works exactly the way I want. Seems ridiculous - what's the right way to do this? Ridiculous_hack.py: import sys import wx def hook(*args): try: sys.__excepthook__(*args) finally: printer.Show() class ErrorDisplay: def __init__(self): self.buffer = '' def write(self, text): self.buffer = self.buffer + text def Show(self): wx.MessageDialog(None, str(self.buffer), 'Error:',wx.OK).ShowModal() self.buffer = '' printer = ErrorDisplay() sys.stderr = printer sys.excepthook = hook -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
"indexed properties"...
Having a hard time phrasing this in the form of a question... The other day I saw a thread where someone asked about overrideable properties and nobody offered the advice that properties are Bad. So maybe we've got over that. I suppose properties could have Bad consequences if a user doesn't know they exist and think that a certain property of an object is just an ordinary attribute. But that applies to almost any aspect of any language. If a person comes from, say, Object Pascal (Delphi) then properties are hard to live without. The other day I decided I wanted what OP calls an "indexed property" or "array property". Couldn't figure out how to make a _property_ behave that way. So I read a little bit about descriptors, and a few minutes later I had an indexedproperty thing that works just like property, except it gives an indexed property! This is just too cool. Why? For example, a Matrix should have a row[n] property allowing things like m.row[0] = m.row[1] + m.row[2] Ok, you could do _that_ by just making row an ordinary list of Row objects. But then you'd have to say m.row[0] = Row([1,2,3]) where I want to be able to say m.row[0] = [1,2,3] and have the Row created automatically. _Also_ with these indexed properties my Matrix can have m.row[j] and m.col[k] that look exactly the same to a client - we don't want to store a list of rows internally and also store the same data in a list of columns. Too cool. Hmm, none of that's a valid excuse for a post here. Um, right, here we go: Anyone see problems or possible improvements with the implementation of indexedproperty below? """indexed.py: "indexedproperty" works more or less like "property" except it gives what in Object Pascal would be an "indexed property". See the __name__="__main__" section below for a demo """ class WriteOnlyIP(Exception): def __str__(self): return """ indexed property is write-only """ class ReadOnlyIP(Exception): def __str__(self): return """ indexed property is read-only """ class indexedproperty(object): def __init__(self, getitem=None, setitem=None): self.getitem = getitem self.setitem = setitem def __get__(self, obj, owner): self.obj = obj return self def __getitem__(self, index): if self.getitem: return self.getitem(self.obj, index) else: raise WriteOnlyIP def __setitem__(self, index, value): if self.setitem: self.setitem(self.obj, index, value) else: raise ReadOnlyIP if __name__ == "__main__": class AClass(object): def __init__(self): self.cells = [[0,0], [0,0]] def SetCell(self, (row, col), value): self.cells[row][col] = value def GetCell(self, (row, col)): return self.cells[row][col] cell = indexedproperty(GetCell, SetCell) C = AClass() for row in range(2): for col in range(2): C.cell[row, col] = "row: %s, col: %s" % (row, col) for row in range(2): for col in range(2): print C.cell[row, col] C.cell[0,0], C.cell[1,1] = C.cell[1,1], C.cell[0,0] print "After C.cell[0,0], C.cell[1,1] = C.cell[1,1], C.cell[0,0]:" for row in range(2): for col in range(2): print C.cell[row, col] -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.excepthack...
In article <[EMAIL PROTECTED]>, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: > On Wed, 14 May 2008 15:47:18 -0500, "David C. Ullrich" <[EMAIL PROTECTED]> > wrote: > > [snip] > > > >Came up with a ridiculous hack involving both sys.stderr > >and sys.excepthook. Works exactly the way I want. > >Seems ridiculous - what's the right way to do this? > > > > [snip] > > Hi David, > > Take a look at the traceback module. The excepthook gets called with > an exception type, instance, and traceback object. The traceback module > is good at turning these things into strings. Thanks. > Jean-Paul -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: "indexed properties"...
On Thu, 15 May 2008 10:59:41 -0300, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: >En Wed, 14 May 2008 18:15:41 -0300, David C. Ullrich <[EMAIL PROTECTED]> >escribió: > >> Having a hard time phrasing this in the form >> of a question... >> >> The other day I saw a thread where someone asked >> about overrideable properties and nobody offered >> the advice that properties are Bad. So maybe we've >> got over that. I suppose properties could have >> Bad consequences if a user doesn't know they exist >> and think that a certain property of an object is >> just an ordinary attribute. But that applies to >> almost any aspect of any language. > >Which "bad consequences" are you thinking of? Didn't have anything specific in mind - there I was just playing devil's advocate. I've seen a lot of people here say things like "properties should only be used when refactoring" without any explanation that I could see of why properties were bad things. I was referring to whatever problems they had in mind. >Apart from the user not being aware of the complexity of certain operations, >or a getter/setter very time-consuming (in that case I'd use public >getXXX/setXXX functions instead, to emphasize that "something" is happening, >not just an attribute lookup) > >> If a person comes from, say, Object Pascal (Delphi) >> then properties are hard to live without. The > >You should read the article "Python is not Java" if you haven't done it yet. >http://dirtsimple.org/2004/12/python-is-not-java.html I suspect you misunderstood my point there. I actually read that article years ago. Been using Python for years. I'd never confuse it with OP, I promise (luckily I don't know any Java and don't intend to). I really didn't express what I meant very well - what I should have said was more like "If you're accustomed to properties from a language like OP they seem like a very useful addition to Python". Looking at the article it seems like two points are relevant. (i) I'm well aware that chains of attribute accesses don't get compiled away in Python the way they do in OP. (ii) Regarding the bit about how getters and setters are evil, and it's also bad to wrap things in properties when simple attributes would do. Yes. Thanks for pointing that out, but I wouldn't do that - using a property where a simple attribute would do would be stupid. But they _can_ be much nicer than having to use explicit getters and setters, in cases where a simple attribute won't do. I got started on this thinking about making myself a nicer interface (nicer-seeming to me) to the wxPython grid object. Being able to say grid[row, col] = value seems much nicer and more natural than grid.SetCellValue(row, col, value) (yes, _that_ one is just __get(set)item__, no property needed), just as window.pos = (x,y) seems more natural than window.SetPos(x,y); in these cases the work involved in changing the cell value or the window position is going to make the extra overhead of the property interface irrelevant. >> other day I decided I wanted what OP calls an >> "indexed property" or "array property". Couldn't >> figure out how to make a _property_ behave that way. >> So I read a little bit about descriptors, and a >> few minutes later I had an indexedproperty thing >> that works just like property, except it gives >> an indexed property! This is just too cool. >> >> Why? For example, a Matrix should have a row[n] >> property allowing things like >> >> m.row[0] = m.row[1] + m.row[2] >> >> Ok, you could do _that_ by just making row >> an ordinary list of Row objects. But then >> you'd have to say >> >> m.row[0] = Row([1,2,3]) >> >> where I want to be able to say >> >> m.row[0] = [1,2,3] >> >> and have the Row created automatically. > >One could make *row* an object with a custom __getitem__/__setitem__ in this >case. But then [see below] >But I prefer to have as little magic as possible on my objects: if it says >m.row[0] = [1,2,3] I >expect m.row[0] to actually *be* that list (whenever possible), and not any >other object initialized >from the [1,2,3] arguments. (Maybe this is some overreaction against C++ >"magic" constructors and such horrible things...) Whatever - the idea here is that m.row[0] is going to walk and quack exactly like that list would, but also do other things that the liist can't do, like you can add two of them. (When you say anobject.aproperty = 2 you also expect aproperty to be 2? But if aproperty is a property that's not n
Re: "indexed properties"...
On Sat, 17 May 2008 00:27:31 -0300, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: >(warning: it's a rather long message) > >En Fri, 16 May 2008 12:58:46 -0300, David C. Ullrich ><[EMAIL PROTECTED]> escribió: >> On Thu, 15 May 2008 10:59:41 -0300, "Gabriel Genellina" >> <[EMAIL PROTECTED]> wrote: >>> En Wed, 14 May 2008 18:15:41 -0300, David C. Ullrich >>> <[EMAIL PROTECTED]> escribió: >>> >>>> The other day I saw a thread where someone asked >>>> about overrideable properties and nobody offered >>>> the advice that properties are Bad. So maybe we've >>>> got over that. I suppose properties could have >>>> Bad consequences if a user doesn't know they exist >>>> and think that a certain property of an object is >>>> just an ordinary attribute. But that applies to >>>> almost any aspect of any language. >>> >>> Which "bad consequences" are you thinking of? >> >> Didn't have anything specific in mind - there I was >> just playing devil's advocate. I've seen a lot of people >> here say things like "properties should only be used >> when refactoring" without any explanation that I could >> see of why properties were bad things. I was referring >> to whatever problems they had in mind. > >I suppose those people were talking about this usage: > > def getfoo(self): return self._foo > def setfoo(self, value): self._foo = value > foo = property(getfoo, setfoo) Yeah. _If_ that's what I had in mind then telling me Python is not Java would have been a great service. If I recall correctly (maybe not, haven't done any OP in a long time) this is one of many things that OP gets righter than Java: you can have the "read" or "write" for a property refer to a method _or_ to an actual field; in the second case access compiles to the same thing as in direct field access. >Just use a plain foo attribute instead. Almost nobody will notice the >difference, and it's faster, easier to maintain, easier to test, less >magic... But if you *do* have more to do besides handling the _foo >attribute, using a property is OK, at least for me. And from your other >comments, I can see it's fine for you too. > >>>> If a person comes from, say, Object Pascal (Delphi) >>>> then properties are hard to live without. The >>> >>> You should read the article "Python is not Java" if you haven't done it >>> yet. >>> http://dirtsimple.org/2004/12/python-is-not-java.html >> >> I suspect you misunderstood my point there. I actually read that >> article years ago. Been using Python for years. I'd never confuse >> it with OP, I promise (luckily I don't know any Java and don't >> intend to). I really didn't express what I meant very well - what >> I should have said was more like "If you're accustomed to properties >> from a language like OP they seem like a very useful addition to >> Python". > >Oh, sure. I missed them a lot until they became available in Python. And I >even wrote a fake property mixin class for Python 2.1 (horrible and slow!). >Now I understand better what you're saying. > >> window.pos = (x,y) >> >> seems more natural than >> >> window.SetPos(x,y); >> >> in these cases the work involved in changing the cell >> value or the window position is going to make the >> extra overhead of the property interface irrelevant. > >Sure, that looks like a good candidate for using a property. > >>> But I prefer to have as little magic as possible on my objects: if it >>> says m.row[0] = [1,2,3] I >>> expect m.row[0] to actually *be* that list (whenever possible), and not >>> any other object initialized >>> from the [1,2,3] arguments. (Maybe this is some overreaction against >>> C++ "magic" constructors and such horrible things...) >> >> Whatever - the idea here is that m.row[0] is going to walk and quack >> exactly like that list would, but also do other things that the liist >> can't do, like you can add two of them. >> >> (When you say anobject.aproperty = 2 you also expect aproperty to >> be 2? But if aproperty is a property that's not necessarily so - this >> seems like as much an argument against properties in general as >> against my version. Or perversion, if you like.) > >No, I don't necesarily expect it, but I try to maintain that behavior as >long as I c
Re: "indexed properties"...
On Sun, 18 May 2008 08:50:23 +0200, pataphor <[EMAIL PROTECTED]> wrote: >In article <[EMAIL PROTECTED]>, >[EMAIL PROTECTED] says... > >> >> window.pos = (x,y) >> >> >> >> seems more natural than >> >> >> >> window.SetPos(x,y); > >Yes, and to assign a row in a matrix I'd also like to use either tuples >or lists on the right side. Heh - in the current (flawed) implementation you can say m.row[0] = 'Hello'; m.row[1]= 'World!' .Not that I see why you'd want to, but that happened in the test code just to check that things were as general as I wanted - sure enough m.row[0] + m.row[1] comes out to ['HW', 'eo', 'lr', ''ld', 'o!']. >> def __add__(self, other): >> return Row([x + y for x, y in zip(self, other)]) >> >> worked as hoped if self is a Row and other is a >> Row _or_ a list.) >> >> Anyway, my m.rows[j] can't be a list, because >> I want to be able to say things like >> m.rows[0] += c*m.rows[2]. Allowing >> m.rows[j] = [1,2,3] seems convenient, while >> requiring m.rows[j] = Row([1,2,3]) fixes >> this problem. Hmm. > >I'm not sure how far you'd go along with Gabriel's idea of decoupling >views from data but I think there isn't even a need for using a matrix >as the underlying data type. Why not use a flat list and compute matrix >positions according to a row or column adressing scheme on the fly? Is there some reason that would be better? It would make a lot of the code more complicated. Ok, it would require only one bit of added code, I suppose, but I don't see the plus side. Hmm. It might actually _reduce_ the total amount of code, since the code to access columns has to exist anyway and rows could use the same code as columns with different "start" and "skip". And come to think of it rows and columns could be obtained just with a slice of the data. So column access might even be more efficient. But I expect that row access will happen a lot more often than column access. >P. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
On Sat, 17 May 2008 15:32:29 -0700 (PDT), Vicent Giner <[EMAIL PROTECTED]> wrote: >Hello. > >I am new to Python. It seems a very interesting language to me. Its >simplicity is very attractive. > >However, it is usually said that Python is not a compiled but >interpreted programming language I mean, it is not like C, in that >sense. > >I am working on my PhD Thesis, which is about Operations Research, >heuristic algorithms, etc., and I am considering the possibility of >programming all my algorithms in Python. Other people have said things about how to use Python effieiently. Something that seems relevant that I don't see mentioned: Are you going to be doing research _about_ the algorithms in question or is it going to be research _using_ these algorithms to draw conclusions about other things? Most of the replies seem to be assuming the latter. If it's the former then Python seems like definitely an excellent choice - when you have want to try something new it will be much faster trying it out in Python, when you write up the results there will be no need for pseudo-code as a guide to the real code because the Python will be just about as easy to read as the pseudo code would be, etc. >The usual alternative is C, but I like Python more. > >The main drawbacks I see to using Python are these: > >* As far as I understand, the fact that Python is not a compiled >language makes it slower than C, when performing huge amounts of >computations within an algorithm or program. > >* I don't know how likely it is to find libraries in Python related to >my research field. > >* I know Python is a "serious" and mature programming language, of >course. But I do not know if it is seen as "just funny" in a research >context. Is Python considered as a good programming language for >implementing Operations Research algorithms, such as heuristics and >other soft-computing algorithms? > >Maybe this is not the right forum, but maybe you can give me some >hints or tips... > >Thank you in advance. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: "indexed properties"...
On Sun, 18 May 2008 18:18:34 +0200, pataphor <[EMAIL PROTECTED]> wrote: >In article <[EMAIL PROTECTED]>, >[EMAIL PROTECTED] says... > >> Is there some reason that would be better? It would make a lot >> of the code more complicated. Ok, it would require only one >> bit of added code, I suppose, but I don't see the plus side. > >The plus side is you give up an untenable position :-) Maybe you could be more specific? Various "positions" I've taken in all this may well be untenable, but I can't think of any that have anything to do with whether the data should be a single list instead of a list of lists. (The only way I can parse this to make it relevant is to assume that the position you're referring to is that a list of lists is better than a single list. If so: First, I haven't said that it was. Second, saying "B is untenable" is not much of an answer when someone asks why you say A is better than B.) >And to address an >item in a matrix costs two lookups, row and column, while an array needs >only one. The phrase "premature optimization" springs to mind. This is _Python_ we're talking about. Supposing you're right that doing two lookups _in Python_ is faster than doing one lookup plus the calculuation col + row*width _in Python_, it can't make enough difference to matter. In the sort of application I have in mind things already happen "instantaneously". The point is not to improve on NumPy. Trying to improve on NumPy in pure Python code would be silly - if I wanted optimized large matrices I'd _use_ NumPy. The point is just to give a simple "intuitive" way to manipulate rows and columns in small matrices. So I'm not looking ahead to the future, things are not scalable? The thing is not _supposed_ to scale up to large matricies. If a person were dealing with large matricies then almost all of it would need to be rewritten (and if a person were dealing with really large matrices then trying to do the thing in pure Python would be silly in the first place, and insisting on being able to write things like "m.row[0] = m.row[1] + m.row[2]" could very well be a totally wrong approach to begin with - I'd figure out the operations I expected to need to do and write functions to do them.) Really. In one of the intended applications the matrix entries are going to be home-made Rationals. Just adding two of those guys takes a long time. It's still more than fast enough for the intended application, but [oh, never mind. Sorry about the argumentative tone - I _would_ like to know which "untenable position" you're referring to... >P. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: python script to windows exe
ter encoding is ascii or smthing >else >def checkStringType(a): > >if isinstance(a,str): > b='not a unicode string' > >else: >a.encode('utf-8') >#print 'unicode type' > >return a > >#function to save the coopy of an email >#:-( but smhow it generate error whenever i make a call to it >def saveCopy(mailItem): > >name="\\"+mailItem.Subject+"__"+str(mailItem.ReceivedTime) >print name >#global outlook_app >try: >mailItem.SaveAs(path+name+".txt",OlSaveAsType['olTXT']) >except BaseException: >print BaseException > >def getHTMLString(b): >a='Your Email Data log is herehead>'+b+'' >return a > >#main entrance to the program >def main(): >global outlook_app,inbox_obj >outlook_app=getAppRef() >#print outlook_app.OlSaveAsType.olMSG >print '==' >print dir(outlook_app) >print '==' >inbox_obj=getOutLookFolders(outlook_app) >print dir(inbox_obj) >print (inbox_obj.Items) >#saveCopy(inbox_obj.Items[1]) >getMailContent(inbox_obj) > > > >main() > > >my setup file has this code > >from distutils.core import setup >import py2exe > >setup(console=['outlook.py']) > > >i have just copied and pasted it from the tutorial available at the >py2exe site and changed the filename with mine filename. > > >thanks and regards >sandeep kumar sharma > >> There is nothing special in executables produced by py2exe. I mean >> that the debugging strategy is as always. A good start might be in >> adding logging\tracing facilities both to script and the executable. >> Comparing two trace files could give you some clue. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
On Sun, 18 May 2008 18:20:22 -0400, John Salerno <[EMAIL PROTECTED]> wrote: >Hey all. Just thought I'd ask a general question for my own interest. Every >time I think of something I might do in Python, it usually involves creating a >GUI interface, so I was wondering what kind of work you all do with Python >that does *not* involve any GUI work. This could be any little scripts you >write for your own benefit, or what you do at work, if you feel like talking >about that! :) You might get a keyboard with an Enter key, btw. Anyway: I'm a math professor, not a programmer. I use Python probably every day to do all sorts of things, for example: (i) Calculating grades. (Ok, this could be done in Excel. But if you know Python anyway you don't need to figure out how to do various things in Excel. Quick: In Excel how do you take all the quiz scores, drop the lowest _two_ of them and average the rest? Stumps people sometimes - if you're doing it by hand in Python it's no problem, you just do it.) (ii) Every semester I get a lot of emails asking about grades. Used to be tedious typing the same replies over and over, looking up the relevant numbers. A littls Python script takes the student's name, looks up the numbers and generates a reply automatically, including a summary of the scores and an explanation of how the grade was calculated.) (iii) Taking various data from various places and making it into HTML to post on the department web site. (Please don't look - a lot of that stuff is currently broken due to improvements on the server introduced by other faculty. These things happen when nobody's in charge so things get done by whoever's willing to do them...) (iv) Say I want to display the following system of equations on a quiz: 3x + 2y + z = 3 x - z = 1. Writing TeX to get the variables to line up properly can be tedious. A little Python thingie takes lists of variable names and coefficients and automatically produces TeX that displays the equations exactly right. I could go on and on - I use computers for a lot of things, and any time I want to do something but it's not obvious how to do it in the relevant big program Python gets pulled out to do the job. A meta-example: I'm about to publish a book on [never mind, the topic is still secret.] Python has been incredibly useful in writing that book, in many different ways. For example: (v) Making modifications to the text itself. For example, the other day I finally figured out how to make a certain aspect of the thing look right. So I wanted to replace every "$$[w]\qed" in the text (where [w] denotes any amount of white space) with "\QED$$". Took about a minute to make a Python script to go through the entire book and make the change. (vi) There are a lot of figures. Some fairly complicated, illustrating fairly complicated mathematical things. The figures are eps files that were generated by Python scripts. The simple ones could just have easily been done in Adobe Illustrator or Corel Whatever, but there's no way you're going to use a mouse-based program like that to draw the complicated figures and have everything in exactly the right place. I have Python do the calculations and then write the corresponding eps file, done. (vii) Many magical things were done with a combination of TeX macros and Python scripts. For example, index entries: If I say \index{Some Theorem} in the text and it turns out that that's on page 37 then "Some Theorem p.37" appears in the index; now if something gets revised so the \index{Some Theorem} is now on page 38 then the index entry is automatically revised to page 38. Or: The first page of Chapter n+1 is supposed to be the smallest odd number larger than the last page of Chapter n. A Python script typesets ("texs") each chapter; after typesetting Chapter n it looks and sees what the last page is, figures out what the first page of Chapter n+1 should be, and modifies the code for Chapter n+1 to start on the page before typesetting it. If I wrote this tomorrow the list of examples would be different. Just now over on comp.text.tex I showed someone a Python solution to a problem he had. I don't know if he's going to use it - he _would_ need to learn a _little_ Python first. But it's what I'd use if _I_ wanted to solve the problem! Other people suggested various programs available that would solve his problem for him - writing a little Python to give the solution took less time than downloading one of those programs would have. >Thanks. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: "indexed properties"...
On Mon, 19 May 2008 14:48:03 +0200, pataphor <[EMAIL PROTECTED]> wrote: >On Mon, 19 May 2008 06:29:18 -0500 >David C. Ullrich <[EMAIL PROTECTED]> wrote: > >> Maybe you could be more specific? Various "positions" I've >> taken in all this may well be untenable, but I can't think >> of any that have anything to do with whether the data should >> be a single list instead of a list of lists. > >What's 'untenable' (hey, I tried to get away with a smiley, remember) Perhaps I should say that I was in no mood for smileys yesterday morning: I hadn't eaten in 24 hours, hadn't had any water in 12 hours, and was anticipating an unpleasane instance of what my doctor likes to call a "procedure" coming up in a few hours. (Yes, everything went fine, thanks for asking - today all is sweetness and light again.) >is that a matrix is a list of rows. Suppose you do the transpose trick >with the zip(*M) routine, now it's a list of columns. Both views are >equal, there is no getting around the fact that you're holding an >unnatural predisposition towards seeing the matrix as a list of rows, >which it is most definitely not ... Well, ok. Like I said, I never _took_ the position that it _should_ be a list of lists, I just said I didn't see the advantage to using a single list. Yes, the asummetry in my setup might be regarded as an aesthetic flaw. But that doesn't mean it doesn't work right, and in any case _I_ regard it as a _feature_: rows and columns look the same to the user even though they're very different under the hood. Although they're going to look the same, in the applications I have in mind I expect that row operations will be more frequent than column operations, so if we _were_ going to worry about optimizing things optimizing row access might be reasonable. >I was holding the brakes for this argument because I realize it's >intuitive and also because Gabriel seems to want a list stay a list if >he assigns something a list. But that's untenable too. Suppose you >assign a column to a list? The list is torn to shreds and placed over >multiple rows. His desire here makes a lot more sense to me than it seemed to at first, when he pointed out the problems with "arow = m.row[0] = []". But this is a good point; if we have rows _and_ columns then it seems like he really can't have it his way. Today's little joke: Long ago I would have solved this by storing the data as a list of rows and _also_ a list of columns, updating each one any time the other changed. Just goes to show you things could always be worse... >> (The only way I can parse this to make it relevant is to >> assume that the position you're referring to is that a >> list of lists is better than a single list. If so: First, I >> haven't said that it was. Second, saying "B is untenable" >> is not much of an answer when someone asks why you >> say A is better than B.) > >Yes, it was not much of an answer but I was afraid of ending up in >this quagmire. I now see that it is unavoidable anyway if I want to >explain myself. Why couldn't you just see it the same way as me and >leave it at that without waking up all the creatures of hell :-) Sorry. >> >And to address an >> >item in a matrix costs two lookups, row and column, while an array >> >needs only one. >> >> The phrase "premature optimization" springs to mind. > >Well, I really liked your slicing idea ... > >> This is _Python_ we're talking about. Supposing you're right that >> doing two lookups _in Python_ is faster than doing one lookup >> plus the calculuation col + row*width _in Python_, it can't >> make enough difference to matter. In the sort of application I >> have in mind things already happen "instantaneously". > >The computation is almost certainly faster. Lookups are expensive. I know one thing about Python: I don't know exactly how it works, and hence it's very difficult to be certain about such things without actually testing them. Which is not to say you're not right. >However I concede the point because we're not supposed to worry about >such stuff. But it *is* a simpler format. No wait, I know _two_ things about Python: (i) [repeat above] (ii) we're supposed to worry about such things _after_ determining that this particular such thing is actually the bottleneck. It seems incredibly unlikely that this detail is going to have any significance at all in the final product. >> The point is not to improve on NumPy. Trying to improve on >> NumPy in pure Python code would be silly - if I wanted >> optimized large matrices I'd _us
Re: "indexed properties"...
In article <[EMAIL PROTECTED]>, pataphor <[EMAIL PROTECTED]> wrote: > On Tue, 20 May 2008 06:12:01 -0500 > David C. Ullrich <[EMAIL PROTECTED]> wrote: > > > Well, ok. Like I said, I never _took_ the position that it _should_ > > be a list of lists, I just said I didn't see the advantage to using > > a single list. > > I'm now thinking about a list of lists containing single element lists. > > def test(): > n = 3 > R = range(n) > M = [[[i+j*n] for i in R] for j in R] > for L in M: > print L > row2 = M[1] > print > print row2 > col3 = [L[2] for L in M] > print col3 > col3[1][0]=9 > > print col3 > print row2 > print > for L in M: > print L > > if __name__=='__main__': > test() > > The idea is to use a single element list as kind of storage facility. > That enables me to copy a column, then change something in that column > and make the change turn up in the matrix and even in a previously made > copy of a row that shared the specific element. > > > Today's little joke: Long ago I would have solved > > this by storing the data as a list of rows and _also_ > > a list of columns, updating each one any time the > > other changed. Just goes to show you things > > could always be worse... > > Well have I ever ... I only thought about this last week and I > actually thought it was a *good* idea. Sorry. If you really want to do this you could keep things in sync automatically by writing the appropriate __setitem__ and resolving never to modify the data except through that... def whatever.__setitem__(self, (row,col), value): self.rows[row][col] = value self.cols[col][row] = value Seems to me like an, um, "untenable" waste of space. And you'd need to be certain to never set anything except through self[row,col]; as far as I can see anything like setrow() would be a loop "for col in range(width): self[row,col] =". Hmm. You could keep the data in some object that encapsulates the two double lists and use some fancy feature (__getattribute__?) to make certain that the only possible access to the data was through __getitem__... > I only gave up on it because > now I would have to keep track of how far the two views are out of > sync, because some operation could use data that was modified by an > other view. Zipstar transposition is very handy for syncing, but it is > also very expensive. But probably not for you. > > > Expressing interest is a big mistake... > > How so? ;-) > > > Sometime soon a thread will appear titled something > > like "indexed attributes" with a stripped-down but > > functional example of what I have in mind for Matrix > > I can't wait! Keep up the good work. > > P. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: "indexed properties"...
On Wed, 21 May 2008 12:47:44 +0200, pataphor <[EMAIL PROTECTED]> wrote: >On Tue, 20 May 2008 10:40:17 -0500 >"David C. Ullrich" <[EMAIL PROTECTED]> wrote: > >> > > Today's little joke: Long ago I would have solved >> > > this by storing the data as a list of rows and _also_ >> > > a list of columns, updating each one any time the >> > > other changed. Just goes to show you things >> > > could always be worse... >> > >> > Well have I ever ... I only thought about this last week and I >> > actually thought it was a *good* idea. >> >> Sorry. If you really want to do this you could keep things >> in sync automatically by writing the appropriate __setitem__ >> and resolving never to modify the data except through that... >> >> def whatever.__setitem__(self, (row,col), value): >> self.rows[row][col] = value >> self.cols[col][row] = value > >Using the trick of encapsulating the values inside single-element lists >one can make a transposition of the matrix and get synchronicity for >the little price of doubling the number of instances. Since the views >share the data this is a lot less expensive than one would think. One >can use the row view or the column view to alter data and the changes >will automatically be visible in the other view, since the views update >the same lists. Oh - that's different. This is not what I thought you had in mind (it's not what I had in mind in the thing I called a joke.) >There is a little notational gotcha, instead of writing >row[0] = [1,2,3] one now must write row[0][:] = [1,2,3] or else >synchronicity is lost. > >I found a nice ListMixin class at >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440656 > >Using that I wrote the following proof of concept: > >class Storage(ListMixin): > > def __init__(self, seq=[]): >self.L = [[x] for x in seq] > > def _constructor(self, iterable): >return Storage(iterable) Probably I'm just being dense. Why does _constructor exist? (Oh - looking at things below, I imagine it's something to do with ListMixin.) > def __len__(self): >return len(self.L) > > def _get_element(self, i): >assert 0 <= i < len(self) >return self.L[i][0] > > def _set_element(self, i, x): >assert 0 <= i < len(self) >self.L[i][0] = x > > def _resize_region(self, start, end, new_size): >assert 0 <= start <= len(self) >assert 0 <= end <= len(self) >assert start <= end >self.L[start:end] = [[None] for i in range(new_size)] > >def test(): >n = 3 >R = range(n) >it = iter(range(n*n)) >MR = [Storage(it.next() for i in R) for i in R] >MC = [Storage() for i in R] >T = zip(*[x.L for x in MR]) >for x,y in zip(MC,T): >x.L = y >print MR >print MC >MC[2][:] = 'abc' >print >print MR >print MC > >if __name__=='__main__': >test() > >Output: > >[Storage([0, 1, 2]), Storage([3, 4, 5]), Storage([6, 7, 8])] >[Storage([0, 3, 6]), Storage([1, 4, 7]), Storage([2, 5, 8])] > >[Storage([0, 1, 'a']), Storage([3, 4, 'b']), Storage([6, 7, 'c'])] >[Storage([0, 3, 6]), Storage([1, 4, 7]), Storage(['a', 'b', 'c'])] > >P. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Relationship between GUI and logic?
On Fri, 23 May 2008 09:13:50 -0400, "John Salerno" <[EMAIL PROTECTED]> wrote: >"Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in >message news:[EMAIL PROTECTED] >> Ever heard of the "Model/View/Controller" pattern ? > >Yes, I have, but I probably don't understand it well enough yet. For >example, I don't really know what is meant by phrases like "build a model", >"the view registers itself with the model", "interations are sent to the >appropriate controller" -- I may understand them literally, but I get the >feeling that the implementation of these ideas are beyond me. I doubt that. I've done things like this. I ended up with just a Model and a View, no Controller. I assumed that meant I was being Bad - I read once that that often happens, specifically with GUI programs. An example, certainly not meant to be definitive, maybe not even right, probably not "right", but illustrating explicitly what those terms you claim not to understand might mean in an implementation: class Model: """Encapsulates an abstract version of the game: Knows nothing about how the players make moves, the moves are reported to the model via the ProcessMove method. Knows nothing about how the state of the game is displayed to the players; that's handled by the view or views. The model might contain a matrix, where the entry in each cell is None or a certain Piece object. The model knows that if a certain Cell contains a King then it's legal to move that King to this Cell but not to that Cell - that's part of the rules of the game, something the View knows nothing about""" def __init__(self): #set up internal state, for example #self.board = [[None]*8]*8 #and then self.board[0,4] = Queen[WhitePlayer], #etc. Whatever... self.views = [] #or just self.view = None if there's #no reason for multiple views. When I did #something like this once I decided at the #end that I should have allowed multiple #views even though there was only one to start, #because functionality that got added to the view #could have been done more cleanly by creating #a second view (one view being the display and #another being spoken messages) def RegisterView(self, view): self.views.append(view) #or just self.view = view def UpdateViews(self): for view in self.views: view.UpdateDisplay(self) #or UpdateView(self): if self.view: self.view.UpdateDisplay(self) def ProcessMove(self, move): """Model recieves "messages" from View here.""" #modify internal state depending on the #information passed in "move", #for example move might say that the Piece in #a certain Cell was dragged to another Cell. #Here in ProcessMove you decide whether that's #a legal move, and if so what effect it should #have on the state of the game. Update state, then self.UpdateViews() #or there could be more than one "Process" method #if there are various different sorts of things the #players might do class Square: def __init__(self, row, col): self.row = row self.col = col #say a move is a drag from one square to another: class Move: def __init__(self, start, end) self.start = start self.end = end #wrote that out explicitly just to emphasize that #the Move object, which the View passes to the #Model as a message, doesn't know anything #about the details of the display and also doesn't #know anything about the rules of the game... class View: def __init__(self, game): #set up the wxPython stuff self.game = game self.game.RegisterView(self) Bind(self, VariousEvents, VariousHandlers) def VariousHandlers(self, evt) #figure out what the players just did based #on evt. Maybe a player has just dragged a piece #from one square to another. figure out the row #and col of the start and end squares from #information in evt. #Now tell the Model what just happened: self.game.ProcessMove(Move(Square(row1, col1),Square(row2, col2))) def UpdateDisplay(self): #look at self.game to figure out what pieces #go where, then draw them on the screen. wx.This wx.That game = Model() view = View(game) >I think it's >mainly an issue of terminology, so probably I should just read up on MVC. > >> The user interface doesn't need to be graphical. There were games and >> emails clients and text editors before GUIs existed, you know ? > >Of course, but I'm specifically asking about creating a program that has a >GUI, and even more specifically it would be wxPython. > David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Fri, 23 May 2008 14:00:33 -0700 (PDT), "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: >On 23 mai, 10:42, "inhahe" <[EMAIL PROTECTED]> wrote: >> "Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in >> messagenews:[EMAIL PROTECTED] >> >> > Brad a écrit : >> >> cm_gui wrote: >> >>> Python is slow. >> >> >> It ain't C++, but it ain't a punch card either... somewhere in between. I >> >> find it suitable for lots of stuff. I use C++ when performance really >> >> matters tho... right tool for the job. Learn a good interpreted language >> >> (Pyhton) and a good compiled language (C or C++) >> >> > LordHaveMercy(tm). Could you guys please learn what you're talking about? >> >> > 1/ being interpreted or compiled (for whatever definition of these >> > terms) is not a property of a language, but a property of an >> > implementation of a language. >> >> That's like saying being spherical is not a property of planets, it's a >> property of an instanciation of a planet. > >I do definitively not have the required knowledge to say anything >about "being spherical" being part of the definition of what a >"planet" is or not. I wasn't going to mention this since it's really not relevant, but since you raise the question: Actually it was a bad analogy because being roughly spherical _is_ part of the definition of "planet". (Of course "spherical" must mean "roughly spherical" here, since no planet is exactly spherical.) A little while ago when Pluto got demoted so it's no longer officially a planet they came up with a definition - part of the definition is that the body is large enough that gravity causes it to assume a spherical shape. >>, and b) It's a far cry to >> imagine a planet coming into being that's not spherical > >Idem > >> (a language as >> dynamic as Python, or most other scripting languages, would be either >> extremely difficult or impossible to make a native compiler for). > >Now this I can tell is false. The problem is not that it's difficult >to "make a native compiler for" dynamic languages, the problem is that >it's difficult to write native compiler for dynamic languages that >generates code that beats the VM/byte-code interpreter/whatever you >name it to be wotrh the effort. > >> I guess I >> should also mention that Python isn't very practical (as in "suitable", >> "right tool for the job", and "perfomance", as mentioned in the above post) >> without an implementation. > >That is debatable. There are algorithm courses taught in "pseudo-code" >- that is, a language that doesn't have any known implementation. > >> So I don't think this distinction has any use >> other than to beat other people over the head with a bat. > >Ok, *you* know this - I mean, the distinction between a language and a >language's implementation(s). Are you sure everyone saying - or >reading - assertions such as "language XXX is slow" or "compiled >languages are faster" etc really know what they're talking about ? > >> > 2/ actually, all known Python implementations compile to byte-code. >> >> Which is then interpreted, but you're still technically right, because >> "compiled" can mean either compiled to bytecode or compiled to native code, >> despite what it actually did mean. Semantics FTW!! > >Yes, semantics. But a bit more than semantics - byte-code interpreters >are usually way faster than "pure" interpreter, and start to be fast >enough for quite a lot of practical use. > >Ok, I'll stop on this - once again, sorry for the noise, and please >bear with me, I tend to be a bit too much on the pedantic side >sometimes. But still, thanks to the pedantics peoples on usenet that >taught me so much so far and still teach me more and more... David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Relationship between GUI and logic?
On 23 May 2008 18:23:04 +0100 (BST), Matthew Woodcraft <[EMAIL PROTECTED]> wrote: >John Salerno <[EMAIL PROTECTED]> wrote: >> Basically, the question is this: can you write the logic behind a >> program (whether it be a game, an email client, a text editor, etc.) >> without having any idea of how you will implement the GUI? > >You probably could, but it's best not to unless you're somehow forced >to. > >In practice, the interface that you want your 'logic' layer to provide >to the GUI is likely to depend on some of the details of how the GUI >works. > >If you did the lower levels first without having any idea at all of >what you were going to do with the GUI, it's quite likely that you'd >find you'd written a few functions which turned out not to be needed at >all, or that some functionality that the GUI needs to use very >frequently is rather slow to execute, or that some functionality that >you thought belonged to the 'logic' is really better done in the GUI >layer, and so on and so forth. > >For example, if you were writing the 'logic' for a chess program you >might choose a way of modelling the board that can't represent a >position with more than one black king. And then when you got round to >doing the GUI you might find out that your users would like to be able >to have this temporarily when setting up a position. What you say may be true, but this doesn't seem to me like a good example. Not that I see _why_ the player would want to have two kings temporarily, but if so I wouldn't have the view report this state to the model, I'd have the view wait until the player had decided on the final configuration betore saying anything to the model. The model should only deal with legal positions. (Could be that it's not until we start actually playing the game through the GUI that we find the model can't deal with two black queens. But that's not an example either, that would just mean the model is wrong, not allowing every legal position.) >-M- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: WXpython Question
On Fri, 23 May 2008 06:40:13 -0700 (PDT), Gandalf <[EMAIL PROTECTED]> wrote: >On May 23, 3:29 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote: >> On May 23, 8:24 am, Gandalf <[EMAIL PROTECTED]> wrote: >> >> > I try to reach a specific wx StaticText element's text and to change >> > it by clicking on a button >> >> > now let's say the this is my element: >> >> > wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE) >> >> > And this is my EVT_BUTTON bind function : >> >> > def OnClick(event): >> >> > which code shude i enter to change "hello" to "goodbay"? >> >> > thanks >> >> You're probably looking for SetLabel(). So if you do something like >> this to instantiate the StaticText: >> >> self.myText = wx.StaticText(panel, 15, "Hello" ,(30, 70) , >> style=wx.ALIGN_CENTRE) >> >> Then you can change your text by adding this to your OnClick event >> handler: >> >> self.myText.SetLabel("goodbye") >> >> Have fun! And remember, there's a great wxPython mailing list too: >> >> http://www.wxpython.org/maillist.php >> >> Mike > >Thanks! You should also note docs.wxwidgets.org (I tend to find that by googling "wxTreeCtrl" or whatever.) The descriptions of various components there are more complete than in the (excellent!) wxPython book - it's C++ but usually not hard to figure out what the corresponding wxPython should be. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: access interactive namespace from module (shared namespace?)
On Sun, 25 May 2008 03:32:30 -0700 (PDT), [EMAIL PROTECTED] wrote: >Thanks for the reply, > >Of course the suggested solution is working and good, but a bit >complicated. The module/function where i need to access the variable >value from the interactive shell is burried quite deep and I would >nedd to hand the locals() quite often from one module to another. >Furthermore it makes the call function slightly more complicated, as >the locals()-argunment has to be given every time. > >I was hoping for something a bit different: If I wanted to access a >value b from another module "utest2.py", I would simply need to type >in utest.py: import utest2; print 2*utest2.b >Isn't there a name for the interactive namespace (like here the >utest2), which I can use to access the variable without handing the >whole dictionary? """utest.py""" import __main__ def doit(): print 2*__main__.a >Cheers, > >Ulrich > > David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: How to covert ASCII to integer in Python?
In article <[EMAIL PROTECTED]>, "Skonieczny, Chris" <[EMAIL PROTECTED]> wrote: > YOU SHOULD REMOVE or CORRECT YOUR POST here: > http://mail.python.org/pipermail/python-list/2007-February/427841.html Why? There's nothing wrong there. > It is not true - eg. try : > a='P'# P is ASCII , isn't it ? > b=int(a) > and what you will get ? An error !!! You really don't see any difference between "convert '1' to an integer" and "convert 'P' to an integer"? In case there's actually a problem you're trying to solve here, try ord instead of int. > Or probably you yourself should - quote : > "You probably should go through the tutorial ASAP that is located here: > > http://docs.python.org/tut/ " > > - > [Image] -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting up and running with Python on a Mac
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote: > I've just bought an iMac (OS X 10.5.2, will almost immediately jump to > 10.5.3), and am looking to install Python on it, and to use it with > XCode, Apple's IDE. If that's what you really want to do then start XCode, select New Project and look for the ones with "Python" in their names. I was excited to hear that Python was going to be automatically integrated into XCode in OS 10.5. I tried it once. I should say I really didn't give it a fair trial - the impression I got from my unfair trial was I'd have to learn a lot about Cocoa to do anything useful. Searched a little, decided to try wxPython next, and I was very happy with that. Seems much easier - also as far as I could see there was nothing but a 'Hello World' example included in XCode, while wxPython comes with a truly amazing suite of complete examples (the C++ wxWidgets book recommends looking at wxPython for the examples!) >Some googling suggests that a number of people > have had trouble getting Python to run satisfactorily on their Macs. > This is my first Mac, and I'd appreciate some guidance on what to do > (and what not to) when installing Python and potential problems to > keep an eye open for. I want to do a fair bit of scientific / > numerical computing, so it would seem that SAGE ot the Enthought > Python distribution would seem to be the most relevant - I'd > appreciate your guidance on getting Python to run on a Mac with a > particular focus on these two distributions. > > Thank you in advance > > Thomas Philips -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: A video introducing Ulipad, an IDE mainly for Python
In article <[EMAIL PROTECTED]>, Dick Moores <[EMAIL PROTECTED]> wrote: > I've been using Ulipad, a free IDE mainly for Python, and written in > wxPython, for a couple of years, and think it's terrific. Now another > user, Kelie Feng, has made an 8-minute video showing it off. The > visual clarity of the video is remarkable. You can download it > (Introducing_Ulipad_2008-05-22.avi), and a codec (tscc.exe) that may > be necessary for your player, from <http://www.rcblue.com/u3/>. I skipped the video and tried Ulipad. Looks very interesting. The documentation I got is mostly in Chinese. Is there an English version somewhere? > Dick Moores -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: re
Actually using regular expressions for the first time. Is there something that allows you to take the union of two character sets, or append a character to a character set? Say I want to replace 'disc' with 'disk', but only when 'disc' is a complete word (don't want to change 'discuss' to 'diskuss'.) The following seems almost right: [^a-zA-Z])disc[^a-zA-Z] The problem is that that doesn't match if 'disc' is at the start or end of the string. Of course I could just combine a few re's with |, but it seems like there should (or might?) be a way to simply append a \A to the first [^a-zA-Z] and a \Z to the second. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: re
In article <[EMAIL PROTECTED]>, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > David C. Ullrich schrieb: > > Actually using regular expressions for the first > > time. Is there something that allows you to take the > > union of two character sets, or append a character to > > a character set? > > > > Say I want to replace 'disc' with 'disk', but only > > when 'disc' is a complete word (don't want to change > > 'discuss' to 'diskuss'.) The following seems almost > > right: > > > > [^a-zA-Z])disc[^a-zA-Z] > > > > The problem is that that doesn't match if 'disc' is at > > the start or end of the string. Of course I could just > > combine a few re's with |, but it seems like there should > > (or might?) be a way to simply append a \A to the first > > [^a-zA-Z] and a \Z to the second. > > Why not > > ($|[\w])disc(^|[^\w]) > > I hope \w is really the literal for whitespace - might be something > different, see the docs. Thanks, but I don't follow that at all. Whitespace is actually \s. But [\s]disc[whatever] doesn't do the job - then it won't match "(disc)", which counts as "disc appearing as a full word. Also I think you have ^ and $ backwards, and there's a ^ I don't understand. I _think_ that a correct version of what you're suggesting would be (^|[^a-zA-Z])disc($|[^a-zA-Z]) But as far as I can see that simply doesn't work. I haven't been able to use | that way, combining _parts_ of a re. That was the first thing I tried. The original works right except for not matching at the start or end of a string, the thing with the | doesn't work at all: >>> test = compile(r'(^|[^a-zA-Z])disc($|[^a-zA-Z])') >>> test.findall('') [] >>> test.findall('disc') [('', '')] >>> test.findall(' disc ') [(' ', ' ')] >>> disc = compile(r'[^a-zA-Z]disc[^a-zA-Z]') >>> disc.findall(' disc disc disc') [' disc '] >>> disc.findall(' disc disc disc') [' disc ', ' disc '] >>> test.findall(' disc disc disc') [(' ', ' '), (' ', ' ')] >>> disc.findall(' disc disc disc') [' disc ', ' disc '] >>> disc.findall(' disc disc disc ') [' disc ', ' disc ', ' disc '] > Diez -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: re
In article <[EMAIL PROTECTED]>, "Russell Blau" <[EMAIL PROTECTED]> wrote: > "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > David C. Ullrich schrieb: > >> Say I want to replace 'disc' with 'disk', but only > >> when 'disc' is a complete word (don't want to change > >> 'discuss' to 'diskuss'.) The following seems almost > >> right: > >> > >> [^a-zA-Z])disc[^a-zA-Z] > >> > >> The problem is that that doesn't match if 'disc' is at > >> the start or end of the string. Of course I could just > >> combine a few re's with |, but it seems like there should > >> (or might?) be a way to simply append a \A to the first > >> [^a-zA-Z] and a \Z to the second. > > > > Why not > > > > ($|[\w])disc(^|[^\w]) > > > > I hope \w is really the literal for whitespace - might be something > > different, see the docs. > > No, \s is the literal for whitespace. > http://www.python.org/doc/current/lib/re-syntax.html > > But how about: > > text = re.sub(r"\bdisc\b", "disk", text_to_be_changed) > > \b is the "word break" character, Lovely - that's exactly right, thanks. I swear I looked at the docs... I'm just blind or stupid. No wait, I'm blind _and_ stupid. No, blind and stupid and slow... Doesn't precisely fit the _spec_ because of digits and underscores, but it's close enough to solve the problem exactly. Thanks. >it matches at the beginning or end of any > "word" (where a word is any sequence of \w characters, and \w is any > alphanumeric > character or _). > > Note that this solution still doesn't catch "Disc" if it is capitalized. Thanks. I didn't mention I wanted to catch both cases because I already knew how to take care of that: r"\b[dD]isc\b" > Russ -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: how should i use this function?
In article <[EMAIL PROTECTED]>, Gandalf <[EMAIL PROTECTED]> wrote: > On Jun 4, 8:21 pm, sturlamolden <[EMAIL PROTECTED]> wrote: > > On Jun 4, 8:14 pm, Gandalf <[EMAIL PROTECTED]> wrote: > > > > > I tried to import win32ui.PyCRichEditCtrl, But the shell told me > > > their's no such module. > > > > There isn't, as it is a class. win32ui is a module. If you cannot > > import that, you don't have pywin32 installed. Go get it from > > Sourceforge. > > But I pywin32 use it all the time i have pywinauto And, as I seem to recall someone saying once, win32ui.PyCRichEditCtrl is not a module so you can't import it. You can say from win32ui import PyCRichEditCtrl Or you can say import win32ui and then reference win32ui.PyCRichEditCtrl . -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Import removing first module component
In article <[EMAIL PROTECTED]>, koblas <[EMAIL PROTECTED]> wrote: > Have the following line: > import notewave.runner.LMTP > > Yeilding the following error: > ImportError: No module named runner.LMTP > > For the life of me I don't understand why the first component > "notewave" is being stripped off, when the import is happening. Does notewave contain a _module_ named runner.LMTP ? Probably not, since the error message says there's no such module. > Thanks, -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: re
On Wed, 04 Jun 2008 20:07:41 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: >> Whitespace is actually \s. But [\s]disc[whatever] >> doesn't do the job - then it won't match "(disc)", >> which counts as "disc appearing as a full word. > >Ok, then this works: Yes it does. My real question was why doesn't a construction like (A|B)C work as expected. The code below shows that it does. That puzzled me because I couldn't see any real difference between your solution here and things I'd tried that didn't work. But those things also work in the code below - when I saw this just now I was even more confused... Oh. Turns out the actual reason for the confusion wasn't regex syntax, it was the fact that findall doesn't return what I thought it did - looking at the result of findall() it seemed as thought the re was matching empty strings and whitespace... Looking more carefully at what findall is supposed to do everything makes sense. Sorry to be dense. Remind me to read more than the first sentence next time: "findall (pattern, string) Return a list of all non-overlapping matches of pattern in string. If one or more groups are present in the pattern, return a list of groups;..." >import re > >test = """ >disc >(disc) >foo disc bar >discuss >""".split("\n") > >for t in test: > if re.search(r"(^|[^\w])(disc)($|[^\w])", t): > print "success:", t > > >> Also I think you have ^ and $ backwards, and there's >> a ^ I don't understand. I _think_ that a correct version > >Yep, sorry for the confusion. > >Diez David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: ClassName.attribute vs self.__class__.attribute
In article <[EMAIL PROTECTED]>, Gabriel Rossetti <[EMAIL PROTECTED]> wrote: > Larry Bates wrote: > > Gabriel Rossetti wrote: > >> Hello everyone, > >> > >> I had read somewhere that it is preferred to use > >> self.__class__.attribute over ClassName.attribute to access class > >> (aka static) attributes. I had done this and it seamed to work, until > >> I subclassed a class using this technique and from there on things > >> started screwing up. I finally tracked it down to > >> self.__class__.attribute! What was happening is that the child > >> classes each over-rode the class attribute at their level, and the > >> parent's was never set, so while I was thinking that I had indeed a > >> class attribute set in the parent, it was the child's that was set, > >> and every child had it's own instance! Since it was a locking > >> mechanism, lots of fun to debug... So, I suggest never using > >> self.__class__.attribute, unless you don't mind it's children > >> overriding it, but if you want a truly top-level class attribute, use > >> ClassName.attribute everywhere! I shouldn't butt in since everyone else knows more about this than I do, but it seems to me that saying you should do this is wrong and saying you should do that is wrong - which you should do depends on what you're trying to accomplish. There's something that comes up all the time in stuff I do, where implicitly accessing self.__class__.attribute is vital to make it work right. Say I have a Matrix class, with an __add__ method: class Matrix: def __init__(self, data): whatever def __add__(self, other): newdata = whatever return Matrix(newdata) The last line is almost surely not what I want (took me a while, long ago, to figure this out). Because someday when I have a subclass I want __add__ to return an instance of the subclass. At first I thought I needed to rewrite the last line to return SubClass(newdata). No, I simply return self.__class__(newdata) and it works exactly the way I want. > >> I wish books and tutorials mentioned this explicitly > >> > >> Gabriel > > > > If you define a class instance variable with the same name as the > > class attribute, how would Python be able to distinguish the two? > > That is a feature not a problem. Getter looks for instance attribute, > > if one is not found it looks for a class attribute, and upwards. This > > behavior is used by Zope to do all sorts of neat stuff. > > > > -Larry Bates > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > A class instance variable, you must mean an instance attribute no? If > that is so, then with just self.attribute? Maybe there is a concept that > I don't know about, I've studied class/static attributes and instance > attributes in my OOP classes. > > Gabriel -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: how to build a street with more than 1 house ?
On Sat, 07 Jun 2008 00:45:07 +0200, Stef Mientki <[EMAIL PROTECTED]> wrote: >hello, > >In the code below, I can build a large street like this: > large_street = house * 25 >but not a small street. like this: > small_street = 5 * house > >Why is this different ? Because you're multiplying on the left in one case and on the right in the other. You realize that house*5 should work, right? >And more interesting, how do I get the right results ? > >thanks, >Stef Mientki > >class type_house ( object ) : > def __init__( self, front_doors = 1 ) : >self.front_doors = front_doors > def __mul__ ( self, b ) : >return type_house ( self.front_doors * b ) The reason house*25 works is that the __mul__ method says what it should be. If you want 5*house to work you need a __rmul__. Nothing in Python automatically makes a*b the same as b*a; when it sees 5*house first it checks 5 to see whether it knows whether it knows what 5*house should be (no, 5 never heard of this house thing), then it checks house to see if it knows what 5*house should be (no, house has no __rmul__). The simplest thing is just to define __rmul__ to make multiplication commuttative: def __rmul__(self, b): """Defines what b*self should return.""" return self*b Now 5*house calls __rmul__, which returns house*5. That in turn calls __mul__, which returns what you want. And some day when you modify __mul__ (in a subclass?) you won't need to worry about making the same change to __rmul__. >house = type_house () >large_street = house * 25 >print large_street.front_doors >small_street = 5 * house >print small_street.front_doors David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
re quiz
True or False? (no fair looking it up) (*) If repl is a string then re.sub(pattern, repl, s) returns s with non-overlapping occurences of pattern replaced by repl. I assumed it was true - spent a few hours trying to figure out what was going on with a certain re.sub, then noticed that (*) is false: (**) "If repl is a string, any backslash escapes in it are processed. That is, "\n" is converted to a single newline character, "\r" is converted to a linefeed, and so forth." So I changed my r"\remark{Hint}" to r"\\remark{Hint}" and things were fine. A pointless question and then a practical one. Pointless question: There must be a good reason for (**). What would it be? Seems needlessly confusing to me (of course a lot of things seem confusing to me...) Maybe it's going to be confusing no matter what they do. But "\\n" looks like it doesn't contain a newline, but it gets converted to something that does. (Another fascinating question is how they could phrase the docs here so as to confuse nobody. Because "\n" _is_ a newline, or so it's going to look to many people; I'd spell it out:: "a string containing '\' followed by 'n' ".) Practical question: What's a _complete_ list of the escapes included in the "and so forth" in (**)? (Or is there a function somewhere that will convert r"\remark{Hint}" to r"\\remark{Hint}" for me, and do the same for precisely the escpapes referred to in the "and so forth"?) David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
regex for balanced parentheses?
There's no regex that detects balanced parentheses, or is there? That is, search('and so ((x+y)+z) = (x+(y+z))') should return '((x+y)+z)'. Not just a theoretical question, I'm cleaning up a large body of TeX code and a regex that did that would be very convenient. (Yes, I know it's not hard to detect balanced parentheses by hand...) I don't know that stuff, but I seen to recall reading that there's a theoretical notion of "regular expression" in CS, and a regular expression in that sense cannot do this. But in the same place I read that the actual regexes in programming languages include things which are not regular expressions in that theoretical sense. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: get keys with the same values
On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <[EMAIL PROTECTED]> wrote: >Hello, > >I have a dictionary and will get all keys which have the same values. > >d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} That's not a dictionary, it's a syntax error. If you actually have a dictionary you could say d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} dd = {} for key, value in d.items(): try: dd[value].append(key) except KeyError: dd[value] = [key] Possibly dd is now what you really want; if you really want what you said you want you could use [l for l in dd.values() if len(l) > 1] >I will something as : > >d.keys(where their values are the same) > >With this statement I can get two lists for this example: >l1= ['a','e'] >l2=['b','d'] > >Would somebody tell me how I can do it? > >Regards, >Nader David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: re quiz
On Thu, 12 Jun 2008 05:12:55 -0700 (PDT), John Machin <[EMAIL PROTECTED]> wrote: >On Jun 12, 8:57 pm, David C. Ullrich <[EMAIL PROTECTED]> wrote: >> True or False? (no fair looking it up) >> >> (*) If repl is a string then re.sub(pattern, repl, s) >> returns s with non-overlapping occurences of pattern >> replaced by repl. >> >> I assumed it was true - spent a few hours trying to >> figure out what was going on with a certain re.sub, >> then noticed that (*) is false: >> > >Well, the docs do say "Return the string obtained by replacing the >leftmost non-overlapping occurrences of pattern in string by the >replacement repl." That's the _first sentence_, yes. I _quoted_ another sentence (from an old version, istr it phrased slightly differently in recent versions) in my post. > -- care to tell us what "a certain re.sub" is, and >false in what way? Read the OP. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: re quiz
On Thu, 12 Jun 2008 14:12:31 +0200, Peter Otten <[EMAIL PROTECTED]> wrote: >David C. Ullrich wrote: > >> (Or is there a function somewhere that will convert >> r"\remark{Hint}" to r"\\remark{Hint}" for me, and >> do the same for precisely the escpapes referred to >> in the "and so forth"?) > >I think you just have to escape the backslash: > >re.sub(pattern, replacement_string.replace("\\", ""), s) > >Anyway here's the list of troublemakers: Heh - I shoulda thought of that, determining which ones cause trouble by checking to see which ones cause trouble. Thanks. >>>> def means_trouble(c): >... try: >... return re.sub("x", "\\" + c, "x") != "\\" + c >... except: >... return True >... >>>> [c for c in map(chr, range(256)) if means_trouble(c)] >['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\\', 'a', 'b', 'f', 'g', >'n', 'r', 't', 'v'] > > >Peter David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: re quiz
On 12 Jun 2008 12:32:13 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote: >David C. Ullrich <[EMAIL PROTECTED]> wrote: > >> Practical question: What's a _complete_ list of the >> escapes included in the "and so forth" in (**)? >> >> (Or is there a function somewhere that will convert >> r"\remark{Hint}" to r"\\remark{Hint}" for me, and >> do the same for precisely the escpapes referred to >> in the "and so forth"?) >> > >As the documentation says: > >Character escapes >Numbered Groups: \0 \1 \2 \3 ... >Named groups: \g >Numbered groups with explicit termination of the number: \g<0> \g<1> ... Right - I was wondering about a complete list of character escapes. >But it doesn't matter what the complete list is. All of the escapes start >with \ so doubling all the \\ will prevent any of them being interpreted as >special so if you aren't wanting to substitute any groups into the string >just try repl.replace('\\', r'\\') Good point. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: regex for balanced parentheses?
On Thu, 12 Jun 2008 06:38:16 -0700 (PDT), Paul McGuire <[EMAIL PROTECTED]> wrote: >On Jun 12, 6:06 am, David C. Ullrich <[EMAIL PROTECTED]> wrote: >> There's no regex that detects balanced parentheses, >> or is there? >> >> [...] > >Pyparsing includes several helper methods for building common >expression patterns, such as delimitedList, oneOf, operatorPrecedence, >countedArray - and a fairly recent addition, nestedExpr. nestedExpr >creates an expression for matching nested text within opening and >closing delimiters, such as ()'s, []'s, {}'s, etc. Keen. Howdya know I wanted that? Thanks. TeX is one of the amazing things about free software. Knuth is great in many ways. He totally blew it in one detail, unfortunately one that comes up a lot: '$' is an opening delimiter, for which the corresponding closing delimiter is also '$'. Then better yet, '$$' is another double-duty delimiter... what I've done with that is first split on '$$', taking the odd-numbered bits to be the parts enclosed in $$..$$, and then taking the remining parts and splitting on $. Not hard but it gives me a creepy feeling. Hence the question: Can pyparsing tell the difference between '$' and '$'? (heh-heh). > The default >delimiters are ()'s. You can also specify a content expression, so >that pyparsing will look for and construct meaningful results. The >default is to return any text nested within the delimiters, broken up >by whitespace. > >Here is your sample string parsed using the default nestedExpr: >>>> from pyparsing import nestedExpr >>>> for e in nestedExpr().searchString('and so ((x+y)+z) = (x+(y+z))'): >... print e[0] >... >[['x+y'], '+z'] >['x+', ['y+z']] > >Pyparsing found 2 matches in your input string. Note that the parens >are gone from the results - nestedExpr returns a nested list >structure, with nesting corresponding to the ()'s found in the >original string. > >Pyparsing supports parse-time callbacks, called 'parse actions', and >it comes with several commonly used methods, such as removeQuotes, >upcaseTokens, and keepOriginalText. The purpose of keepOriginalText >is to revert any structuring or parsing an expression or other parse >actions might do, and just return the originally matched text. > >Here is how keepOriginalText gives you back just the nested >parenthetical expressions, without any additional processing or >grouping: >>>> from pyparsing import keepOriginalText >>>> matchedParens = nestedExpr().setParseAction(keepOriginalText) >>>> for e in matchedParens.searchString('and so ((x+y)+z) = (x+(y+z))'): >... print e[0] >... >((x+y)+z) >(x+(y+z)) > >-- Paul David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
In article <[EMAIL PROTECTED]>, "Andrea Gavana" <[EMAIL PROTECTED]> wrote: > Hi Diez & All, > > > And on a personal note: I find it *buttugly*. > > Do you mind explaining "why" you find it *buttugly*? My guess would be that "buttugly" is a colloquialism meaning "exquisitely lovely". >I am asking just > out of curiosity, obviously. I am so biased towards wxPython that I > won't make any comment on this thread in particular, but I am curious > to know why some people find it "ugly" or "bad" or whatever. It has > its own bugs and missing features, of course, but it is one of the > major GUI player in the arena, together with PyQt and PyGTK. > > Andrea. > > "Imagination Is The Only Weapon In The War Against Reality." > http://xoomer.alice.it/infinity77/ -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: regex for balanced parentheses?
In article <[EMAIL PROTECTED]>, Paul McGuire <[EMAIL PROTECTED]> wrote: > Parsing TeX is definitely not for the faint-of-heart! You might try > something like QuotedString('$', escQuote='$$') in pyparsing. (I've > not poked at TeX or its ilk since the mid-80's so my TeXpertise is > long rusted away.) Thanks. Not actually parsing TeX, just going through and making little changes to a few things. Easier since I wrote the original crap so I know that various things don't come up (for example _every_ % is the start of a comment and _none_ of those comments is actually important, they're all just old stuff commented out.) > I know of two projects that have taken on the problem using pyparsing > - one is the mathtext module in John Hunter's matplotlib, and Tim > Arnold posted some questions on the subject a while back - try > googling for "pyparsing tex" for further leads. > > -- Paul -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: re quiz
In article <[EMAIL PROTECTED]>, Johannes Bauer <[EMAIL PROTECTED]> wrote: > David C. Ullrich schrieb: > > >> -- care to tell us what "a certain re.sub" is, and > >> false in what way? > > > > Read the OP. > > Well, aren't you funny. Maybe you should have referenced the other > thread so one can find the OP? What other thread? OP is sometimes Original Poster and sometimes Original Post. In the original post in this very thread I gave an quote from the docs and an example illustrating the answer to the question I was asked. Ok, I guess it's hard to find the top of the thread. I wanted to replace a certain pattern with r"\remark{Hint}". I didn't understand why that didn't work until I read the bit of the docs that I quoted in my original post: (**) "If repl is a string, any backslash escapes in it are processed. That is, "\n" is converted to a single newline character, "\r" is converted to a linefeed, and so forth." > Regards, > Johannes -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: get keys with the same values
In article <[EMAIL PROTECTED]>, Nader <[EMAIL PROTECTED]> wrote: > On Jun 12, 1:41 pm, David C. Ullrich <[EMAIL PROTECTED]> wrote: > > On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <[EMAIL PROTECTED]> > > wrote: > > > > >Hello, > > > > >I have a dictionary and will get all keys which have the same values. > > > > >d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} > > > > That's not a dictionary, it's a syntax error. If you actually > > have a dictionary you could say > > > > d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > > > > dd = {} > > > > for key, value in d.items(): > > try: > > dd[value].append(key) > > except KeyError: > > dd[value] = [key] > > > > Possibly dd is now what you really want; if you really > > want what you said you want you could use > > > > [l for l in dd.values() if len(l) > 1] > > > > >I will something as : > > > > >d.keys(where their values are the same) > > > > >With this statement I can get two lists for this example: > > >l1= ['a','e'] > > >l2=['b','d'] > > > > >Would somebody tell me how I can do it? > > > > >Regards, > > >Nader > > > > David C. Ullrich > > Thank for your type about the syntax error. This an example example, > the keys of my dictionary are tuples: > d = {(37.75, 42.22): 1 , (37.51, 40.02): 3 (45.55, 24.27): 4 (47.08, > 30.99) : 1} > > But what I will is to get all keys which has the same valus. That's exactly what the code I posted does. > And not > the keys that have value more than 1! It doesn't do that. Or if you prefer, it doesn't do that! Instead of looking at it and trying to figure out what it does, which of course can be tricky, try _running_ the code. Then print dd. Then print [l for l in dd.values() if len(l) > 1] . > > Nader -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: get keys with the same values
In article <[EMAIL PROTECTED]>, Paul McGuire <[EMAIL PROTECTED]> wrote: > On Jun 12, 6:41 am, David C. Ullrich <[EMAIL PROTECTED]> wrote: > > On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <[EMAIL PROTECTED]> > > wrote: > > > > >Hello, > > > > >I have a dictionary and will get all keys which have the same values. > > > > > > > d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > > > > dd = {} > > > > for key, value in d.items(): > > try: > > dd[value].append(key) > > except KeyError: > > dd[value] = [key] > > > > > Instead of all that try/except noise, just use the new defaultdict: That's certainly much better. The machine where I am in the early morning is still stuck with Python 1.5.3... > >>> from collections import defaultdict > >>> > >>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4} > >>> > >>> dd = defaultdict(list) > >>> for key, value in d.items(): > ... dd[value].append(key) > ... > >>> for k,v in dd.items(): > ... print k,':',v > ... > 1 : ['a', 'e'] > 2 : ['c'] > 3 : ['b', 'd'] > 4 : ['f'] > > -- Paul -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Mapping None. Why?
On Thu, 12 Jun 2008 12:05:02 -0700 (PDT), Paddy <[EMAIL PROTECTED]> wrote: > >Iam wondering why the peculiar behavior of map when the function in >given as None: If you start with a value x and then apply no function at all to it, what results is x. >Help on built-in function map in module __builtin__: > >map(...) >map(function, sequence[, sequence, ...]) -> list > >Return a list of the results of applying the function to the items >of >the argument sequence(s). If more than one sequence is given, the >function is called with an argument list consisting of the >corresponding >item of each sequence, substituting None for missing values when >not all >sequences have the same length. If the function is None, return a >list of >the items of the sequence (or a list of tuples if more than one >sequence). > > >It seems as the action whith none is the same as using a function of > lambda *x: x >As in the following example: > >>>> l1 = 'asdf' >>>> l2 = 'qwertyuip' >>>> l3 = range(3) >>>> l1,l2,l3 >('asdf', 'qwertyuip', [0, 1, 2]) >>>> map(lambda *x: x, l1,l2,l3) == map(None, l1,l2,l3) >True >>>> > > >On looking up map on Wikipedia there is no mention of this special >behaviour, >So my question is why? > >Thanks, Paddy. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Mapping None. Why?
In article <[EMAIL PROTECTED]>, Paddy <[EMAIL PROTECTED]> wrote: > On Jun 13, 12:49 pm, David C. Ullrich <[EMAIL PROTECTED]> wrote: > > On Thu, 12 Jun 2008 12:05:02 -0700 (PDT), Paddy > > > > <[EMAIL PROTECTED]> wrote: > > > > >Iam wondering why the peculiar behavior of map when the function in > > >given as None: > > > > If you start with a value x and then apply no function > > at all to it, what results is x. > > > > David C. Ullrich > > True, but None is not a function. It's a sentinel value to turn on the > functionality. Uh, thanks. I think I knew that - I was just suggesting why the way map works makes sense. > - Paddy. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Python class questions
In article <[EMAIL PROTECTED]>, Lie <[EMAIL PROTECTED]> wrote: > On Jun 19, 7:21 pm, Ulrich Eckhardt <[EMAIL PROTECTED]> wrote: > > John Dann wrote: > > > Let's say I define the class in a module called comms.py. The class > > > isn't really going to inherit from any other class (except presumably > > > in the most primitive base-class sense, which is presumably automatic > > > and implicit in using the class keyword). Let's call the class > > > serial_link. So in comms.py I have: > > > > > class serial_link: > > > def __init__(self): > > > Try > > > Import serial # the pyserial library > > > > Stop, this can't work. Other than VB, Python actually is case sensitive, so > > you must write 'try' and not 'Try' and also 'import' and not 'Import'. > > Further, many (all?) statements that cause an indention are usually > > terminated with a colon, so like with 'class ..:' and 'def ..:' you also > > must use 'try:' and not just 'try'. Fix all these and try again, I guess > > this will already help a lot. > >[...] > > > > Uli > > > > -- > > Sator Laser GmbH > > Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 > > I think it's not that hard to see that it's just a pseudo code I would have _thought_ it wasn't hard to see that if a person says he's totally new to the language, and even explicitly says that the problem could be syntax errors, then he shouldn't post pseudo code. How in the world is pseudo code going to allow people to help him fix his syntax? -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: ask for a RE pattern to match TABLE in html
In article <[EMAIL PROTECTED]>, Cédric Lucantis <[EMAIL PROTECTED]> wrote: > Le Thursday 26 June 2008 15:53:06 oyster, vous avez écrit : > > that is, there is no TABLE tag between a TABLE, for example > > something with out table tag > > what is the RE pattern? thanks > > > > the following is not right > > [^table]*? > > The construct [abc] does not match a whole word but only one char, so > [^table] means "any char which is not t, a, b, l or e". > > Anyway the inside table word won't match your pattern, as there are '<' > and '>' in it, and these chars have to be escaped when used as simple text. > So this should work: > > re.compile(r'.*') > ^ this is to avoid matching a tag name starting with > table > (like ) Doesn't work - for example it matches '' (and in fact if the html contains any number of tables it's going to match the string starting at the start of the first table and ending at the end of the last one.) -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: ask for a RE pattern to match TABLE in html
In article <[EMAIL PROTECTED]>, Jonathan Gardner <[EMAIL PROTECTED]> wrote: > On Jun 26, 3:22 pm, MRAB <[EMAIL PROTECTED]> wrote: > > Try something like: > > > > re.compile(r'.*?', re.DOTALL) > > So you would pick up strings like "foo td>"? I doubt that is what oyster wants. I asked a question recently - nobody answered, I think because they assumed it was just a rhetorical question: (i) It's true, isn't it, that it's impossible for the formal CS notion of "regular expression" to correctly parse nested open/close delimiters? (ii) The regexes in languages like Python and Perl include features that are not part of the formal CS notion of "regular expression". Do they include something that does allow parsing nested delimiters properly? -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: ask for a RE pattern to match TABLE in html
In article <[EMAIL PROTECTED]>, Dan <[EMAIL PROTECTED]> wrote: > On Jun 27, 1:32 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote: > > In article > > <[EMAIL PROTECTED]>, > > Jonathan Gardner <[EMAIL PROTECTED]> wrote: > > > > > On Jun 26, 3:22 pm, MRAB <[EMAIL PROTECTED]> wrote: > > > > Try something like: > > > > > > re.compile(r'.*?', re.DOTALL) > > > > > So you would pick up strings like "foo > > td>"? I doubt that is what oyster wants. > > > > I asked a question recently - nobody answered, I think > > because they assumed it was just a rhetorical question: > > > > (i) It's true, isn't it, that it's impossible for the > > formal CS notion of "regular expression" to correctly > > parse nested open/close delimiters? > > Yes. For the proof, you want to look at the pumping lemma found in > your favorite Theory of Computation textbook. Ah, thanks. Don't have a favorite text, not having any at all. But wikipedia works - what I found at http://en.wikipedia.org/wiki/Pumping_lemma_for_regular_languages was pretty clear. (Yes, it's exactly that \1, \2 stuff that convinced me I really don't understand what one can do with a Python regex.) > > > > (ii) The regexes in languages like Python and Perl include > > features that are not part of the formal CS notion of > > "regular expression". Do they include something that > > does allow parsing nested delimiters properly? > > So, I think most of the extensions fall into syntactic sugar > (certainly all the character classes \b \s \w, etc). The ability to > look at input without consuming it is more than syntactic sugar, but > my intuition is that it could be pretty easily modeled by a > nondeterministic finite state machine, which is of equivalent power to > REs. The only thing I can really think of that is completely non- > regular is the \1 \2, etc syntax to match previously match strings > exactly. But since you can't to an arbitrary number of them, I don't > think its actually context free. (I'm not prepared to give a proof > either way). Needless to say that even if you could, it would be > highly impractical to match parentheses using those. > > So, yeah, to match arbitrary nested delimiters, you need a real > context free parser. > > > > > -- > > David C. Ullrich > > > -Dan -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: complex numbers should respect the "I" representation
In article <[EMAIL PROTECTED]>, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > hi > > I think complex numbers should respect the "i" or "I" representation, > instead of "j". > No reason being cute and using a different character instead of the > traditional representation? At least have the decency of supporting > the orginal representation? > Programmers use j as frequently as i as indexing variable, I see no > reason choosing "j" over "i". Have some respect for majority's rules. Yeah, I tried Python once, found it used "j" this way and decided that Perl made a lot more sense. > This is childish. erm, yes it is, for various values of "this"... -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Do I need "self" and "other"?
In article <[EMAIL PROTECTED]>, Kurda Yon <[EMAIL PROTECTED]> wrote: > Hi, > > I found one example which defines the addition of two vectors as a > method of a class. It looks like that: > > class Vector: > def __add__(self, other): > data = [] > for j in range(len(self.data)): > data.append(self.data[j] + other.data[j]) > return Vector(data) > > In this example one uses "self" and "other". Does one really need to > use this words? And, if yes, why? I have replaced "self" by "x" and > "other" by "y" and everything looks OK. Is it really OK or I can have > some problem in some cases? What everyone else has said: yes and no. Having said that, it seems to me like this is exactly the sort of situation where 'x' and 'y' make a lot of sense - self means that this is the object on which the method was invoked, and here that seems irrelevant: If you want to calculate x + y you use x.data and y.data... Otoh, I once saw a library (someone's Python arbitrary-precision reals package) where he used x and y, and sure enough I was confused. Otooh, I was't confused by it for long, and I quickly decided that it actually made _that_ code look like it made more sense. > Thank you! -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: ask for a RE pattern to match TABLE in html
In article <[EMAIL PROTECTED]>, Jonathan Gardner <[EMAIL PROTECTED]> wrote: > On Jun 27, 10:32 am, "David C. Ullrich" <[EMAIL PROTECTED]> wrote: > > (ii) The regexes in languages like Python and Perl include > > features that are not part of the formal CS notion of > > "regular expression". Do they include something that > > does allow parsing nested delimiters properly? > > > > In perl, there are some pretty wild extensions to the regex syntax, > features that make it much more than a regular expression engine. > > Yes, it is possible to match parentheses and other nested structures > (such as HTML), and the regex to do so isn't incredibly difficult. > Note that Python doesn't support this extension. Huh. My evidently misinformed impression was that the regexes in P and P were essentially equivalent. (I hope nobody takes that as a complaint...) > See http://www.perl.com/pub/a/2003/08/21/perlcookbook.html -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: caseless dict - questions
In article <[EMAIL PROTECTED]>, Phoe6 <[EMAIL PROTECTED]> wrote: > I have a requirement for using caseless dict. I searched the web for > many different implementations and found one snippet which was > implemented in minimal and useful way. > > # > import UserDict > > class CaseInsensitiveDict(dict, UserDict.DictMixin): > def __init__(self, *args, **kwargs): > self.orig = {} > super(CaseInsensitiveDict, self).__init__(*args, **kwargs) > def items(self): > keys = dict.keys(self) > values = dict.values(self) This items() can't be what anyone would want items to be for a "caseless dict". > return [(self.orig[k],v) for k in keys for v in values] > def __setitem__(self, k, v): > hash_val = hash(k.lower()) > self.orig[hash_val] = k > dict.__setitem__(self, hash_val, v) > def __getitem__(self, k): > return dict.__getitem__(self, hash(k.lower())) > > > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > print obj.items() > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > print obj1.items() > ### > [EMAIL PROTECTED] python]$ python cid1.py > {15034981: 'senthil'} > [('Name', 'senthil')] > {'Name': 'senthil'} > [('Name', 'senthil')] > > --- > The difference between the Caselessdict and {} is that when called as > the object, the Caselessdict() is giving me the internal > representation. > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > gives: {15034981: 'senthil'} > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > Correctly gives {'Name': 'senthil'} > > What changes should I make to CaseInsensitiveDict ( written above), so > that its instance gives the actual dictionary instead of its internal > representation. > Constructing a dictionary and returning from __init__ method did not > work. It's not entirely clear to me what you want: Since this is supposed to be a "caseless" dict, I imagine that if you say d['Name'] = 'first value' d['name'] = 'new value' then d['Name'] should now be 'new value'. Fine. Now in that case exactly what do you want to see when you print d? Do you want to see {'name':'new value'} or {'name':'new value', 'Name': 'newvalue'}? > TIA, > Senthil -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make a function associated with a class?
In article <[EMAIL PROTECTED]>, Kurda Yon <[EMAIL PROTECTED]> wrote: > On Jul 1, 5:01 pm, "[EMAIL PROTECTED]" > <[EMAIL PROTECTED]> wrote: > > On 1 juil, 22:43, Kurda Yon <[EMAIL PROTECTED]> wrote: > > > > > > > > > Hi, > > > > > I have a class called "vector". And I would like to define a function > > > "dot" which would return a dot product of any two "vectors". I want > > > to call this function as follow: dot(x,y). > > > > > Well, I can define a functions "dot" outside the class and it works > > > exactly as I want. However, the problem is that this function is not > > > associated with the class (like methods a method of the class). > > > > > For example, if I call "x.calc()" or "y.calc()", python will execute > > > different methods if "x" and "y" belongs to different classes. I want > > > to have the same with my "dot" function. I.e. I want it calculates the > > > dot product ONLY IF the both arguments of that function belong to the > > > "vector" class. > > > > > Is it possible? > > > > You don't need to make dot() a method of your Vector class to have > > this behaviour, and making it a method of the Vector class isn't > > enough to have this behaviour. > > > > The simplest solution would be: > > > > class Vector(object): > > def dot(self, other): > > if not isinstance(other, type(self)): > > raise TypeError("can only calculate the dot product of two > > vectors") > > # do the job here and return what's appropriate > > > > Now since it's a binary operator, you might as well implement it as > > such: > > > > class Vector(object): > > def __mul__(self, other): > > if not isinstance(other, type(self)): > > raise TypeError("can only calculate the dot product of two > > vectors") > > # do the job here and return what's appropriate > > > > Then use it as doproduct = vector1 * vector2 > > > > HTH > > As far as I understood, In the first case, you gave, I need to call > the function as follows "x.dot(y)". In the second case I need to call > the function as follows "x*y". But I want to call the function as > follows "dot(x,y)". You want to say dot(x,y), but to have the actual behavior determined by the class of which x and y are instances? You could do this: def dot(x,y): return x.dot(y) and now give Vector an appropriate dot(self, other) method. > By the way, "type(self)" returns the name of the class to which the > "self" belongs? > Does "instance" return "true" if the first argument belongs to the > class whose name is given in the second argument? -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
"in"consistency?
Luckily I tried it before saying no, that's not how "in" works: >>> 'ab' in 'abc' True >>> [1,2] in [1,2,3] False Is there a reason for the inconsistency? I would have thought "in" would check for elements of a sequence, regardless of what sort of sequence it was... -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: "in"consistency?
In article <[EMAIL PROTECTED]>, Mel <[EMAIL PROTECTED]> wrote: > Ben Finney wrote: > > > "David C. Ullrich" <[EMAIL PROTECTED]> writes: > > > >> >>> 'ab' in 'abc' > >> True > >> >>> [1,2] in [1,2,3] > >> False > > > > http://www.python.org/doc/ref/comparisons.html> > > > >> Is there a reason for the inconsistency? > > > > Probably. The special behaviour of string types was changed in Python > > 2.3, according to that document. > > As it stands, you'd get > > [1,2] in [1,2,3] == False > > [1,2] in [1, [1,2], 3] == True > > > This could be a good thing. Oh, of course that's a good thing - changing "in" for lists to give True there would be awful. I was wondering why it _does_ work that way for strings. Maybe the answer is "because it can" - for strings the sort of possible problem you point out can't come up. > Mel. > > -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: "in"consistency?
In article <[EMAIL PROTECTED]>, Nick Dumas <[EMAIL PROTECTED]> wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. > Because the list [1,2,3] only contains the integers 1,2,3, the code > returns a False. Try "[1,2] in [[1,2],[2,3]]" Thanks. I understand how it works for lists and why - I was wondering why it's not the same for strings. > David C. Ullrich wrote: > > Luckily I tried it before saying no, that's > > not how "in" works: > > > >>>> 'ab' in 'abc' > > True > >>>> [1,2] in [1,2,3] > > False > > > > Is there a reason for the inconsistency? I would > > have thought "in" would check for elements of a > > sequence, regardless of what sort of sequence it was... > > > -BEGIN PGP SIGNATURE- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkhyiwEACgkQLMI5fndAv9jbiwCeKMXrAclILJMPro5VuSRgdkvB > cGkAn1igcjFWRQJSwEDOxpk3spzceZGa > =iq8L > -END PGP SIGNATURE- -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: "in"consistency?
In article <[EMAIL PROTECTED]>, Terry Reedy <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > >>>> 'ab' in 'abc' > > True > > 'a' in 'abc' works according to the standard meaning of o in collection. > > 'ab' in 'abc' could not work by that standard meaning because strings, > as virtual sequences, only contain characters (length 1 strings). Among > built-in collections, this limitation is unique to strings (and bytes, > in 3.0). So in 2.3, 'in' was given a useful extension of meaning that > is also unique to strings (and bytes). Ah, I didn't realize that this was new. Thanks - at least this means I was right about the way it worked formerly. > >>>> [1,2] in [1,2,3] > > False > > [1,2] can be an member of tuples, lists, dicts and other general > collections. [1,2] in collection therefore has that meaning, that it is > a single element of collection. Extending the meaning would conflict > with this basic meaning. Well of course. > > Is there a reason for the inconsistency? I would > > have thought "in" would check for elements of a > > sequence, regardless of what sort of sequence it was... > > It is not an inconsistency but an extension corresponding to the > limitation of what an string element can be. It's an inconsistency. That doesn't mean it's a bad thing or that I want my money back. It may well be a reasonable inconsistency - strings _can_ work that way while it's clear lists had better not. But it's an inconsistency. > Terry J. Reedy -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: "in"consistency?
In article <[EMAIL PROTECTED]>, Terry Reedy <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > In article <[EMAIL PROTECTED]>, > > Terry Reedy <[EMAIL PROTECTED]> wrote: > > >>> Is there a reason for the inconsistency? I would > >>> have thought "in" would check for elements of a > >>> sequence, regardless of what sort of sequence it was... > >> It is not an inconsistency but an extension corresponding to the > >> limitation of what an string element can be. > > > > It's an inconsistency. That doesn't mean it's a bad thing or that > > I want my money back. It may well be a reasonable inconsistency - > > strings _can_ work that way while it's clear lists had better not. > > But it's an inconsistency. > > To decisively argue 'inconsistency' as factual or not, versus us having > divergent opinions, you would have to supply a technical definition ;-) > The math definition of 'leading to a contradiction' in the sense of > being able to prove False is True, does not seem to apply here. > > However, > a) In common English, 'in' and 'contains', applied to strings of > characters (text), is understood as applying to substrings that appear > in the text. This is also true of many other programming languages. > 'Dictionary' contains 'diction'. This is even the basis of various word > games. > b) Python otherwise allows operators to vary in meaning for different > classes. > > In any case, back to your original question: the extension of meaning, > 'inconsistent' or not, was deliberated and adopted on the basis that the > usefulness of the extension would outweigh the confusion wrought by the > class-specific nature of the extension. (In other words, threads such > as this *were* anticipated ;-) I wasn't saying that the fact that the behavior of "in" for strings is inconsistent with the behavior for lists was a bad thing - I was just asking about the reason for it. (I also wasn't claiming that it was inconsistent with the common English usage of "in"...) People have pointed out that "in" for strings _can_ work that way, while (of course) "in" for lists had better not. That's fine. > Terry Jan Reedy -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird lambda rebinding/reassignment without me doing it
In article <[EMAIL PROTECTED]>, ssecorp <[EMAIL PROTECTED]> wrote: > I am never redefining the or reassigning the list when using validate > but since it spits the modified list back out that somehow means that > the modified list is part of the environment and not the old one. > i thought what happend inside a function stays inside a function > meaning what comes out is independent of what comes in. > Meaning if I want the list I send as a parameter to the function I > have to do x = func(x) and not just func(x) and x is magically what > comes out of func(). A function cannot modify the value of a global variable (unless it specifies "global"). It doesn't reassign anything. But in the functions below you're not reassigning a variable, you're _modifiying_ an object. A function _can_ modify an object you pass to it: >>> def DoesntReassign(x): ... x = 0 ... >>> def Modifies(x): ... x.append(0) ... >>> x=42 >>> DoesntReassign(x) >>> x 42 >>> x=[] >>> Modifies(x) >>> x [0] Hmm, look at this: >>> x=[] >>> id(x) 404296 >>> Modifies(x) >>> x [0] >>> id(x) 404296 'x' refers to exactly the same object before and after the call to Modifies. The function has _modified_ that object, but it hasn't redefined or reassigned anything. > Doesnt Python have closure or that isnt what this is about? > > > def validate(placed): > student = round(random.random()*401) > if student in placed: > return validate(placed) > else: > placed.append(student) > return student, placed > > def val(placed): > student = round(random.random()*401) > if student in placed: > return validate(placed) > else: > placed.append(student) > return student > > > > >>> g = lambda x:validate(x) > >>> l=[] > >>> for x in range(1,10): > g(l) > > > (141.0, [141.0]) > (19.0, [141.0, 19.0]) > (86.0, [141.0, 19.0, 86.0]) > (120.0, [141.0, 19.0, 86.0, 120.0]) > (76.0, [141.0, 19.0, 86.0, 120.0, 76.0]) > (262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0]) > (234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0]) > (74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0]) > (325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0]) > >>> g = lambda x:val(x) > >>> l=[] > >>> for x in range(1,10): > g(l) > > > 183.0 > 33.0 > 315.0 > 244.0 > 308.0 > 168.0 > 146.0 > 378.0 > 297.0 > >>> -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird lambda rebinding/reassignment without me doing it
In article <[EMAIL PROTECTED]>, Terry Reedy <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > In article > > <[EMAIL PROTECTED]>, > > ssecorp <[EMAIL PROTECTED]> wrote: > > > >> I am never redefining the or reassigning the list when using validate > >> but since it spits the modified list back out that somehow means that > >> the modified list is part of the environment and not the old one. > >> i thought what happend inside a function stays inside a function > >> meaning what comes out is independent of what comes in. > >> Meaning if I want the list I send as a parameter to the function I > >> have to do x = func(x) and not just func(x) and x is magically what > >> comes out of func(). > > > > A function cannot modify the value of a global variable > > Yes it can. > >>> a=[] > >>> def f(): > a.append('yes I can') > > >>> f() > >>> a > ['yes I can'] > > > (unless it specifies "global"). It doesn't reassign anything. > > The statement 'global a' would allow f to *rebind* the global *name* > 'a'. Aargh. That's exactly what I meant, sorry. > The word 'variable' should almost not be used in discussing Python > since it is often unclear whether it refers to a name (or collection > slot) or an object bound thereto. Indeed. Which is exactly why I included those snippets of code that you snipped, one of which does exactly what your snippet above does... you're probably right, "variable" is a bad idea, and "modify the value of a variable" is a very bad idea. The code doesn't "modify the value of the variable" in the sense that the value of the variable is a certain object, and after the function call the value is the same object. It does "modify the value of the variable" in the sense that the object which is the value of the variable has been modified. There's a problem here. Please note that this is not a criticism, and I don't really know what anyone could do about the problem. The problem is that if the reader is not accustomed to thinking explicitly about what's going on under the hood when code is executed he's going to have a hard time understanding the difference between "assigning a value to a variable" and "binding a name to an object". Once I realized that dicts rule everything this became clear to me, but for some time the discussions I saw on all this made no sense to me. Which is why I think it's a good idea to include examples illustrating what can and cannot be done, which is why I did that. I tend to suspect that the OP is at least as confused on the subtlties as I was back then (evidence below). > > But in the functions below you're not reassigning a variable, > > you're _modifiying_ an object. A function _can_ modify an > > object you pass to it: > > It can modify any mutable object it can access. > > >> Doesnt Python have closure or that isnt what this is about? > > Python does have closures. This is not about that. This is why I suspect what I say I suspect. He's thought that the word "closure" meant something like "local scope"... > >> def validate(placed): > >> student = round(random.random()*401) > >> if student in placed: > >> return validate(placed) > >> else: > >> placed.append(student) > >> return student, placed > > Delete this. It is redundant with the below. > > >> def val(placed): > >> student = round(random.random()*401) > >> if student in placed: > >> return validate(placed) > >> else: > >> placed.append(student) > >> return student > > I believe this is equivalent to > > def addval(placed): >while True: > student = round(random.random()*401) > if student not in placed: >break >placed.append(student) >return student > > While this avoids the indefinite recursion depth problem, it does not > avoid the indefinite time problem. Use random.shuffle, or write your > own version if doing this for practice. Also consider removing the > return statement unless you actually directly use the added value. It > is easier to remember that addval mutates 'placed' without the return. > > >>>>> g = lambda x:validate(x) > > This is doubly diseased. > > First, never write a 'name = lambda...' statement since it is equivalent > to a def statement
Re: Weird lambda rebinding/reassignment without me doing it
In article <[EMAIL PROTECTED]>, ssecorp <[EMAIL PROTECTED]> wrote: > >>> def mod(x,y): > return x.append(y) > > >>> mod([1,2],3) > >>> k=[1,2,3] > >>> k > [1, 2, 3] > >>> l = mod(k,4) > >>> l > >>> k > [1, 2, 3, 4] > >>> l > >>> k==l > False > >>> mod(k,5) > >>> k > [1, 2, 3, 4, 5] > >>> mod(l,4) > > Traceback (most recent call last): > File "", line 1, in > mod(l,4) > File "", line 2, in mod > return x.append(y) > AttributeError: 'NoneType' object has no attribute 'append' > >>> l > >>> l=k > >>> l > [1, 2, 3, 4, 5] > >>> i=mod(k,1) > >>> i > >>> > > same stuff but i dont find this intuitive. You need to read the docs. AList.append(x) does _not_ return AList with x appended. In fact it returns None, because it wants to be a "procedure" that doesn't return anything at all, but there is no such thing in Python; functions and methods that do not explicitly contain a "return" statement return None. So when you say "return x.append(a)" you're saying "return None", which explains the rest of it. You noticed that the second line of > >>> l = mod(k,4) > >>> l didn't print anything? That's because the first line set l to None. If you'd typed "print l" instead of just "l" you would have seen >>> l = mod(k,4) >>> l >>> None -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython code giving strange errors.
In article <[EMAIL PROTECTED]>, Mike Driscoll <[EMAIL PROTECTED]> wrote: > On Jul 13, 10:18 am, teh_sAbEr <[EMAIL PROTECTED]> wrote: > > I'm busy trying to learn wxPython, and i'm trying to run the following > > piece of code (its from the wxPyWiki tutorial): > > > > import wx > > [...] > > > > app = wx.PySimpleApp() > > frame = MainWindow(None, -1, "Sample editor") > > app.MainLoop() > >[...] > > This code works "as is" on Windows XP. However, I have gotten this > error when trying to run it from IDLE and I've heard that that can > happen in other Tkinter-based IDEs. So I've heard. Just for fun I tried running it in a wxPython-based shell - it worked fine. > Try running it from the command > line and I'll bet you won't get that error. > > Also, there's a great wxPython user's group you can join from the > official website: > > www.wxpython.org > > Mike -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Written in C?
In article <[EMAIL PROTECTED]>, Erik Max Francis <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > > I'm just learning about Python now and it sounds interesting. But I > > just read (on the Wiki page) that mainstream Python was written in C. > > That's what I was searching for: Python was written in what other > > language? > > > > See, my concern was something like: OK, if Python is so hot, then, > > hopefully someone is writing it in assembly language for each MPU chip > > out there. Otherwise, if, say, they've written it in C#, then it looks > > like the REAL, generally useful language to learn is C# and Python is > > akin to Visual Basic or something: a specialty languagewhereas > > REAL WORLD programmers who want to be generally useful go and learn > > C#. > > Psst. What language do you think the primary implementations of C# is > written in? I know, I know, call on me! Object Pascal, obviously. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
repr(string)
I've been saving data in a file with one line per field. Now some of the fields may become multi-line strings... I was about to start escaping and unescaping linefeeds by hand, when I realized that repr() and eval() should do. Hence the question: If s is a string, is repr(s) guaranteed not to contain line breaks? -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: repr(string)
In article <[EMAIL PROTECTED]>, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > > I've been saving data in a file with one line per field. > > Now some of the fields may become multi-line strings... > > > > I was about to start escaping and unescaping linefeeds > > by hand, when I realized that repr() and eval() should > > do. Hence the question: If s is a string, is repr(s) > > guaranteed not to contain line breaks? > > yes. > > just keep in mind that using eval() on untrusted data isn't a very good > idea. Right. This data comes from me, gets put into a file and then read by me. Someone _could_ corrupt that file, but someone who could do that could more easily just throw the machine out the window... > -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: repr(string)
In article <[EMAIL PROTECTED]>, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > David C. Ullrich skrev: > > >> just keep in mind that using eval() on untrusted data isn't a very good > >> idea. > > > > Right. This data comes from me, gets put into a file and then > > read by me. Someone _could_ corrupt that file, but someone who > > could do that could more easily just throw the machine out > > the window... > > and then your boss finds your program useful, and it's installed on a > shared server, and then the guys at the office in Eggkleiva wants a > copy, and then people start shipping save files via mail to keep things > synchronized, and then someone sets up a web service... ;-) Heh-heh. Good point, except that the idea that someone's going to find it useful is utterly implausible. Nobody but me has ever found a program I wrote useful. People think it's funny that I write little Python programs to do things I could just do in Excel or Open Office. (When I have some accounting/secretarial sort of thing to do doing it by hand in Python is one way to make it tolerably interesting. Easier to add new features - instead of trying to find an Excel way to do something like delete the smallest _two_ items in a list I just do it.) > -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: repr(string)
In article <[EMAIL PROTECTED]>, Peter Otten <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > > In article <[EMAIL PROTECTED]>, > > Fredrik Lundh <[EMAIL PROTECTED]> wrote: > > > >> David C. Ullrich wrote: > >> > >> > I've been saving data in a file with one line per field. > >> > Now some of the fields may become multi-line strings... > >> > > >> > I was about to start escaping and unescaping linefeeds > >> > by hand, when I realized that repr() and eval() should > >> > do. Hence the question: If s is a string, is repr(s) > >> > guaranteed not to contain line breaks? > >> > >> yes. > >> > >> just keep in mind that using eval() on untrusted data isn't a very good > >> idea. > > > > Right. This data comes from me, gets put into a file and then > > read by me. Someone _could_ corrupt that file, but someone who > > could do that could more easily just throw the machine out > > the window... > > You could also use a csv file with a single row. Excellent suggestion. I have a different point of view on all this than most of you guys (see reply to F). From my curious point of view csv was no fun anymore when csvlib got added to Python... > Peter -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: repr(string)
In article <[EMAIL PROTECTED]>, MRAB <[EMAIL PROTECTED]> wrote: > On Jul 23, 4:04 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote: > > I've been saving data in a file with one line per field. > > Now some of the fields may become multi-line strings... > > > > I was about to start escaping and unescaping linefeeds > > by hand, when I realized that repr() and eval() should > > do. Hence the question: If s is a string, is repr(s) > > guaranteed not to contain line breaks? > > > Might I suggest you use encode and decode instead? Ah, you certainly might! Seems exactly right, thanks. Many years ago I thought I had some idea of what was available in Python - these days it's full of all this neat stuff I never heard of... > >>> 'first line\nsecond line'.encode('string-escape') > 'first line\\nsecond line' > >>> _.decode('string-escape') > 'first line\nsecond line' > >>> u'first line\nsecond line'.encode('unicode-escape') > 'first line\\nsecond line' > >>> _.decode('unicode-escape') > u'first line\nsecond line' -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance and __getattr__
In article <[EMAIL PROTECTED]>, "Enrico" <[EMAIL PROTECTED]> wrote: > Hi there, > I have the following situation (I tryed to minimize the code to concentrate > on the issue): > > >>> class A(object): > def __getattr__(self, name): > print 'A.__getattr__' > if name == 'a': return 1 > raise AttributeError('%s not found in A' % name) > > >>> class B(object): > def __getattr__(self, name): > print 'B.__getattr__' > if name == 'b': return 1 > raise AttributeError('%s not found in B' % name) > > Both classes have a __getattr__ method. > Now I want to have a class that inherits from both so I write: > > >>> class C(B,A): > pass > > The problem arise when I try something like this: > >>> c=C() > >>> c.a > A.__getattr__ > 1 > >>> c.b > A.__getattr__ > > Traceback (most recent call last): > File "", line 1, in > c.b > File "", line 5, in __getattr__ > raise AttributeError('%s not found in A' % name) > AttributeError: b not found in A > > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > method of B but it seems that after A.__getattr__ fails the exception stops > the flow. So, if I did understand well, B.__getattr__ will be never called > "automatically". I don't know if this has a reason, if it is a design choice > or what else, any explanation is welcome. Well, it's simply the way it works. When you say C(A, B) then A is searched first for a given attribute and if A has no such attribute then B is searched. If you really want to do something like this then yes, you have to do something as below. I suspect that the people who feel expert enough to talk about what you should and shouldn't want are going to say that you shouldn't want something like this - with things set up the way you have them you really can't tell what's going to happen with c.__getattr__ unless you look at all the code in all the subclasses. > Since A and B are not written by me I can only work on C. The solution that > comes to my mind is to define a __getattr__ also in C and write something > like: > > >>> class C(A,B): > def __getattr__(self, name): > try: >return A.__getattr__(self, name) > except AttributeError: >return B.__getattr__(self, name) > > >>> c=C() > >>> c.a > A.__getattr__ > 1 > >>> c.b > A.__getattr__ > B.__getattr__ > 1 > > A better solution is welcome. > Many thanks, Enrico -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance and __getattr__
In article <[EMAIL PROTECTED]>, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Enrico a écrit : > > Hi there, > > I have the following situation (I tryed to minimize the code to concentrate > > on the issue): > > > >>>> class A(object): > > def __getattr__(self, name): > > print 'A.__getattr__' > > if name == 'a': return 1 > > raise AttributeError('%s not found in A' % name) > > > >>>> class B(object): > > def __getattr__(self, name): > > print 'B.__getattr__' > > if name == 'b': return 1 > > raise AttributeError('%s not found in B' % name) > > > > Both classes have a __getattr__ method. > > Now I want to have a class that inherits from both so I write: > > > >>>> class C(B,A): > > pass > > > > The problem arise when I try something like this: > >>>> c=C() > >>>> c.a > > A.__getattr__ > > 1 > >>>> c.b > > A.__getattr__ > > > > Traceback (most recent call last): > > File "", line 1, in > > c.b > > File "", line 5, in __getattr__ > > raise AttributeError('%s not found in A' % name) > > AttributeError: b not found in A > > That's what I would have expected. > > > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > > method of B but it seems that after A.__getattr__ fails the exception stops > > the flow. > > Indeed. You explicitely raise, so the lookup stops here. ??? Surely the reason the lookup stops there is that a __getattr__ was _found_. In the code below the lookup is not continuing, there's a _second_ lookup started by the request for super.__getattr__. > You'd need to > explicitely call on superclass instead to have B.__getattr__ called, ie: > > class A(object): > def __getattr__(self, name): > if name == 'a': > return 1 > return super(A, self).__getattr__(name) > > class B(object): > def __getattr__(self, name): > if name == 'b': > return 2 > return super(B, self).__getattr__(name) > > class C(A, B): > pass > -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
PIL (etc etc etc) on OS X
Decided to try to install PIL on my Mac (OS X.5). I know nothing about installing programs on Linux, nothing about building C programs, nothing about installing libraries, nothing about "fink", nothing about anything. Please insert question marks after every sentence: I saw a "BUILDME" with instructions "for lazy programmers". I did that. It seems that everything worked except a jpg library is missing. I read that I need to install libjpeg. I read that on OS X this is "usually" done using fink. Great: (i) The idea of installing fink scares me, for no reason I could name. There's no way that's going to confuse the rest of Darwin, right? (ii) When I look at the fink website I see a list of supported libraries, not including libjpeg. I hate messing with things that I don't understand at _all_... Thanks for any advice or comments. DU. ** PIL 1.1.6 BUILD SUMMARY version 1.1.6 platform darwin 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] --- TKINTER support ok *** JPEG support not available --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok To add a missing option, make sure you have the required library, and set the corresponding ROOT variable in the setup.py script. To check the build, run the selftest.py script. 0-1d-4f-fc-28-d:Imaging-1.1.6 dullric$ python selftest.py * Failure in example: _info(Image.open("Images/lena.jpg")) from line #24 of selftest.testimage Exception raised: Traceback (most recent call last): File "./doctest.py", line 499, in _run_examples_inner exec compile(source, "", "single") in globs File "", line 1, in File "./selftest.py", line 22, in _info im.load() File "PIL/ImageFile.py", line 180, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: mapping a string to an instancemethod
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote: > The following bit of code will allow an instance member to > be called by reference. How can I map a string (e.g. > "hello1" or "Foo.hello1" to a the instance member? > > class Foo: > def hello1(self, p): > print 'hello1', p > def hello2(self, p): > print 'hello2', p > def dispatch(self, func, p): > func(self,p) > > f=Foo() > f.dispatch(Foo.hello1, 23) > f.dispatch(Foo.hello1, 24) > > f.dispatch_as_string("hello1", 23) ## this is what I want to do. Do what's below. Then learn about *args to make a version that works with variable numbers of parameters... class Foo: def hello1(self, p): print 'hello1', p def hello2(self, p): print 'hello2', p def dispatch(self, func, p): func(self,p) def dispatch_as_string(self, funcname, p): getattr(self, funcname)(p) f = Foo() f.dispatch_as_string('hello1', 'world') > Many TIA and apologies if this is a FAQ, I googled and couldn't > find the answer. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
In article <[EMAIL PROTECTED]>, Irmen de Jong <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > Decided to try to install PIL on my Mac (OS X.5). > > > > I know nothing about installing programs on Linux, > > nothing about building C programs, nothing about > > installing libraries, nothing about "fink", nothing > > about anything. Please insert question marks after > > every sentence: > > Not needed. > Just download a precompiled installation package from > http://pythonmac.org/packages/ Lovely - thanks. > I just installed PIL 1.1.6 two days ago, using the Python 2.5 package from > this site :) > (OS X 10.4.11 on a PPC mac mini) > > --irmen -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
>From the other reply it seems I may not need to worry about any of this. Otoh I've had issues with pythonmac versus OSX versions, etc, in the past. Just in case, also in the spirit of that curious idea that learning things is good: First, it occurred to me that I've got wxPython installed and it includes jpeg support. I don't suppose that means that wxPython has already put a libjpeg somewhere and I just need to tell PIL where it is? Regardless, about your suggestions below (again, any assertions here are really questions): Presumably jibjpeg needs to be unzipped into its own directory, or configure/make etc wouldn't be able to figure out what I want to make. Presumably that happens automatically when I unzip it. Then after I do the configure/make/sudo make install will libjpeg automatically be in some standard place? If not, what's a good choice of standard place to put it, and how do I put it there? (If I start here then it will unzip to there, and then after I make it there it will be installed in this third place, which is where I want it.) Thanks. Sorry to be so dumb - yes, it's perfectly reasonable for eff to assume that people using PIL are programmers. With a "new thing" in, say, Python I'd just try something and then figure out what to try next to make it work - I don't want to take that approach here lest I re-make part of Darwin or something. Once many years ago I learned a new thing: Attempting to run a sufficiently invalid DOS exe could cause physical damage to a hard drive... that wasn't the only thing I learned that day. (Probably won't get back to this til Monday, btw, in case you say something and I don't seem interested.) DU. In article <[EMAIL PROTECTED]>, Kevin Walzer <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > Decided to try to install PIL on my Mac (OS X.5). > > OK, sounds good. > > > > I know nothing about installing programs on Linux, > > nothing about building C programs, nothing about > > installing libraries, nothing about "fink", nothing > > about anything. Please insert question marks after > > every sentence: > > For the record, OS X isn't Linux--it's a variant of BSD Unix. Similar, > but no identical, to Linux. > > > > > I saw a "BUILDME" with instructions "for lazy programmers". > > I did that. It seems that everything worked except a > > jpg library is missing. > > OK. > > > > > I read that I need to install libjpeg. I read that on OS X > > this is "usually" done using fink. Great: > > > > (i) The idea of installing fink scares me, for no reason > > I could name. There's no way that's going to confuse the > > rest of Darwin, right? > > You don't really need Fink just to install libjpeg. You do need the > developer tools (Xcode) installed, otherwise you can't build any > software at all. > > Libjpeg can be downloaded from http://www.ijg.org/. Download it, > untar/unzip it. Fire up terminal, cd to the libjpeg directory, and type > these commands: > > configure > make > sudo make install > > That should get libjpeg built and installed. > > > > > (ii) When I look at the fink website I see a list of > > supported libraries, not including libjpeg. > > So don't worry about Fink. > > > > > I hate messing with things that I don't understand at _all_... > > Well, that's understandable, but this is your chance to learn something > new. > > > > Thanks for any advice or comments. > > > > DU. > > > --Kevin -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
Thanks for the hand-holding. DU. In article <[EMAIL PROTECTED]>, Kevin Walzer <[EMAIL PROTECTED]> wrote: > > [more about installing libjpeg...] -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
Just as well that the message sent earlier today seems to have been lost... Ok. Read your instructions on libjpeg. Read some of the install.doc. ./configure, fine. make, fine. "make test", fine. So I said "sudo make install" and this happened: 0-1d-4f-fc-28-d:jpeg-6b dullric$ sudo make install Password: /usr/bin/install -c cjpeg /usr/local/bin/cjpeg /usr/bin/install -c djpeg /usr/local/bin/djpeg /usr/bin/install -c jpegtran /usr/local/bin/jpegtran /usr/bin/install -c rdjpgcom /usr/local/bin/rdjpgcom /usr/bin/install -c wrjpgcom /usr/local/bin/wrjpgcom /usr/bin/install -c -m 644 ./cjpeg.1 /usr/local/man/man1/cjpeg.1 /usr/bin/install -c -m 644 ./djpeg.1 /usr/local/man/man1/djpeg.1 /usr/bin/install -c -m 644 ./jpegtran.1 /usr/local/man/man1/jpegtran.1 /usr/bin/install -c -m 644 ./rdjpgcom.1 /usr/local/man/man1/rdjpgcom.1 /usr/bin/install -c -m 644 ./wrjpgcom.1 /usr/local/man/man1/wrjpgcom.1 Surely that means it was installed in /usr/local/bin, right? So I start over with PIL. It says I should "python setup.py build_ext -i". So I do: 0-1d-4f-fc-28-d:Imaging-1.1.6 dullric$ python setup.py build_ext -i running build_ext --- using frameworks at /System/Library/Frameworks PIL 1.1.6 BUILD SUMMARY version 1.1.6 platform darwin 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] --- TKINTER support ok *** JPEG support not available --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok To add a missing option, make sure you have the required library, and set the corresponding ROOT variable in the setup.py script. So I look in setup.py and I find this: # Library pointers. # # Use None to look for the libraries in well-known library locations. # Use a string to specify a single directory, for both the library and # the include files. Use a tuple to specify separate directories: # (libpath, includepath). Examples: # # JPEG_ROOT = "/home/libraries/jpeg-6b" # TIFF_ROOT = "/opt/tiff/lib", "/opt/tiff/include" # # If you have "lib" and "include" directories under a common parent, # you can use the "libinclude" helper: # # TIFF_ROOT = libinclude("/opt/tiff") FREETYPE_ROOT = None JPEG_ROOT = None #JPEG_ROOT = "/usr/local/bin" I try it both ways, with JPEG_ROOT=None and JPEG_ROOT = "/usr/local/bin" - same result both times, "JPEG support not available". Any thoughts? Later in setup.py it says if find_library_file(self, "jpeg"): feature.jpeg = "jpeg" elif sys.platform == "win32" and find_library_file(self, "libjpeg"): feature.jpeg = "libjpeg" # alternative name Not knowing exactly what "find_library_file" does I couldn't say, but it almost sounds like it's looking for a file named "jpeg". The summary from the jpeg install looks like it didn't install any such file. Maybe "jpeg" should be the name of one of those files that did get installed? This _is_ fun. Eech. DU. -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
In article <[EMAIL PROTECTED]>, Kevin Walzer <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > Just as well that the message sent earlier today > > seems to have been lost... > > > > Ok. Read your instructions on libjpeg. Read some > > of the install.doc. ./configure, fine. make, fine. > > "make test", fine. So I said "sudo make install" > > and this happened: > > > > 0-1d-4f-fc-28-d:jpeg-6b dullric$ sudo make install > > Password: > > /usr/bin/install -c cjpeg /usr/local/bin/cjpeg > > /usr/bin/install -c djpeg /usr/local/bin/djpeg > > /usr/bin/install -c jpegtran /usr/local/bin/jpegtran > > /usr/bin/install -c rdjpgcom /usr/local/bin/rdjpgcom > > /usr/bin/install -c wrjpgcom /usr/local/bin/wrjpgcom > > /usr/bin/install -c -m 644 ./cjpeg.1 /usr/local/man/man1/cjpeg.1 > > /usr/bin/install -c -m 644 ./djpeg.1 /usr/local/man/man1/djpeg.1 > > /usr/bin/install -c -m 644 ./jpegtran.1 /usr/local/man/man1/jpegtran.1 > > /usr/bin/install -c -m 644 ./rdjpgcom.1 /usr/local/man/man1/rdjpgcom.1 > > /usr/bin/install -c -m 644 ./wrjpgcom.1 /usr/local/man/man1/wrjpgcom.1 > > > > Surely that means it was installed in /usr/local/bin, right? > > > > So I start over with PIL. It says I should "python setup.py build_ext > > -i". > > So I do: > > > > 0-1d-4f-fc-28-d:Imaging-1.1.6 dullric$ python setup.py build_ext -i > > running build_ext > > --- using frameworks at /System/Library/Frameworks > > > > PIL 1.1.6 BUILD SUMMARY > > > > version 1.1.6 > > platform darwin 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > > [GCC 4.0.1 (Apple Inc. build 5465)] > > > > --- TKINTER support ok > > *** JPEG support not available > > --- ZLIB (PNG/ZIP) support ok > > --- FREETYPE2 support ok > > > > To add a missing option, make sure you have the required > > library, and set the corresponding ROOT variable in the > > setup.py script. > > > > So I look in setup.py and I find this: > > > > # Library pointers. > > # > > # Use None to look for the libraries in well-known library locations. > > # Use a string to specify a single directory, for both the library and > > # the include files. Use a tuple to specify separate directories: > > # (libpath, includepath). Examples: > > # > > # JPEG_ROOT = "/home/libraries/jpeg-6b" > > # TIFF_ROOT = "/opt/tiff/lib", "/opt/tiff/include" > > # > > # If you have "lib" and "include" directories under a common parent, > > # you can use the "libinclude" helper: > > # > > # TIFF_ROOT = libinclude("/opt/tiff") > > > > FREETYPE_ROOT = None > > JPEG_ROOT = None > > #JPEG_ROOT = "/usr/local/bin" > > > > How about "/usr/local/lib" ? It's looking for a dylib (library file), > not an executable (bin). Thanks. I'd already tried that (a much longer post detaining everything I'd tried got lost - you saw the abbreviated version, sorry). I noticed there are no new files in /usr/local/lib. So I looked at the libjpeg install.doc and saw this: * If you want to build libjpeg as a shared library, say ./configure --enable-shared To get both shared and static libraries, say ./configure --enable-shared --enable-static Note that these switches invoke GNU libtool to take care of system-dependent shared library building methods. If things don't work this way, please try running configure without either switch; that should build a static library without using libtool. (What I want here is a static library?) When I add either or both of those switches it says 0-1d-4f-fc-28-d:jpeg-6b dullric$ make ./libtool --mode=compile gcc -O2 -I. -c ./jcapimin.c make: ./libtool: Command not found make: *** [jcapimin.lo] Error 127 -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
In article <[EMAIL PROTECTED]>, Irmen de Jong <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > Just as well that the message sent earlier today > > seems to have been lost... > > > > Ok. Read your instructions on libjpeg. Read some > > of the install.doc. ./configure, fine. make, fine. > > "make test", fine. So I said "sudo make install" > > and this happened: > > > > 0-1d-4f-fc-28-d:jpeg-6b dullric$ sudo make install > > Password: > [...] > > I had to do the following to build and install it in a way such that PIL > would recognise > it. But it does now, without changing anything in PIL's setup files. > > $ cd jpeg-6b/ > $ ln -s `which glibtool` libtool > $ export MACOSX_DEPLOYMENT_TARGET=10.4 > $ ./configure --enable-shared --enable-static --host=powerpc > $ make > $ sudo make install Thanks - that gets me closer: I'd already found out about the --enable-* switches, but when I tried them it complained it couldn't find ./libtool. I _guessed_ host should be intel I changed the 10.4 to 10.5 and did this: $ ln -s `which glibtool` libtool $ export MACOSX_DEPLOYMENT_TARGET=10.4 $ ./configure --enable-shared --enable-static --host=intel $ make $ sudo make install That fixed the complaints about no ./libtool, great. Then I went back to PIL. The setup.py reported that everything was great, including JPEG. And then selftest.py said it couldn't find a jpeg decoder... 0-1d-4f-fc-28-d:Imaging-1.1.6 dullric$ python selftest.py * Failure in example: _info(Image.open("Images/lena.jpg")) from line #24 of selftest.testimage Exception raised: Traceback (most recent call last): File "./doctest.py", line 499, in _run_examples_inner exec compile(source, "", "single") in globs File "", line 1, in File "./selftest.py", line 22, in _info im.load() File "PIL/ImageFile.py", line 180, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. > > (note that I have a PPC mac so the host parameter may not be correct for your > system) > --irmen -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list