Re: Code formatting question: conditional expression
"Nicola Larosa (tekNico)" writes: > Nicola Larosa wrote: > > Here's my take: > > > > excessblk = Block(total - P.BASE, srccol, > > carry_button_suppress=True > > ) if total > P.BASE else None > > Oops, it got shortened out: line longer than 72 chars, acceptable in > code, but not in email. I'll try again. Fine in email; just munged on your behalf (and probably without your knowledge) by your email service provider. If you don't want that happening, it's probably best to avoid Google Mail. -- \ “I wish a robot would get elected president. That way, when he | `\came to town, we could all take a shot at him and not feel too | _o__) bad.” —Jack Handey | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Object Reference question
On Tuesday 25 August 2009 21:32:09 Aahz wrote: > In article , > > Hendrik van Rooyen wrote: > >On Friday 21 August 2009 08:07:18 josef wrote: > >> My main focus of this post is: "How do I find and use object reference > >> memory locations?" > >> > a = [1,2,3,4] > id(a) > > > >8347088 > > Of course, that doesn't actually allow you to do anything... Well - if the OP is the sort of person who likes juggling with running chainsaws, then he can look up a thread I started about a thing I called a "can", which enabled you to get the object back from a string representation of the ID. I did not want to open that "can" of worms again, and I thought that answering half a question was better than nothing... *weg* - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: your favorite debugging tool?
Dennis Lee Bieber writes: > My normal debug technique is wolf fencing* (eg; print statements) That method was formerly completely automated on the web: http://www.st.cs.uni-saarland.de/askigor/faq.php It was amazing. Further info is here: http://www.st.cs.uni-saarland.de/dd/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
Nicola Larosa wrote: > Here's my take: > > excessblk = Block(total - P.BASE, srccol, > carry_button_suppress=True > ) if total > P.BASE else None Oops, it got shortened out: line longer than 72 chars, acceptable in code, but not in email. I'll try again. If the first line is too long, I would write it like this: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None If not, like this: excessblk = Block(total - P.BASE, srccol, cbs=True ) if total > P.BASE else None If the condition or the last value were too long to make it all fit on two lines, then it would probably best to revert to a plain "if" statement. -- Nicola Larosa - http://www.tekNico.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
A few additional comments on top of what others have said. On Aug 26, 11:09 am, Phil wrote: > I've seen lots of web sites explaining everything, but for whatever > reason I seem to not be picking something up. > I am a graphical person, which is probably the reason I haven't found > my answer. > May somebody please confirm if my diagram accurately represents the > stack, generally speaking. > > http://i26.tinypic.com/1fe82x.png > > Even if that is the case, I'm having a hard time understanding the > differences. I guess wsgiref has absolutely nothing to do with FCGI/ > SCGI/CGI and simply receives and responds to HTTP requests following > the WSGI specification? Technically it receives and responses to request based on HTTP specification, not WSGI specification. The underlying HTTP server translates to and communicates with a Python web application using the WSGI interface. > Does it just spawn a new thread for each > request? If so, then how is this any different than a production > server with FCGI? I would describe there as being four major ways that WSGI can be hosted. These are: 1. Custom build HTTP/WSGI server written in Python. Production quality examples are CherryPy WSGI server and Paste HTTP server. You shouldn't use wsgiref for anything but very simple stuff. 2. Per request process execution by way of CGI and a CGI/WSGI adapter. This could be under Apache or any other web server which supports CGI. 3. Module that embeds Python interpreter into a C based web server. Example are mod_wsgi and mod_python for Apache. Note that mod_python would infrequently be used to host WSGI and doesn't include its own WSGI adapter. These days mod_wsgi for Apache would be used. Processes in this would be persistent. 4. Module in a web server that allows one to communicate using a custom protocol with a separate persistent web application process hosting the web application through a WSGI interface. This convers FASTCGI, SCGI and AJP. The mod_wsgi module for Apache has a hybrid mode which work in a similar way but uses an internal protocol. Amongst these, there are many variations as far as number of process and threads. For a bit of discussion about this in relation to mod_wsgi read: http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading > The way I am understanding the 'Production' side of that picture is > that the web server (eg. lighttpd) creates a single FCGI process. FASTCGI isn't restricted to a single process, nor single threading. Whether a particular implementation allows for the variations depends on the implementation. > The > FCGI process is actually the entry point of the Framework/Application > which sets up Flup's WSGIServer, being the interface between FCGI and > the Framework/Application? What I mean is, it is just the code that > the web server loads to start with, example... > from flup.server.fcgi import WSGIServer > from app import application > WSGIServer(application).run() > ... Then for each HTTP request, Flup's WSGIServer creates a new thread > to handle the request? > > As I've read elsewhere, "These days, FastCGI is never used directly. Even back in time, I don't think it was really ever used as a generic interface that people worked with directly, there was always a more usable layer built on top of it. > Just like mod_python it is only used for the deployment of WSGI > applications. The mod_python module isn't used just for WSGI applications and is probably rarely used for them. This is because mod_python has its own interface for building web applications. It also has abilities to hook into Apache request handling phases, meaning it can do more than host a a content handler/web application. > As far as I understand, the main (or only?) reasoning > for this is because WSGI makes Python applications easier to deploy > without having to worry about whether using FCGI/SCGI/CGI. WSGI provides for portability, it isn't necessarily easier to use than mod_python. > What would be involved to run Python on the web using FCGI without > WSGI? I can feel the flames already. No, you really don't want to do that. > This isn't the only reason I want > to know, but one reason is that I want to use Python 3.1 and as I > understand, this will have to wait for the WSGI 2.0 specification to > ensure time isn't wasted. Then look at mod_wsgi. It already has support for Python 3.X. Some aspects of how it implements WSGI 1.0 may change, but will not be too much and details are being sorted out in the back rooms as we speak. See: http://code.google.com/p/modwsgi/wiki/ChangesInVersion0300 The other option is CherryPy WSGI server as that is close to a Python 3.X release as well, as I perceive it. I wouldn't bother waiting for WSGI 2.0. That is more of a pipe dream. There will be an updated WSGI 1.0 for Python 3.0. Graham > I apologize if the questions are ridiculous. I've just recently got > into web programming and it seems that in order for me to use Python, >
PyObject_CallFunction and writable memory
I'm working a patch to a hex editor (frhed) written in c++ so it can load python scripts. Internally the c++ code has a unsigned char * of possibly serveral hundred megs which I want to send into the python code to modify.What is the best way to send the unsigned char * as writable memory into the python code, so I don't have to duplicate the memory in order to return a modified copy? I'm currently using "PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to send an immutable string but I haven't seen what I need to set in the format string which makes the data writable to python.The solution can be for either python 2.6 or 3.1. Thanks, Christopher -- http://mail.python.org/mailman/listinfo/python-list
Re: break unichr instead of fix ord?
wrote in message news:2ad21a79-4a6c-42a7-8923-beb304bb5...@v20g2000yqm.googlegroups.com... In Python 2.5 on Windows I could do [*1]: # Create a unicode character outside of the BMP. >>> a = u'\U00010040' # On Windows it is represented as a surogate pair. >>> len(a) 2 >>> a[0],a[1] (u'\ud800', u'\udc40') # Create the same character with the unichr() function. >>> a = unichr (65600) >>> a[0],a[1] (u'\ud800', u'\udc40') # Although the unichr() function works fine, its # inverse, ord(), doesn't. >>> ord (a) TypeError: ord() expected a character, but string of length 2 found On Python 2.6, unichr() was "fixed" (using the word loosely) so that it too now fails with characters outside the BMP. >>> a = unichr (65600) ValueError: unichr() arg not in range(0x1) (narrow Python build) Why was this done rather than changing ord() to accept a surrogate pair? Does not this effectively make unichr() and ord() useless on Windows for all but a subset of unicode characters? Switch to Python 3? x='\U00010040' import unicodedata unicodedata.name(x) 'LINEAR B SYLLABLE B025 A2' ord(x) 65600 hex(ord(x)) '0x10040' unicodedata.name(chr(0x10040)) 'LINEAR B SYLLABLE B025 A2' ord(chr(0x10040)) 65600 print(ascii(chr(0x10040))) '\ud800\udc40' -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Division and right shift in python
On Tue, Aug 25, 2009 at 8:40 PM, Mark Tolonen wrote: > > "Cevahir Demirkiran" wrote in message > news:3f74e020908251648k7b391a09g78b155507b2f2...@mail.gmail.com... >> >> Hi, >> >> I would like to do a floor division by a power of 2 in python to make it >> faster than / (modular division in 2.x). >> However, it is slower. >> What is the reason of that? >> I checked them via: >> >> def f2(x,n): >> t1 = clock() >> r = x/pow(2,n) >> t2 = clock() >> print (t2-t1) >> print r >> t2 = clock() >> r = x>>n >> t3 = clock() >> print (t3-t2) >> print r >> > > It's not slower on my system, but note the inconsistent results also: > f2(1024,5) > > 3.47396033483e-06 > 32 > 2.19077375482e-06 > 32 f2(1024,5) > > 4.84135603429e-06 > 32 > 3.08499440393e-06 > 32 f2(1024,5) > > 4.6782844052e-06 > 32 > 3.77604384028e-06 > 32 > > Time it with timeit... > > C:\>python -m timeit -n 1000 -s x=1024 "x>>5" > 1000 loops, best of 3: 0.113 usec per loop > > C:\>python -m timeit -n 1000 -s x=1024 "x/pow(2,5)" > 1000 loops, best of 3: 0.468 usec per loop > > Right-shift is over 4x faster. Adjusting for not having to lookup the name "pow", right shift is still faster, but only slightly. ch...@morpheus ~ $ python -m timeit -n 1000 -s x=1024 "x/pow(2,5)" 1000 loops, best of 3: 0.318 usec per loop ch...@morpheus ~ $ python -m timeit -n 1000 -s x=1024 "x/(2**5)" 1000 loops, best of 3: 0.0973 usec per loop ch...@morpheus ~ $ python -m timeit -n 1000 -s x=1024 "x>>5" 1000 loops, best of 3: 0.0885 usec per loop Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
On Aug 26, 1:17 pm, alex23 wrote: > Phil wrote: > > My interest in Python 3.1 was actually to develop a framework. Again, > > I can feel the flames. :) I understand there are enough frameworks but > > I actually have no applications that I wish to develop. > > No offense intended, but that's probably the worst approach to take. > > Frameworks created for the sake of creating a framework, as opposed to > those written to meet a defined need, tend to be the worst examples of > masturbatory coding. I would in part actually disagree with that. The problem with people creating frameworks to meet some defined need is that they often implement only just enough of that framework to meet that need and nothing more. End result is that the framework is more often than not ever fleshed out enough to be of much use to anyone else. Its existence though just pollutes the Internet with more crap that one has to wade through. Since there is already a plethora of good frameworks out there, if writing an application, you are better of using one of the existing frameworks. If interested in working at the framework level, you would still be much better off looking at the existing frameworks, first learn how they work and then consider contributing to them, rather than implementing your own. For some related reading, see: http://lucumr.pocoo.org/2009/7/30/nih-in-the-wsgi-world As far as low level framework (or anti frameworks), suggest looking at Werkzeug, Paste/Pylons and bobo. I'll comment more on original message later. Graham -- http://mail.python.org/mailman/listinfo/python-list
Re: Division and right shift in python
"Cevahir Demirkiran" wrote in message news:3f74e020908251648k7b391a09g78b155507b2f2...@mail.gmail.com... Hi, I would like to do a floor division by a power of 2 in python to make it faster than / (modular division in 2.x). However, it is slower. What is the reason of that? I checked them via: def f2(x,n): t1 = clock() r = x/pow(2,n) t2 = clock() print (t2-t1) print r t2 = clock() r = x>>n t3 = clock() print (t3-t2) print r It's not slower on my system, but note the inconsistent results also: f2(1024,5) 3.47396033483e-06 32 2.19077375482e-06 32 f2(1024,5) 4.84135603429e-06 32 3.08499440393e-06 32 f2(1024,5) 4.6782844052e-06 32 3.77604384028e-06 32 Time it with timeit... C:\>python -m timeit -n 1000 -s x=1024 "x>>5" 1000 loops, best of 3: 0.113 usec per loop C:\>python -m timeit -n 1000 -s x=1024 "x/pow(2,5)" 1000 loops, best of 3: 0.468 usec per loop Right-shift is over 4x faster. -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
On Aug 25, 11:17 pm, alex23 wrote: > Phil wrote: > > My interest in Python 3.1 was actually to develop a framework. Again, > > I can feel the flames. :) I understand there are enough frameworks but > > I actually have no applications that I wish to develop. > > No offense intended, but that's probably the worst approach to take. > > Frameworks created for the sake of creating a framework, as opposed to > those written to meet a defined need, tend to be the worst examples of > masturbatory coding. No offense taken. I understand your concern. I actually do have some important design decisions I wish to meet. It has sort of been a process of evaluating the things I love and hate most from existing frameworks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
Phil wrote: > My interest in Python 3.1 was actually to develop a framework. Again, > I can feel the flames. :) I understand there are enough frameworks but > I actually have no applications that I wish to develop. No offense intended, but that's probably the worst approach to take. Frameworks created for the sake of creating a framework, as opposed to those written to meet a defined need, tend to be the worst examples of masturbatory coding. -- http://mail.python.org/mailman/listinfo/python-list
Re: web frameworks that support Python 3
On Aug 26, 12:19 pm, exar...@twistedmatrix.com wrote: > On 01:41 am, a...@pythoncraft.com wrote: > > > > > > >In article > >, > >Graham Dumpleton wrote: > >>On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: > > >>>In any case, there is bottle [1], which provides a *very minimal* > >>>framewo= > >>rk > >>>for WSGI web development. =A0Don't expect too much, it is really > >>>small, a= > >>nd > >>>doesn't do much more than routing and minimal templating. > > >>>However, it is the only Python-3-compatible web framework I know of. > > >>>[1]http://bottle.paws.de/page/start > > >>There is one big flaw with your claim. That is the there is no WSGI > >>specification for Python 3.0 as yet. Anything that claims to work with > >>WSGI and Python 3.0 is just a big guess as far as how WSGI for Python > >>3.0 may work. > > >Perhaps you meant "library" instead of "specification"? > > He meant specification. > > Python 3.x is different enough from any Python 2.x release that PEP 333 > no longer completely makes sense. It needs to be modified to be > applicable to Python 3.x. > > So, in the sense that there is no written down, generally agreed upon > specification for what WSGI on Python 3.x means, there is no... > specification. > > There is, however, apparently, a library. ;) If you are talking about wsgiref then that was somewhat broken in Python 3.0. In Python 3.1 it works for some definition of works. The problem again being that since WSGI specification hasn't been updated for Python 3.X, that how it works will likely not match what the specification may eventually say. This will become more and more of a problem if WSGI specification isn't updated. At the moment the discussion is going around in circles, although, if I put my optimistic face on, I would say it is a slow inward spiral. Not quite a death spiral at least. Graham -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
Thank you for the helpful and timely response. My interest in Python 3.1 was actually to develop a framework. Again, I can feel the flames. :) I understand there are enough frameworks but I actually have no applications that I wish to develop. I enjoy developing these kinds of things from scratch as a learning experience. I've been doing fine with 2.x and WSGI, even without understanding half of this stuff. It is actually my first Python project. Haha. I just have my own design philosophies that I wish to experiment with. Python 3.x just makes everything nicer with UNICODE, etc. Although you've been helpful with almost all of the mentioned concerns, I am still looking for more details on some of the questions I've asked. So, if others stumble upon this post, feel free to contribute further. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: web frameworks that support Python 3
On 01:41 am, a...@pythoncraft.com wrote: In article , Graham Dumpleton wrote: On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: In any case, there is bottle [1], which provides a *very minimal* framewo= rk for WSGI web development. =A0Don't expect too much, it is really small, a= nd doesn't do much more than routing and minimal templating. However, it is the only Python-3-compatible web framework I know of. [1]http://bottle.paws.de/page/start There is one big flaw with your claim. That is the there is no WSGI specification for Python 3.0 as yet. Anything that claims to work with WSGI and Python 3.0 is just a big guess as far as how WSGI for Python 3.0 may work. Perhaps you meant "library" instead of "specification"? He meant specification. Python 3.x is different enough from any Python 2.x release that PEP 333 no longer completely makes sense. It needs to be modified to be applicable to Python 3.x. So, in the sense that there is no written down, generally agreed upon specification for what WSGI on Python 3.x means, there is no... specification. There is, however, apparently, a library. ;) Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with arrays
Stephen Fairchild wrote: Philip Semanchuk wrote: On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: Hello! I'm working on an exercise wherein I have to write a Guess The Number game, but it's the computer who's guessing MY number. I can get it to work, but there's one obvious problem: the computer generates random numbers until one of them corresponds to my number, but it will often generate one number (eg. 4) numerous times, meaning it doesn't know that this number is invalid. What I mean is, it will sometimes use 37 tries to guess a number out of 1 - 9, which makes no sense, since it should only take 9 tries, at most. I was trying to find a way to make a dynamic list of all the numbers the computer generates in the loop and then make it re-generate the number if the previous number is present in the list, so it doesn't keep on generating 4 (as an example). I don't know if that makes sense... Basically, we humans know that once something is incorrect, there's no point in trying to use it as the answer next time, because we already know it's incorrect. How do I go about coding this in Python? I'm still quite new to the language so any help will be appreciated... One cheap way to do it (not necessarily efficient) is to make a list of your possible guesses (e.g. range(1,10)), use random.shuffle() to put them in random order and then run through the guesses one at a time. import random import time l = range(1, 10) while l: print l.pop(random.randint(0, len(l) - 1)) time.sleep(2) While both of these will work well, I'd point out that a direct translation of your question is to use a set. Define an empty set, and each time you try a number unsuccessfully, add it to the set. Then just use while x in myset: x = newguess() to find the next guess. This approach isn't as efficient, but it's a useful paradigm to understand. A separate question is whether the human is supposed to tell the computer whether the guess is high or low. If so, you can eliminate many numbers on each guess. For example, suppose the solution is 8. A guess of 5 would say "too low." Then you'd cross off now only 5 but 1-4 as well. With this change the best solution changes from a random shuffle to a binary search. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: break unichr instead of fix ord?
Jan Kaliszewski wrote: Are you sure, you couldn't have UCS-4-compiled Python distro for Windows?? :-O Nope, Windows require UCS-2 builds. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on the Web
On 2009-08-25 20:09 PM, Phil wrote: I've seen lots of web sites explaining everything, but for whatever reason I seem to not be picking something up. I am a graphical person, which is probably the reason I haven't found my answer. May somebody please confirm if my diagram accurately represents the stack, generally speaking. http://i26.tinypic.com/1fe82x.png Even if that is the case, I'm having a hard time understanding the differences. I guess wsgiref has absolutely nothing to do with FCGI/ SCGI/CGI and simply receives and responds to HTTP requests following the WSGI specification? Correct. Does it just spawn a new thread for each request? No, it is single-threaded. If so, then how is this any different than a production server with FCGI? The way I am understanding the 'Production' side of that picture is that the web server (eg. lighttpd) creates a single FCGI process. The FCGI process is actually the entry point of the Framework/Application which sets up Flup's WSGIServer, being the interface between FCGI and the Framework/Application? What I mean is, it is just the code that the web server loads to start with, example... from flup.server.fcgi import WSGIServer from app import application WSGIServer(application).run() ... Then for each HTTP request, Flup's WSGIServer creates a new thread to handle the request? Something like that, yes. As I've read elsewhere, "These days, FastCGI is never used directly. Just like mod_python it is only used for the deployment of WSGI applications." As far as I understand, the main (or only?) reasoning for this is because WSGI makes Python applications easier to deploy without having to worry about whether using FCGI/SCGI/CGI. Yes, that is the primary reason for WSGI, in my mind. There are other things like the composability of applications, but the decoupling of application authoring from deployment is the sine qua non, in my opinion. What would be involved to run Python on the web using FCGI without WSGI? I can feel the flames already. This isn't the only reason I want to know, but one reason is that I want to use Python 3.1 and as I understand, this will have to wait for the WSGI 2.0 specification to ensure time isn't wasted. I am willing to bet that the FCGI libraries haven't been upgraded to Python 3.x, either. I suspect that the most 3.x-updating work will be going into WSGI and the adapters. E.g. http://www.saddi.com/software/news/archives/64-Dabbling-in-Python-3.0.html You may want to rethink the Python 3.x requirement, though. It will probably be much less a waste of your time to write your app using a framework like Django or Pylons on Python 2.x and then upgrade to Python 3.x when they do. I apologize if the questions are ridiculous. I've just recently got into web programming and it seems that in order for me to use Python, I need a deep understanding of web servers, HTTP, FCGI, etc. I have more questions but they go more off topic, so I will save it for another thread, another day. Knowing something about HTTP will certainly help get into the right mindset to know what limitations and capabilities web apps can have. Typically, though, you use a framework that abstracts most of this stuff away from you. You usually only need to delve into the details in very specific circumstances. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: web frameworks that support Python 3
In article , Graham Dumpleton wrote: >On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: >> >> In any case, there is bottle [1], which provides a *very minimal* framewo= >rk >> for WSGI web development. =A0Don't expect too much, it is really small, a= >nd >> doesn't do much more than routing and minimal templating. >> >> However, it is the only Python-3-compatible web framework I know of. >> >> [1]http://bottle.paws.de/page/start > >There is one big flaw with your claim. That is the there is no WSGI >specification for Python 3.0 as yet. Anything that claims to work with >WSGI and Python 3.0 is just a big guess as far as how WSGI for Python >3.0 may work. Perhaps you meant "library" instead of "specification"? I don't understand how a language can be missing a specification. -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
Stephen Fairchild wrote: You are trying to run code in a class that does not exist yet. def Demo(): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": fact(5)}) Demo = Demo() d = Demo() print d._classvar# prints 120 print d.fact(7) # prints 5040 print Demo # prints In all these messages, something I haven't seen pointed out is that fact() has no self argument. Seems to me that makes it a staticmethod, so it should be declared that way. But you can't call a static method from the class scope, since the class hasn't been completed yet. That's the part I consider a problem, not all the rest. I've seen the same problem in Forth, where 'smudge' is used to prevent a definition from accidentally calling itself. But I don't recall whether that was in the standard, or just vendor's helpful additions. Anyway, my first choice is to move the static method out of the class. Second choice workaround follows, moving the initialization of the class variable to after the class, when it can properly use the class name.: class Demo(object): @staticmethod def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) Demo._classvar = Demo.fact(5) print Demo._classvar xx = Demo() print xx.fact(6) DaveA -- http://mail.python.org/mailman/listinfo/python-list
Return value of multiprocessing manager registerred function
Hi, I'm using the multiprocessing.manager to run procedures remotely. It all worked fine except I hope to have a different return value type. The remote function calls always return a proxy, which when I need to get the value it need to connect to the manager again to fetch it. But I just need the value, not the proxy. Can I just return the value instead of a proxy from a manager? br, Terry -- http://mail.python.org/mailman/listinfo/python-list
Re: can python make web applications?
Mark wrote: > On Sun, 23 Aug 2009 21:45:17 +0100, Goke Aruna wrote: > >http://www.openerp.com, all done is python. > > That does look impressive. Is that Django or Turbogears? Turbogears, according to the product's wikipedia page. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing managers and socket connection.
On Aug 25, 10:14 pm, Chris wrote: > I've been using multiprocessing managers and I really like the > functionality. > > I have a question about reconnecting to a manager. I have a situation > where I start on one machine (A) a manager that is listening and then > on another machine (B) connects to that manager and uses its proxy > object to call functions on the manager's computer; this all works as > expected. But, if the manager from A shuts down, B's application won't > notice because in the MP code it ignores socket error > errno.ECONNREFUSED. If A becomes available again or is restarted, B > doesn't automatically reconnect either and continue its operation. > It's function is basically stopped. > > Here is the code from connection.py: > while 1: > try: > s.connect(address) > except socket.error, e: > if e.args[0] != errno.ECONNREFUSED: # connection refused > debug('failed to connect to address %s', address) > raise > time.sleep(0.01) > else: > break > > How can I have B automatically reconnect to A and continue its work > once A is available again? I think you need to retry repeatedly until successfully connected. br, Terry -- http://mail.python.org/mailman/listinfo/python-list
Python on the Web
I've seen lots of web sites explaining everything, but for whatever reason I seem to not be picking something up. I am a graphical person, which is probably the reason I haven't found my answer. May somebody please confirm if my diagram accurately represents the stack, generally speaking. http://i26.tinypic.com/1fe82x.png Even if that is the case, I'm having a hard time understanding the differences. I guess wsgiref has absolutely nothing to do with FCGI/ SCGI/CGI and simply receives and responds to HTTP requests following the WSGI specification? Does it just spawn a new thread for each request? If so, then how is this any different than a production server with FCGI? The way I am understanding the 'Production' side of that picture is that the web server (eg. lighttpd) creates a single FCGI process. The FCGI process is actually the entry point of the Framework/Application which sets up Flup's WSGIServer, being the interface between FCGI and the Framework/Application? What I mean is, it is just the code that the web server loads to start with, example... from flup.server.fcgi import WSGIServer from app import application WSGIServer(application).run() ... Then for each HTTP request, Flup's WSGIServer creates a new thread to handle the request? As I've read elsewhere, "These days, FastCGI is never used directly. Just like mod_python it is only used for the deployment of WSGI applications." As far as I understand, the main (or only?) reasoning for this is because WSGI makes Python applications easier to deploy without having to worry about whether using FCGI/SCGI/CGI. What would be involved to run Python on the web using FCGI without WSGI? I can feel the flames already. This isn't the only reason I want to know, but one reason is that I want to use Python 3.1 and as I understand, this will have to wait for the WSGI 2.0 specification to ensure time isn't wasted. I apologize if the questions are ridiculous. I've just recently got into web programming and it seems that in order for me to use Python, I need a deep understanding of web servers, HTTP, FCGI, etc. I have more questions but they go more off topic, so I will save it for another thread, another day. I realize there is a large number of questions, so thanks for any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: break unichr instead of fix ord?
25-08-2009 o 21:45:49 wrote: In Python 2.5 on Windows I could do [*1]: # Create a unicode character outside of the BMP. >>> a = u'\U00010040' # On Windows it is represented as a surogate pair. [snip] On Python 2.6, unichr() was "fixed" (using the word loosely) so that it too now fails with characters outside the BMP. [snip] Does not this effectively make unichr() and ord() useless on Windows for all but a subset of unicode characters? Are you sure, you couldn't have UCS-4-compiled Python distro for Windows?? :-O *j -- Jan Kaliszewski (zuo) -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
You are trying to run code in a class that does not exist yet. def Demo(): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": fact(5)}) Demo = Demo() d = Demo() print d._classvar# prints 120 print d.fact(7) # prints 5040 print Demo # prints -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it a bug?
25-08-2009 o 22:51:14 Gleb Belov wrote: I have two questions: 1) Is it possible and if so, how do I access each individual element? Are there any indexes and what is the syntax? It's a 'Read-The-Friendly-Manual' question. (hint: library reference - Built-in Types - ...) -- Jan Kaliszewski (zuo) -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
25-08-2009 o 22:16:24 Stephen Hansen wrote: The OP's probably is that during the execution of the class body, the class doesn't exist... so the 'def fact' -can't- use Classname.fact to address itself explicitly, and within fact the locals don't contain a reference to the function itself, and its globals don't either. You just can't do that. The right way, IMHO, is to move 'fact' up and out of the class into a _fact global variable. Alternatively, you can use a metaclass. Note that you can also pass a function to the function itself, and then it works: class Foo: ... def func(foo=None): ... if foo: ... return foo() ... else: ... return '2nd step' ... x = func(func) ... Foo.x '2nd step' Note that when called from class definition body, func is an ordinary function, not a method. It become a method *when it's called as a method* (what is possible *after* creating the class => outside the definition). Cheers, *j -- Jan Kaliszewski (zuo) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, qt, and lgpl
On 25 Aug, 21:45, Terry Reedy wrote: > Will be good news if realized. Good news for everyone except Riverbank. -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]
On Aug 25, 3:47 pm, Evan Driscoll wrote: > So here is my simplified version that only works for globals: So I think this works if (1) you only use changed_value in the same module as it's defined in (otherwise it picks up the globals from the module it's defined in, which is almost certainly not what you want), and (2) the value you want to change is just a simple variable and not either something like "os.path" or a builtin. I have worked on this a bit more and have something that addresses these issues in at least the cases I've tested. I'm not going to post the code here, but it is up at http://pages.cs.wisc.edu/~driscoll/python/utils.py and there are a few unit tests at http://pages.cs.wisc.edu/~driscoll/python/utils_test.py I solved issue (1) by reintroducing the use of inspect to walk back up the stack a couple frames, but I pulled out the f_globals member instead of f_locals. Issue (2a) I fixed by splitting the variable name at periods and walking through successive dictionaries with each component. Issue (2b) I fixed by looking for a '__builtins__' entry if the name I'm looking up doesn't exist. Right now it's sort of hackish... it probably doesn't respond particularly well if things go unexpectedly (e.g. a bad variable name is given) and I should probably verify that the value is unchanged during the with statement and throw an exception otherwise, but it probably works well enough for my purposes for now. Comments are appreciated... a couple of the things in there it seems like there could very well be reimplementations of things that are already done. Evan -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with arrays
On Aug 25, 11:50 pm, Stephen Fairchild wrote: > Philip Semanchuk wrote: > > > On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > > >> Hello! I'm working on an exercise wherein I have to write a Guess The > >> Number game, but it's the computer who's guessing MY number. I can get > >> it to work, but there's one obvious problem: the computer generates > >> random numbers until one of them corresponds to my number, but it will > >> often generate one number (eg. 4) numerous times, meaning it doesn't > >> know that this number is invalid. What I mean is, it will sometimes > >> use 37 tries to guess a number out of 1 - 9, which makes no sense, > >> since it should only take 9 tries, at most. I was trying to find a way > >> to make a dynamic list of all the numbers the computer generates in > >> the loop and then make it re-generate the number if the previous > >> number is present in the list, so it doesn't keep on generating 4 (as > >> an example). I don't know if that makes sense... Basically, we humans > >> know that once something is incorrect, there's no point in trying to > >> use it as the answer next time, because we already know it's > >> incorrect. How do I go about coding this in Python? I'm still quite > >> new to the language so any help will be appreciated... > > > One cheap way to do it (not necessarily efficient) is to make a list > > of your possible guesses (e.g. range(1,10)), use random.shuffle() to > > put them in random order and then run through the guesses one at a time. > > import random > import time > > l = range(1, 10) > > while l: > print l.pop(random.randint(0, len(l) - 1)) > time.sleep(2) > > -- > Stephen Fairchild Perhaps generate all of the possible moves at the outset in some form of lookup table that you can refer to? I think it is a similar thing to how computers play chess, I think it is called "hash tables" -- http://mail.python.org/mailman/listinfo/python-list
Division and right shift in python
Hi, I would like to do a floor division by a power of 2 in python to make it faster than / (modular division in 2.x). However, it is slower. What is the reason of that? I checked them via: def f2(x,n): t1 = clock() r = x/pow(2,n) t2 = clock() print (t2-t1) print r t2 = clock() r = x>>n t3 = clock() print (t3-t2) print r -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python: Permission denied
On Aug 25, 4:00 pm, David wrote: > Thanks Graham. Let me contact Admin. Hi Graham: you are right. it's fixed now. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for professsional Windows GUI apps?
If you are planning a database driven app, you should first settle on a DB server. Any real enterprise DB system will put all of the business logic in the database server. The choice of a front end should be secondary. Wikipedia's list of Python apps: http://en.wikipedia.org/wiki/List_of_Python_software -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python: Permission denied
disclaimer: i did not write this code. i copied it and inserted into my cgi code. it is from http://webpython.codepoint.net/mod_python_publisher_big_file_upload. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with arrays
Philip Semanchuk wrote: > > On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > >> Hello! I'm working on an exercise wherein I have to write a Guess The >> Number game, but it's the computer who's guessing MY number. I can get >> it to work, but there's one obvious problem: the computer generates >> random numbers until one of them corresponds to my number, but it will >> often generate one number (eg. 4) numerous times, meaning it doesn't >> know that this number is invalid. What I mean is, it will sometimes >> use 37 tries to guess a number out of 1 - 9, which makes no sense, >> since it should only take 9 tries, at most. I was trying to find a way >> to make a dynamic list of all the numbers the computer generates in >> the loop and then make it re-generate the number if the previous >> number is present in the list, so it doesn't keep on generating 4 (as >> an example). I don't know if that makes sense... Basically, we humans >> know that once something is incorrect, there's no point in trying to >> use it as the answer next time, because we already know it's >> incorrect. How do I go about coding this in Python? I'm still quite >> new to the language so any help will be appreciated... > > One cheap way to do it (not necessarily efficient) is to make a list > of your possible guesses (e.g. range(1,10)), use random.shuffle() to > put them in random order and then run through the guesses one at a time. import random import time l = range(1, 10) while l: print l.pop(random.randint(0, len(l) - 1)) time.sleep(2) -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python: Permission denied
A little more info: "Defrosting.rtf" is a file that I wanted to upload. This file was supposed to upload to folder '/var/www/keyword- query/files/'. My code runs in root. -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python: Permission denied
On Aug 26, 8:43 am, David wrote: > Hello, > > I googled online however I did not find a clue my question. So I post > it here. > > I created a mod_python CGI to upload a file and saves it in folder "/ > var/www/keyword-query/files/". My code runs in root. > > fileitem = req.form['file'] > > # Test if the file was uploaded > if fileitem.filename: > > # strip leading path from file name to avoid directory traversal > attacks > fname = os.path.basename(fileitem.filename) > # build absolute path to files directory > dir_path = os.path.join(os.path.dirname(req.filename), 'files') > f = open(os.path.join(dir_path, fname), 'wb', 1) > > # Read the file in chunks > for chunk in fbuffer(fileitem.file): > f.write(chunk) > f.close() > message = 'The file "%s" was uploaded successfully' % fname > > I got: > > File "/var/www/keyword-query/upload.py", line 30, in upload > f = open(os.path.join(dir_path, fname), 'wb', 1) > > IOError: [Errno 13] Permission denied: '/var/www/keyword-query/files/ > Defrosting.rtf' > > "Defrosting.rtf" is a file on the desktop of my Windows XP computer. > > Anybody knows what the problem is? > > Thanks for your replies. Apache service likely running as a special user which doesn't have write permission to your directory. Graham -- http://mail.python.org/mailman/listinfo/python-list
Re: How does the file.seek() work ?
On Aug 25, 5:37 am, Tim Chase wrote: > > I want the file pointer set to 100 and overwrite everything from there > [snip] > > def application(environ, response): > > query=os.path.join(os.path.dirname(__file__),'teemp') > > range=environ.get('HTTP_RANGE','bytes=0-').replace > > ('bytes=','').split(',') > > offset=[] > > for r in range: offset.append(r.split('-')) > > with open(query,'w+') as f: > > f.seek(int(offset[0][0])) > > while True: > > chunk=environ['wsgi.input'].read(8192).decode('latin1') > > if not chunk: break > > f.write(chunk) > > f=open(query) > > l=str(os.fstat(f.fileno()).st_size) > > response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > Length', str(len(l)))]) > > return [l] > > A couple items of note: > > - you don't open the file in binary mode -- seek is more reliable > in binary mode :) If my memory is right, if file is opened in binary mode, also wouldn't need to be decoding the WSGI input stream as latin-1 to get a string. Instead can just deal with bytes and write bytes to file. Graham > - if you want to lop off the rest of the file, use f.truncate() > > An example: > > # create the initial file > >>> f = file('zzz.zzz', 'wb+') > >>> f.write('abcdefghijklmnop') > >>> f.close() > > >>> f = file('zzz.zzz', 'ab+') > >>> f.read() # show the existing content > 'abcdefghijklmnop' > >>> f.seek(5) # seek to the desired offset > >>> f.truncate() # throw away everything after here > >>> f.write('zyx') # write the new data at pos=5 > >>> f.close() > > # demonstrate that it worked > >>> f = file('zzz.zzz', 'rb') > >>> f.read() > 'abcdezyx' > >>> f.close() > > > also why must I open the file a second time to know how big it is ? > > Likely the output has been buffered. You can try using > > f.flush() # write all the data to the disk first > size = os.fstat(f.fileno()).st_size > > which seems to do the trick for me. > > -tkc -- http://mail.python.org/mailman/listinfo/python-list
mod_python: Permission denied
Hello, I googled online however I did not find a clue my question. So I post it here. I created a mod_python CGI to upload a file and saves it in folder "/ var/www/keyword-query/files/". My code runs in root. fileitem = req.form['file'] # Test if the file was uploaded if fileitem.filename: # strip leading path from file name to avoid directory traversal attacks fname = os.path.basename(fileitem.filename) # build absolute path to files directory dir_path = os.path.join(os.path.dirname(req.filename), 'files') f = open(os.path.join(dir_path, fname), 'wb', 1) # Read the file in chunks for chunk in fbuffer(fileitem.file): f.write(chunk) f.close() message = 'The file "%s" was uploaded successfully' % fname I got: File "/var/www/keyword-query/upload.py", line 30, in upload f = open(os.path.join(dir_path, fname), 'wb', 1) IOError: [Errno 13] Permission denied: '/var/www/keyword-query/files/ Defrosting.rtf' "Defrosting.rtf" is a file on the desktop of my Windows XP computer. Anybody knows what the problem is? Thanks for your replies. -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to display photos
On Aug 25, 1:40 am, Thomas Guettler wrote: > Some years ago I had the same problem. > > I wrote a simple app with pygtk. You get get it from here: > http://guettli.sourceforge.net/gthumpy/src/README.html > The next pictures get loaded in background. Switching from > one image to the next is faster then in some other apps. But > somehow it is not ready for the public. I guess I am the only > one who uses it. > > Flags are symlinks in the home directory .local/share/app/gthumpy. This > means you should not move your images, otherwise the flags get lost. > > I don't think it will work on ms-windows, but it could be ported. > > Or you use mirage:http://mirageiv.berlios.de/index.html > > It is a pygtk image viewer. You can define shortcuts that execute user defined > commands. > > Thomas > > samwyse schrieb: > > > I have several thousand photographs that I need to quickly classify, > > all by myself. After extensive searches, I have been unable to find > > anything to my liking, so desire to write something myself. I'm > > thinking about displaying a photo and waiting for keystrokes to tag > > it; 'i' for interior, 'e' for exterior, etc., while hitting space or > > enter will advance to the next photo. My big question is, what's the > > best way to display the photos. I've used PIL in the past, but IIRC > > it uses an external program. Pygame is the next obvious choice, but > > like PIL it requires an add-in. That leaves Tkinter. Has anyone used > > it to display .JPG files, perhaps with rescaling to fit my screen? > > How is its performance? Is there any other possibilities that I've > > missed? Thanks. > > -- > Thomas Guettler,http://www.thomas-guettler.de/ > E-Mail: guettli (*) thomas-guettler + de Thanks! Both of these look very similar to what I need. I will investigate further. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on Crays
Ok, here are links to word documents outlining the commands I executed as well as the make.log file and the make_install.log file instructions/commands: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018965_1-t_dSnfEm5b make.log: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018966_1-t_zjqLuV5v javascript:parent.send('smtp') make_install.log: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018967_1-t_n8aqH2P The issue referred to in the previous message (http://bugs.python.org/issue1594809) sounds similar - however I do not think that I can just build the shared unicodedata module and have it work properly, as I am trying to statically link the necessary modules. I am very new with this, so if I am completely misunderstanding, please feel free to let me know. Thanks! Carrie - Original Message - From: Mark Dickinson Date: Friday, August 21, 2009 12:50 pm Subject: Re: Python on Crays To: python-list@python.org > On Aug 21, 12:21 am, Carrie Farberow wrote: > > I am trying to build a statically-linked Python based on directions > at: > > > > http://yt.enzotools.org/wiki/CrayXT5Installation > > > > I have tried this on multiple systems. The first time I attempt to > build python, 'make' runs fine but 'make install' fails with the > following error: > > > > Sorry: UnicodeError: ("\\N escapes not supported (can't load > unicodedata module)",) > > > > Any help regarding the source of this error and possible fixes would > be appreciated. > > Hmm. There's not a lot of information to go on here. > What version of Python is this? Python 2.6.2? > Have you tried Googling for that exact error message? > > The following issue looks as though it might be relevant: > > http://bugs.python.org/issue1594809 > > especially since it looks as though the directions you linked > to involve messing with the PYTHONPATH environment variable. > > If you could post a log somewhere[*] showing the exact commands > that you executed, along with all the output (and especially > all the output from 'make' and 'make install'), that might help > someone diagnose the problem further. > > Mark > > [*] I'm not sure where, though. Posting all that output directly > in a newsgroup message might not be considered very friendly. > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with arrays
On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: Hello! I'm working on an exercise wherein I have to write a Guess The Number game, but it's the computer who's guessing MY number. I can get it to work, but there's one obvious problem: the computer generates random numbers until one of them corresponds to my number, but it will often generate one number (eg. 4) numerous times, meaning it doesn't know that this number is invalid. What I mean is, it will sometimes use 37 tries to guess a number out of 1 - 9, which makes no sense, since it should only take 9 tries, at most. I was trying to find a way to make a dynamic list of all the numbers the computer generates in the loop and then make it re-generate the number if the previous number is present in the list, so it doesn't keep on generating 4 (as an example). I don't know if that makes sense... Basically, we humans know that once something is incorrect, there's no point in trying to use it as the answer next time, because we already know it's incorrect. How do I go about coding this in Python? I'm still quite new to the language so any help will be appreciated... One cheap way to do it (not necessarily efficient) is to make a list of your possible guesses (e.g. range(1,10)), use random.shuffle() to put them in random order and then run through the guesses one at a time. HTH Philip -- http://mail.python.org/mailman/listinfo/python-list
Help with arrays
Hello! I'm working on an exercise wherein I have to write a Guess The Number game, but it's the computer who's guessing MY number. I can get it to work, but there's one obvious problem: the computer generates random numbers until one of them corresponds to my number, but it will often generate one number (eg. 4) numerous times, meaning it doesn't know that this number is invalid. What I mean is, it will sometimes use 37 tries to guess a number out of 1 - 9, which makes no sense, since it should only take 9 tries, at most. I was trying to find a way to make a dynamic list of all the numbers the computer generates in the loop and then make it re-generate the number if the previous number is present in the list, so it doesn't keep on generating 4 (as an example). I don't know if that makes sense... Basically, we humans know that once something is incorrect, there's no point in trying to use it as the answer next time, because we already know it's incorrect. How do I go about coding this in Python? I'm still quite new to the language so any help will be appreciated... -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile
Ryniek90 wrote: Ryniek90 wrote: [snip] Here's my script code: *http://paste.ubuntu.com/259310/ *Shouldn't that bug be patched already :-? Are you giving it the contents of the file when it's actually expecting the filename? Of course the content of the file: [snip] See? *backup_obj.add(read_obj.read())* In previous pasted Traceback you can see *backup_obj.add(read_bin_obj)* - read_obj_bin was a reference to the *read_obj.read()* . The documentation lists the methods "add" and "addfile". Pick one and provide the values it's expecting. For example, if you choose "add" then provide the filename, not the contents of the file. Do only I have this problem or Python programming under Windows is nightmare? It's only a nightmare if you don't follow the documentation. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
> seb (s) wrote: >s> i am still a bit puzzle by the following. >s> I read in >http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators >s> """Python 3.0 unifies all collection types by introducing dict and set >s> comprehensions, similar to list comprehensions: > [ n*n for n in range(5) ] # regular list comprehension >s> [0, 1, 4, 9, 16] > > { n*n for n in range(5) } # set comprehension >s> {0, 1, 4, 16, 9} > > { n: n*n for n in range(5) } # dict comprehension >s> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} >s> """ >s> and we can add to this list the quite similar syntax for generator >s> expressions. >s> On all these loop constructs, one can consistenly add filtering on a >s> condition by adding an "if ..." after the "for ... in ..." part (and >s> it looks to me difficult to argue, for instance, that we should not >s> allow filtering for dict comprehesion because we could get the same >s> result by some other construct) You can also say: [x+y for x in range(3) for y in range(4) if x < y] If you want to write this as a loop you have to put the for's on separate lines separated by colons, so why not the if also? Or would you also like to have the for's on one line? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
Stephen Hansen said: But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A First Look at Classes": When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. [snip] (BTW, Diez, your toy example is another demonstration that there *is* a class-scope-lookup: the "def" statement binds the name "fact" in the class scope, and the assignment statement looks up the name "fact" in that scope.) This sounds like a fundamental confusion -- a namespace is not equivalent to a scope, really, I think. My apologies if I was being too loose with the terms "namespace" and "scope". I was trying to use Diez's terminology (e.g. "class-scope-lookup"). But I think you agree with me in *almost* everything you say below. The def statement creates a function object, and assigns it to the given name, in its /local scope/ which is the class's namespace -- but that is not a new scope. Its just, during class creation, the local scope. When you enter a class definition, a new namespace is created, and that is used as the local scope during the class's definition. Under "class Foo", the local scope is this class's namespace-- and the global scope is the module's namespace. Any lookup operation checks first in the local scope, then in the global scope... When the "def fact(...)" is executed (note that class bodies are executed on load, function bodies aren't), a new namespace is created as well-- the function's namespace-- and its used as the local scope. During execution of the code, it looks up in the local scope first-- and then it looks up in the global scope if it doesn't find anything. There /is/ no class-lookup-scope... but there IS a class namespace. There's just those two scopes: but the namespace bound to those scopes changes as you enter different parts of the code. For a long time that's all there was, just the local and global scope: to access any other namespace required you to explicitly address it. The class namespace remains accessible only via explicit addressing, but PEP 227 in Python 2.1/2.2 introduced static nested scopes. But that applies only to enclosing functions: embedding one function into another. You can only call recursive functions if the function is able to refer to itself according to the same lookup rules: is the function's name in the local scope? No it's not... is it in the global scope? No? Then it can't call itself recursively... well, unless its a method, and it addresses itself specifically-- with "self.". All of the above is consistent with my previous post. The OP's probably is that during the execution of the class body, the class doesn't exist... so the 'def fact' -can't- use Classname.fact to address itself explicitly, and within fact the locals don't contain a reference to the function itself, and its globals don't either. You just can't do that. Here's where we disagree, and I'm sticking to my guns. The fact that the class definition has not been completely processed is irrelevant. The OP's problem was attempting to implement a recursive function. A non-recursive implementation of fact() works fine: class ThisWorks(object): def fact(n): answer = 1 i = 1 while i <= n: answer *= i i += 1 return answer clsvar = fact(4) print ThisWorks.clsvar # output: 24 The right way, IMHO, is to move 'fact' up and out of the class ... We're back to agreement on this point! -John -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for professsional Windows GUI apps?
On Tue, Aug 25, 2009 at 7:24 AM, Wolfgang Keller wrote: > The only framework that seems to be worth trying is Dabo. Unfortunately > there's little documentation, and that's mostly outdated. To be honest, that was my biggest concern when I tried Dabo. However, after as small a learning curve as one could expect for any non-trivial tool, it seemed that if I wasn't sure what a particular way to do something was, the most obvious guess was almost always correct. Contrast that with developing in wxPython, which has quite a bit of documentation, which I constantly had to refer to, because the confusing and inconsistent design. There is a step by step guide on Google docs written by one of the authors that is a very helpful approach to using Dabo. The authors are also very active on the dabo-users list, and any questions are quickly answered. So I guess if you need a desktop framework in Python, I would strongly urge you to check out Dabo and not let the volume of documentation scare you off. -- # p.d. -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric literals in other than base 10 - was Annoying octal notation
On 24 Aug, 03:49, Dennis Lee Bieber wrote: ... > > Here's another suggested number literal format. First, keep the > > familar 0x and 0b of C and others and to add 0t for octal. (T is the > >thirdletter of octal as X is thethirdletter of hex.) The numbers > > above would be > > The thing is -- "x" and "hex" have similar pronunciations: (h)ecks; > the name of the radix is its own reminder for the character to use > without thinking such conventions as "thirdletter of the radix name". > > But "t" (tee) has no pronunciation resemblance to "oct" (o'kt) > whereas the unlovely "o" at least if taken as a short vowel sound is > similar to the "o" of "oct" given the short stop between it and the > "ct". > > > 0b1011, 0t7621, 0xc26b > > And "b" for binary breaks the "thirdletter of radix name" > convention... You should be using "n" for that (and "c" for decimal ) I wasn't proposing a convention of using the third character of the base name. I was saying that t is not too unreasonable given that we use x for hex (rather than h). > > Or we use b, o, d, h (as the HP calculator) and drop the "x" > version. > > > > > where the three characters "0.(" begin the sequence. > > Ugly... > > > Comments? Improvements? > > Retaining which ever character is finally decided, I'd make all > radix specified literals follow a quoted format: > > "digits"radix > > "01110"b > "123"d (of course, just 123 would be allowed for simplicity) > "7C"x > "327"o The quoting is good. For hex, decimal, octal and binary, however, I can't see a good reason to change away from the conventional prefix form. And, in general, it's easier for a human to parse if the base is specified first. > > Probably wouldn't need that much change to the parser as it would, > left to right, see a string, and then when the string is not followed by > one white space character, find a radix marker -- the parser would then > parse the string using the specified radix, and emit the appropriate > numeric value instead of a string value. Maybe. I think, though, that having the base as prefix would make the parser's job easier as well as the job of humans. It's easier if we know what we are parsing before we parse it rather than afterwards. > It only adds one extra > character (instead of leading 0r, one has ""r), and the leading " serves > as a warning to a reader that this is not directly readable as a number. > > The alternative syntax of radix"digits" is the same length, but adds > to the parsing as it initially looks like a name entity, then hits the > quote, and has to back up to interpret the result as a radix marker. True. The beginning of a number should be numeric. Using your scheme, though, instead of radix"digits" you could have 0radix"digits". > 0r > format starts as a number, hits a radix marker while the > "conversion/accumulator" is still a 0 value (0 is 0 in all radix) and > switches the converter to accept the digits in the specified radix. Sounds like you are suggesting 0radix"digits" but I'm not sure. > > Whereas all prefix versions that don't start with a 0r tend to > require more complex parsing: > > 0.( > > starts out looking like a number (the 0)... a floating point number (the > .)... a function/method call on a floating point 0... WAIT? floating > point numbers aren't callables (yet! I'm sure someone is going to show a > way to define a variable bound to a number as a callable, though not to > a literal number)... throw away this parse tree branch, back up and > reparse as special numeric radix prefix... You've laid it on thick but I agree in principle. What about radix"digits" where radix is numeric: So 2"1101" or 3"122"? (Not to replace 0b1101 etc but to supplement it for arbitrary bases.) > > Of course, one still has to consider what will be used for \ > character encoding... \x0F vs \013 vs \b000? The plans I had did not allow for the suggestions above so I have no comments on character encoding yet but it's good that you mentioned it. James -- http://mail.python.org/mailman/listinfo/python-list
TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile
Ryniek90 wrote: Referring to my earlier posts: http://groups.google.pl/group/comp.lang.python/browse_thread/thread/4e34f995800f5352?hl=pl and http://groups.google.pl/group/comp.lang.python/browse_thread/thread/abf5573b8fceb37e?hl=pl# I've dealt with those errors. but now have another. When my backup scripts starts to backup chosen file, python gave me Traceback: " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup Checking permissions for reading and writing... Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. Have permissions on [F:\] for writing. Preparing for backup [nowegg.exe]... Starting backup... Now adding [nowegg.exe]... Traceback (most recent call last): File "backuper.py", line 197, in main_meth() File "backuper.py", line 189, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename[1], pars.options.filename[2]) File "backuper.py", line 127, in backup_file backup_obj.add(read_bin_obj) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\tarfile.py", line 1948, in add if self.name is not None and os.path.abspath(name) == self.name: File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\ntpath.py", line 458, in abspath path = _getfullpathname(path) TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str " I've searched over google, but found only that is bug in Python ( http://bugs.python.org/issue4071 - in that issue bug is inside Python 2.5.2 - i've got ActiveState Active Python with core Python 2.6.2), and another info: *http://tinyurl.com/lvyn7o and **http://tinyurl.com/kn49vk * Here's my script code: *http://paste.ubuntu.com/259310/ *Shouldn't that bug be patched already :-? Are you giving it the contents of the file when it's actually expecting the filename? Of course the content of the file: " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup Checking permissions for reading and writing... Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. Have permissions on [F:\] for writing. Preparing for backup [nowegg.exe]... Starting backup... Now adding [nowegg.exe]... Traceback (most recent call last): File "backuper.py", line 196, in main_meth() File "backuper.py", line 188, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename[1], pars.options.filename[2]) File "backuper.py", line 126, in backup_file backup_obj.add(read_obj.read()) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\tarfile.py", line 1948, in add if self.name is not None and os.path.abspath(name) == self.name: File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\ntpath.py", line 458, in abspath path = _getfullpathname(path) TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str " See? *backup_obj.add(read_obj.read())* In previous pasted Traceback you can see *backup_obj.add(read_bin_obj)* - read_obj_bin was a reference to the *read_obj.read()* . Do only I have this problem or Python programming under Windows is nightmare? -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
On Aug 25, 10:46 pm, Falcolas wrote: > On Aug 25, 1:58 pm, seb wrote: > > > On Aug 25, 9:42 pm, Falcolas wrote: > > > On Aug 25, 11:25 am, seb wrote: > > > So, what part of the statement does the "if" statement belong to; > > > particularly a concern considering this is valid python: > > > > for x in y if y else z: > > > body > > > can this be done in list/set/dict comprehensions/generator > > expressions ? > > It's a statement, so anywhere you use a statement (such as in > generators and list comprehensions), it can exist. for ... in ... only > requires that the statement return an iterable, it doesn't matter what > statement you use to get there. > I never thought about this case... Testing that in python 3.0, i see that >>> [x for x in range(5) if False else range(10)] SyntaxError: invalid syntax (, line 1) >>> [x for x in (range(5) if False else range(10))] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] hence, to avoid the ambiguity you mentionned (that already exists with list comprehensions), one can use the parenthesis. This minor incompatibility is referenced in http://www.python.org/dev/peps/pep-0308/ > It doesn't feel clear to me, which is why I would have to disagree. > IIRC, these very filters are the main reason that list comprehensions, > and later one-line generators and dictionary comprehensions were > originally created: so you can filter the stream before acting on it. > One statement performs one action - very precise and understandable. in my mind, I am thinking as you are but with 'loop' instead of 'stream' """so you can filter the 'loop' before acting on it. One statement performs one action - very precise and understandable.""" and it doesn't look that dissimilar to your own reasoning. > > It's just my two cents, but I would not agree that adding a filter > keyword to for loops is required. Not when we have the filter > function, various types of comprehensions, and if statements which all > provide that very functionality. > before having list comprehensions, we could also have said that """ I would not agree that adding a 'list comprehension' feature is required. Not when we have the filter function, and the 'for+if' statements which all provide that very functionality.""" How can unifying the "for ... in ..." statement with the "for ... in ... if ..." syntax be detrimental ? It would be an inconsistence less to remember, wouldn't it ? cheers, sebastien -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it a bug?
On Aug 26, 12:59 am, Stephen Fairchild wrote: > Gleb Belov wrote: > > Hey everyone! I'm quite new to Python and equally new to newsgroups in > > general, so apologies if this makes no sense. > > > Basically, I was just exploring Python "arrays" on my own, since I > > come from C++. What I did was: > words = ["Hi!", "What's up?", "Bye!"] > print words > > ['Hi!', "What's up?", 'Bye!'] > > > I have two questions: > > 1) Is it possible and if so, how do I access each individual element? > > Are there any indexes and what is the syntax? > > For the first element: > > >>> words[0] > > 2) I just noticed that the first and the last words in the output are > > enclosed in single quotes, and the middle one is enclosed in double > > quotes. Is it a bug? If not, why does the output work that way? > > The output is valid python code. To represent with single quotes for the > second item, there would have to be a \ escape character for the > apostrophe. > -- > Stephen Fairchild Oh, thank you! That makes sense! Should have thought of the escape character issue... -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it a bug?
Gleb Belov wrote: > Hey everyone! I'm quite new to Python and equally new to newsgroups in > general, so apologies if this makes no sense. > > Basically, I was just exploring Python "arrays" on my own, since I > come from C++. What I did was: words = ["Hi!", "What's up?", "Bye!"] print words > ['Hi!', "What's up?", 'Bye!'] > > I have two questions: > 1) Is it possible and if so, how do I access each individual element? > Are there any indexes and what is the syntax? For the first element: >>> words[0] > 2) I just noticed that the first and the last words in the output are > enclosed in single quotes, and the middle one is enclosed in double > quotes. Is it a bug? If not, why does the output work that way? The output is valid python code. To represent with single quotes for the second item, there would have to be a \ escape character for the apostrophe. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Is it a bug?
Hey everyone! I'm quite new to Python and equally new to newsgroups in general, so apologies if this makes no sense. Basically, I was just exploring Python "arrays" on my own, since I come from C++. What I did was: >>> words = ["Hi!", "What's up?", "Bye!"] >>> print words ['Hi!', "What's up?", 'Bye!'] I have two questions: 1) Is it possible and if so, how do I access each individual element? Are there any indexes and what is the syntax? 2) I just noticed that the first and the last words in the output are enclosed in single quotes, and the middle one is enclosed in double quotes. Is it a bug? If not, why does the output work that way? Alright, thanks in advance for any replies and I hope I'll manage to actually find this topic... -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]
On Aug 25, 3:25 pm, "Diez B. Roggisch" wrote: > Modifying locals isn't really allowed - it might stop working with > certain implementations of python. > > And to be honest - I don't really see a use-case for your whole > approache. Why don't you want to introduce a new name? Wow, this actually was very helpful, because it forced me to clarify what I'm doing to myself, and I *am* making it rather too complicated. The reason that I can't introduce a new name is that I want to call another function that refers to the old name. (Specifically, I'm using this in a testing framework, and I want to mock out some things like file I/O so want to replace 'open' and others temporarily. I don't really want to make said function take an extra parameter which is "the open function to use" or something like that.) But then I don't need to modify locals. In fact, the references that I want to affect are used in a function that isn't even on the stack when the "with" statement is entered! So I only need to modify a global, which is much easier than what I was mucking about with. So here is my simplified version that only works for globals: from contextlib import contextmanager @contextmanager def changed_value(var_name, temp_value): old_value = globals()[var_name] globals()[var_name] = temp_value try: yield None finally: globals()[var_name] = old_value x = 5 print "5:", x with changed_value("x", 10): print "10:", x print "5:", x y = 7 def test(): print "5:", x with changed_value("x", 20): print "20:", x print "7:", y print "5:", x test() print "5:", x How does that look? And thanks for making me think about what I'm doing. :-) Evan -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
On Aug 25, 1:58 pm, seb wrote: > On Aug 25, 9:42 pm, Falcolas wrote: > > On Aug 25, 11:25 am, seb wrote: > > So, what part of the statement does the "if" statement belong to; > > particularly a concern considering this is valid python: > > > for x in y if y else z: > > body > > can this be done in list/set/dict comprehensions/generator > expressions ? It's a statement, so anywhere you use a statement (such as in generators and list comprehensions), it can exist. for ... in ... only requires that the statement return an iterable, it doesn't matter what statement you use to get there. For example, the following is perfectly valid (if nonsensical - I don't use ternary operators very often in my programming, so I don't have many good examples of their use) list = [x if x else y for x, y in iterable] > it is in fact precisely to avoid this sort of line: > for n in (x for x in y if x%3==0): > and have instead the (more readable IMO) line > for n in y if n%3==0: > with: > - 1 "for ... in ..." instead of 2 (where one is the repetition of the > other) > - no parentheses > - no extra technical variable with local binding to the expression > generator ('x') > it looks more pythonic to me but it is a personal taste. > It doesn't feel clear to me, which is why I would have to disagree. IIRC, these very filters are the main reason that list comprehensions, and later one-line generators and dictionary comprehensions were originally created: so you can filter the stream before acting on it. One statement performs one action - very precise and understandable. It's just my two cents, but I would not agree that adding a filter keyword to for loops is required. Not when we have the filter function, various types of comprehensions, and if statements which all provide that very functionality. ~G -- http://mail.python.org/mailman/listinfo/python-list
Re: os.popen output different from native shell output
On Aug 25, 11:57 am, Thomas Guettler wrote: > In one of the first chapters of "Advanced programming in the unix > environment (second edition)" there is explained how a unix shell works. > > You could write you own shell using python. This way the python > interpreter gets stared only once, and not for every call to "ls". > > Have fun, > Thomas > > nickname schrieb: > > > wow guys! thanks for all the great leads! this is awesome! > > > The reason why I want to do this is because I am going to do a little > > project. I will write a python script called ls which will log the > > time and username and then will show the actual ls output. I want this > > to be transparent and so want to throw the ls output (via python) > > exactly as it will be in native shell execution. > > very good point, I will look it up :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: your favorite debugging tool?
Ben Finney wrote: Esmail writes: Hi Ben, Ben Finney wrote: Whenever a simple output statement is too cumbersome for debugging, I take it as a sign that the program is too cumbersome to follow. I'll have to think about this .. though my gut says this is true :-) Note that it's only a sign, *not* an ironclad guarantee. But it's the right way to bet, IME. :-) .. I took it as a rule of thumb too .. I didn't meant to imply anything more serious. These design guidelines help though. Thanks, Esmail -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]
Evan Driscoll schrieb: On Aug 25, 2:33 pm, Evan Driscoll wrote: I want to make a context manager that will temporarily change the value of a variable within the scope of a 'with' that uses it. This is inspired by a C++ RAII object I've used in a few projects. Ideally, what I want is something like the following: Okay, so I think I actually got this with some consultation with a friend. Critiques? Modifying locals isn't really allowed - it might stop working with certain implementations of python. And to be honest - I don't really see a use-case for your whole approache. Why don't you want to introduce a new name? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]
On Aug 25, 3:07 pm, Evan Driscoll wrote: > Okay, so I think I actually got this with some consultation with a > friend. Critiques? This is wrong; it's not quite working right. It does with the example I posted, but not in a more thorough test. I'm still ignoring the "you can't do this" answers for a little while more and continuing to try to hack on it. :-) Evan -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
> > > But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A > First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope — thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > [snip] > > (BTW, Diez, your toy example is another demonstration that there *is* a > class-scope-lookup: the "def" statement binds the name "fact" in the class > scope, and the assignment statement looks up the name "fact" in that scope.) > This sounds like a fundamental confusion -- a namespace is not equivalent to a scope, really, I think. The def statement creates a function object, and assigns it to the given name, in its /local scope/ which is the class's namespace -- but that is not a new scope. Its just, during class creation, the local scope. When you enter a class definition, a new namespace is created, and that is used as the local scope during the class's definition. Under "class Foo", the local scope is this class's namespace-- and the global scope is the module's namespace. Any lookup operation checks first in the local scope, then in the global scope... When the "def fact(...)" is executed (note that class bodies are executed on load, function bodies aren't), a new namespace is created as well-- the function's namespace-- and its used as the local scope. During execution of the code, it looks up in the local scope first-- and then it looks up in the global scope if it doesn't find anything. There /is/ no class-lookup-scope... but there IS a class namespace. There's just those two scopes: but the namespace bound to those scopes changes as you enter different parts of the code. For a long time that's all there was, just the local and global scope: to access any other namespace required you to explicitly address it. The class namespace remains accessible only via explicit addressing, but PEP 227 in Python 2.1/2.2 introduced static nested scopes. But that applies only to enclosing functions: embedding one function into another. You can only call recursive functions if the function is able to refer to itself according to the same lookup rules: is the function's name in the local scope? No it's not... is it in the global scope? No? Then it can't call itself recursively... well, unless its a method, and it addresses itself specifically-- with "self.". The OP's probably is that during the execution of the class body, the class doesn't exist... so the 'def fact' -can't- use Classname.fact to address itself explicitly, and within fact the locals don't contain a reference to the function itself, and its globals don't either. You just can't do that. The right way, IMHO, is to move 'fact' up and out of the class into a _fact global variable. Alternatively, you can use a metaclass. --S -- http://mail.python.org/mailman/listinfo/python-list
Re: proposal: add setresuid() system call to python
On Fri, Aug 21, 2009 at 03:13:12PM -0500, tra...@subspacefield.org wrote: > Since the authors of the paper (Wagner et. al.) are proposing a new > set of APIs to make all of this clearer, I'm thinking that I will > create a module specifically for dropping permissions. I've created the module here: http://www.subspacefield.org/~travis/python/privilege/ I could sure use any comments people had on my python style. PyPi link: http://pypi.python.org/pypi/privilege/1.0 -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email j...@subspacefield.org to get blacklisted. pgpPM2rX9bRlM.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]
Evan Driscoll schrieb: (If you don't want to read the following, note that you can answer my question by writing a swap function.) I want to make a context manager that will temporarily change the value of a variable within the scope of a 'with' that uses it. This is inspired by a C++ RAII object I've used in a few projects. Ideally, what I want is something like the following: x = 5 print x # prints 5 with changed_value(x, 10): print x # prints 10 print x # prints 5 This is similar to PEP 343's example 5 ("Redirect stdout temporarily"; see http://www.python.org/dev/peps/pep-0343/), except that the variable that I want to temporarily change isn't hard-coded in the stdout_redirected function. What I want to write is something like this: @contextmanager def changed_value(variable, temp_value): old_value = variable variable = temp_value try: yield None finally: variable = old_value with maybe a check in 'finally' to make sure that the value hasn't changed during the execution of the 'with'. Of course this doesn't work since it only changes the binding of 'variable', not whatever was passed in, and I kind of doubt I can stick a "&" and "*" in a couple places to make it do what I want. :-) So my question is: is what I want possible to do in Python? How? No. And unfortunately, the with-statement (as the for-statement and others) leaks it's name, so you can't even use it like this: with changed_value(variable, temp_value) as new_name: ... The new_name will be defined afterwards. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
John Posner schrieb: Diez said: Classes are not scopes. So the above doesn't work because name resolution inside functions/methods looks for local variables first, then for the *global* scope. There is no class-scope-lookup. But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A First Look at Classes": When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. The following example confirms this: class Spam(object): clsvar_1 = 555 clsvar_2 = clsvar_1 + 222 def __init__(self): print "Spam instance initialized" sp = Spam() print sp.clsvar_1, sp.clsvar_2 output: Spam instance initialized 555 777 Does the OP (kj) have a legitimate gripe, though? I confess that I know nothing about Python's implementation -- I'm strictly a user. So it's just a suspicion of mine that something special enables a recursive function definition to refer to the function's own name before the definition has been completed. It works at the module-namespace (i.e. global) level, and Diez's "toy example" shows that it works at function-namespace level: class Demo(object): def fact(n): def inner(n): if n < 2: return 1 else: return n * inner(n - 1) return inner(n) _classvar = fact(5) So why can't it work at the class-namespace level, too? See my other post on what name lookup with class-scope *inside* functions would mean. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]
On Aug 25, 2:33 pm, Evan Driscoll wrote: > I want to make a context manager that will temporarily change the > value of a variable within the scope of a 'with' that uses it. This is > inspired by a C++ RAII object I've used in a few projects. Ideally, > what I want is something like the following: Okay, so I think I actually got this with some consultation with a friend. Critiques? from contextlib import contextmanager import inspect def get_parents_var(offset, var): f = inspect.stack()[offset][0] if var in f.f_locals: return f.f_locals[var] else: return f.f_globals[var] def set_parents_var(offset, var, val): f = inspect.stack()[offset][0] if var in f.f_locals: f.f_locals[var] = val elif var in f_globals: f.f_globals[var] = val else: assert False @contextmanager def changed_value_tb(var_name, temp_value): # 1 is here, 2 will be the implicit next() function, 3 is the real caller offset = 3 old_value = get_parents_var(offset, var_name) set_parents_var(offset, var_name, temp_value) try: yield None finally: set_parents_var(offset, var_name, old_value) x = 5 print x # prints 5 with changed_value_tb("x", 10): print x # prints 10 print x # prints 5 -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
On Aug 25, 9:42 pm, Falcolas wrote: > On Aug 25, 11:25 am, seb wrote: > > > > > We could as consistenly explain that the syntax > > > for n in range(10) if n%3==0: > > body > > > means > > > for n in range(10): > > if n%3==0: > > body > > > This syntax has also the benefit of avoiding an extra level of > > indentation (the one for the if) that bears no real meaning on a > > structural level. > > > Maybe a PEP could do the job... > > > Sébastien > > So, what part of the statement does the "if" statement belong to; > particularly a concern considering this is valid python: > > for x in y if y else z: > body > can this be done in list/set/dict comprehensions/generator expressions ? > You can always do the following at the cost of 6 symbols, and the gain > of clarity: > > for n in (x for x in y if y%3==0): > body it is in fact precisely to avoid this sort of line: for n in (x for x in y if x%3==0): and have instead the (more readable IMO) line for n in y if n%3==0: with: - 1 "for ... in ..." instead of 2 (where one is the repetition of the other) - no parentheses - no extra technical variable with local binding to the expression generator ('x') it looks more pythonic to me but it is a personal taste. > > ~G -- http://mail.python.org/mailman/listinfo/python-list
break unichr instead of fix ord?
In Python 2.5 on Windows I could do [*1]: # Create a unicode character outside of the BMP. >>> a = u'\U00010040' # On Windows it is represented as a surogate pair. >>> len(a) 2 >>> a[0],a[1] (u'\ud800', u'\udc40') # Create the same character with the unichr() function. >>> a = unichr (65600) >>> a[0],a[1] (u'\ud800', u'\udc40') # Although the unichr() function works fine, its # inverse, ord(), doesn't. >>> ord (a) TypeError: ord() expected a character, but string of length 2 found On Python 2.6, unichr() was "fixed" (using the word loosely) so that it too now fails with characters outside the BMP. >>> a = unichr (65600) ValueError: unichr() arg not in range(0x1) (narrow Python build) Why was this done rather than changing ord() to accept a surrogate pair? Does not this effectively make unichr() and ord() useless on Windows for all but a subset of unicode characters? -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager to temporarily change the variable of a register [aka write swap(a,b)]
On 8/25/2009 12:33 PM Evan Driscoll said... So my question is: is what I want possible to do in Python? Probably not with immutables (as in your example) -- maybe otherwise. Emile -- http://mail.python.org/mailman/listinfo/python-list
Python, qt, and lgpl
" New LGPL Python bindings for Qt slither into the light A new set of LGPL-licensed Python bindings for Qt has been announced. The project, which is backed by Nokia, will make it easier for commercial software developers to adopt Python and Qt for rapid application development." http://arstechnica.com/open-source/news/2009/08/openbossa-announces-new-lgpl-python-bindings-for-qt.ars Will be good news if realized. -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
On Aug 25, 11:25 am, seb wrote: > We could as consistenly explain that the syntax > > for n in range(10) if n%3==0: > body > > means > > for n in range(10): > if n%3==0: > body > > This syntax has also the benefit of avoiding an extra level of > indentation (the one for the if) that bears no real meaning on a > structural level. > > Maybe a PEP could do the job... > > Sébastien So, what part of the statement does the "if" statement belong to; particularly a concern considering this is valid python: for x in y if y else z: body You can always do the following at the cost of 6 symbols, and the gain of clarity: for n in (x for x in y if y%3==0): body ~G -- http://mail.python.org/mailman/listinfo/python-list
Context manager to temporarily change the variable of a register [aka write swap(a,b)]
(If you don't want to read the following, note that you can answer my question by writing a swap function.) I want to make a context manager that will temporarily change the value of a variable within the scope of a 'with' that uses it. This is inspired by a C++ RAII object I've used in a few projects. Ideally, what I want is something like the following: x = 5 print x # prints 5 with changed_value(x, 10): print x # prints 10 print x # prints 5 This is similar to PEP 343's example 5 ("Redirect stdout temporarily"; see http://www.python.org/dev/peps/pep-0343/), except that the variable that I want to temporarily change isn't hard-coded in the stdout_redirected function. What I want to write is something like this: @contextmanager def changed_value(variable, temp_value): old_value = variable variable = temp_value try: yield None finally: variable = old_value with maybe a check in 'finally' to make sure that the value hasn't changed during the execution of the 'with'. Of course this doesn't work since it only changes the binding of 'variable', not whatever was passed in, and I kind of doubt I can stick a "&" and "*" in a couple places to make it do what I want. :-) So my question is: is what I want possible to do in Python? How? I think it might be possible to rig something up by passing in the variable that i want to change as a *string* and looking up that string in a dictionary somewhere, but I think what I need is the locals () dictionary of the calling function, and I'm not sure how to get that. Thanks, Evan Driscoll -- http://mail.python.org/mailman/listinfo/python-list
Re: Object Reference question
In article , Hendrik van Rooyen wrote: >On Friday 21 August 2009 08:07:18 josef wrote: >> >> My main focus of this post is: "How do I find and use object reference >> memory locations?" > a = [1,2,3,4] id(a) >8347088 Of course, that doesn't actually allow you to do anything... -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
7stud said: python ignores the names inside a function when it creates the function. This "program" will not produce an error: def f(): print x python parses the file and creates the function object and assigns the function object to the variable f. It's not until you execute the function that python will raise an error. The same thing happens with the recursive function. Thanks for that explanation. So in the OP's example: Class Demo(object): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) _classvar = fact(5) ... no failure occurs when "fact(5)" is invoked, because the lookup of "fact" in the local scope is a class-scope-lookup, which succeeds. The failure occurs on the first recursive invocation of fact() in the statement "return n * fact(n - 1)": the function-scope-lookup of "fact" fails, and then the interpreter falls back to a global-scope-lookup of "fact", which also fails. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple IRC library
On 2009-08-24 01:39:21 -0600, devaru said: Hi all, I am new to Python language. I want to capture(either in database or a file) the conversation in IRC. Fed. Please suggest me some simple IRC library or code snippet for this. I have used the oyoyo library with success. It's pretty nice and has a framework for bots which you might be interested in looking at. http://code.google.com/p/oyoyo/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Waiting for a subprocess to exit
In article , Miles Kaufmann wrote: > >debacle[1]). Leaving shell=3DFalse makes scripts more secure and =20 >robust; besides, when I'm putting together a command and its =20 >arguments, it's as convenient to build a list (['mycmd', 'myarg']) as =20= > >it is a string (if not more so). unless you want to use "~" on Mac or Unix. -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com -- http://mail.python.org/mailman/listinfo/python-list
Re: proposal: add setresuid() system call to python
On Tue, Aug 25, 2009 at 03:03:12PM +0200, Hrvoje Niksic wrote: > You should use ctypes.get_errno() instead of os.errno; sorry about that. > > Also, when raising OSError, you should set the 'errno' attribute to the > appropriate code. How does that compare to: raise pythonapi.PyErr_SetFromErrno(py_object(OSError)) ? -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email j...@subspacefield.org to get blacklisted. pgpc0M9ykZOdl.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: your favorite debugging tool?
On 2009-08-25 06:57 AM, Esmail wrote: Michele Simionato wrote: On Aug 22, 4:25 pm, Esmail wrote: Hi all, What is your favorite tool to help you debug your code? The times when I would just use 'print' are long past. Nowadays I spend lots of my time with code written by others than myself. I use pdb all the time, and now also ipdb (ipdb is very cool if you are used to ipython). Never heard of ipdb, I'll have to check it out. It's not really a separate thing, just the pdb integration into the IPython interactive shell (which I highly recommend that you check out). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: os.popen output different from native shell output
In one of the first chapters of "Advanced programming in the unix environment (second edition)" there is explained how a unix shell works. You could write you own shell using python. This way the python interpreter gets stared only once, and not for every call to "ls". Have fun, Thomas nickname schrieb: > wow guys! thanks for all the great leads! this is awesome! > > The reason why I want to do this is because I am going to do a little > project. I will write a python script called ls which will log the > time and username and then will show the actual ls output. I want this > to be transparent and so want to throw the ls output (via python) > exactly as it will be in native shell execution. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for professsional Windows GUI apps?
On 25 Aug, 13:24, Wolfgang Keller wrote: > The area of _desktop_ database application development indeed looks like a > vast and very hostile desert in the Python landscape. Yes, you don't have drag-and-drop database tools like MS Access or FoxPro. You actually have to use a database API (such as pyodbc or pymssql) with GUI (tkinter, wxPython, PyGTK, PyQt, MFC) manually. If you need a framework for this, you should not be developing software anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: your favorite debugging tool?
On 2009-08-25 09:49 AM, Ben Finney wrote: Esmail writes: Hi Ben, Ben Finney wrote: Whenever a simple output statement is too cumbersome for debugging, I take it as a sign that the program is too cumbersome to follow. I'll have to think about this .. though my gut says this is true :-) Note that it's only a sign, *not* an ironclad guarantee. But it's the right way to bet, IME. re your other point about the interactive shell, I agree it's useful, but to me still doesn't quite do what a full-fledged debugger can - but perhaps that is a reflection of my skill with the shell at this point. This, on the other hand, I find even more consistent: if the code can't be effectively inspected from the interactive interpreter, that's a sure sign that its external interfaces are poor or its internal dependencies too tightly coupled; or more likely both. And a debugger is a great tool to help you figure out exactly why your code doesn't actually have the wonderful decoupling that you thought you designed into it so you can fix it. :-) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric literals in other than base 10 - was Annoying octal notation
On Aug 25, 9:14 am, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: > >> If you want your data file to have values entered in hex, or oct, or > >> even unary (1=one, 11=two, 111=three, =four...) you can. > > > Unary? I think you'll find that Standard Positional Number Systems are > > not defined for radix 1. > > Of course not. But unary isn't a positional number system. It's a tally > system, like my example above shows. Roman numerals are another tally > system. Like Roman numerals, the disadvantages of unary are that you > can't represent negative numbers, zero, or fractions, and anything but > addition and subtraction is difficult. But if you want to use it, perhaps > out of a sense of sadism towards your users, it's easy: > > def int2unary(n): > return '1'*n > > def unary2int(s): > n = 0 > for c in s: > if c == '1': n+=1 > else: raise ValueError('invalid unary string') > return n But without insignificant leading 0's, I fail to see the relevance of unary to this discussion. And what would you call a tally system of radix 2? Certainly not binary. > > -- > Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for professsional Windows GUI apps?
On 25 Aug, 20:30, Gilles Ganault wrote: > Combined with the comment above about issues with printing, it looks > like Python for GUI apps isn't a very good idea :-/ With pywin32, printing is the same as for any other Windows app (you get MFC for Python). -- http://mail.python.org/mailman/listinfo/python-list
Re: os.popen output different from native shell output
On Aug 25, 6:16 am, Nobody wrote: > On Tue, 25 Aug 2009 01:36:08 -0700, nickname wrote: > > I am a relative newbie to python, I am using os.popen to run an > > ls command. The output that I get using the read() function is > > different in look and feel from when I run the ls command natively > > from the shell (not via python). > > As others have pointed out, the default behaviour of ls is different if > its output is a terminal. > > > Is there an easy way to "mirror" the output. When python displays the > > output, how can it tell the bash shell that some of the entries are > > directories and they should appear blue on the bash shell, and that > > everything should not be appearing on 1 column only. > > You can get the terminal-style behaviour even when using a pipe with: > > ls -x --color > > But why are you reading this information into Python then writing it > back out to the terminal? > > If you're planning on processing the output within Python, both the > multi-column format and the escape sequences used for colour will make > such processing awkward. > > If you want to enumerate the contents of a directory within Python, use > os.listdir(). > > If you want to generate coloured output, use the curses module, e.g.: > > #!/usr/bin/env python > > import sys > import curses > > curses.setupterm() > setaf = curses.tigetstr('setaf') or "" > setab = curses.tigetstr('setab') or "" > origp = curses.tigetstr('op') or "" > > def fg(c): > sys.stdout.write(curses.tparm(setaf, c)) > > def bg(c): > sys.stdout.write(curses.tparm(setab, c)) > > def orig(): > sys.stdout.write(origp) > > # example > bg(curses.COLOR_BLUE) > fg(curses.COLOR_YELLOW) > print "hello, world" > orig() wow guys! thanks for all the great leads! this is awesome! The reason why I want to do this is because I am going to do a little project. I will write a python script called ls which will log the time and username and then will show the actual ls output. I want this to be transparent and so want to throw the ls output (via python) exactly as it will be in native shell execution. I know there's history files I can look up, but I just am exploring my own intermediate-logging-layer the functionality for which is executed right before the actual command is executed. Thanks, -A -- http://mail.python.org/mailman/listinfo/python-list
Re: Putting together a larger matrix from smaller matrices
On 2009-08-24 21:30 PM, Matjaz Bezovnik wrote: Dear all, I'm but a layman so do not take offence at this maybe over simple question. This is something which is done often in FEM methods, and the alike. I have matrix A of 3x3 elements, and B, of the same number of elements, 3x3. What would be the most obvious way to assemble a matrix which: a11 a12 a13 a21 a22 a23 a31 a32 a33+b11 b12 b13 b21 b22 b23 b31 b32 b33 (the missing elements = zero) (you see the pattern - if there was a third matrix C, it would "connect" to b33 on the main diagonal) You will certainly want to use numpy for this and ask questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists I believe that someone recently posted a recipe for constructing such "block diagonal" arrays. I think it will be included in a future release of numpy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Putting together a larger matrix from smaller matrices
On 25 Aug, 17:37, Matjaz Bezovnik wrote: > Scott, thank you very much for the snippet. > > It is exactly what I looked for; simple to read and obvious as to what > it does even a month later to a non-pythonist! Since you were talking about matrices, observe that numpy has a matrix subclass of ndarray, which e.g. changes the meaning of the * operator mean indicate matrix multiplication. Thus, >>> import numpy as np >>> np.eye(4) array([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) >>> np.matrix(np.eye(4)) matrix([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) >>> a = np.ones((4,4)) >>> a*a array([[ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]]) >>> b = np.matrix(a) >>> b*b matrix([[ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.]]) >>> b**2 matrix([[ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.]]) >>> b**4 matrix([[ 64., 64., 64., 64.], [ 64., 64., 64., 64.], [ 64., 64., 64., 64.], [ 64., 64., 64., 64.]]) In Matlab, you use .* vs. * and .^ vs. ^ to obtain the same effect. In NumPy we use different classes for arrays and matrices. Sturla Molden -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for professsional Windows GUI apps?
On Tuesday 25 August 2009 13:24, Wolfgang Keller wrote: > The area of _desktop_ database application development indeed looks like a > vast and very hostile desert in the Python landscape. > > The only framework that seems to be worth trying is Dabo. Unfortunately > there's little documentation, and that's mostly outdated. > > There's also Kiwi, but that's even less well documented. > > And GNU Enterprise essentially seems to be dead. There's also Camelot, if that's the kind of thing you're after: http://www.conceptive.be/projects/camelot David -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
On Aug 25, 12:11 pm, John Posner wrote: > Diez said: > > > > > Classes are not scopes. > > > So the above doesn't work because name resolution inside functions/methods > > looks for local variables first, then for the *global* scope. There is no > > class-scope-lookup. > > Buthttp://docs.python.org/tutorial/classes.htmlsays, in Section 9.3 "A > First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope — thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > The following example confirms this: > > class Spam(object): > clsvar_1 = 555 > clsvar_2 = clsvar_1 + 222 > > def __init__(self): > print "Spam instance initialized" > > sp = Spam() > print sp.clsvar_1, sp.clsvar_2 > > output: > Spam instance initialized > 555 777 > > Does the OP (kj) have a legitimate gripe, though? I confess that I know I guess a counter example would be something like this: y = "hello" class Demo(object): y = "goodbye" def __init__(self): self.x = 10 print y Demo() --output:-- hello > > nothing about Python's implementation -- I'm strictly a user. So it's > just a suspicion of mine that > something special enables a recursive function definition to refer to > the function's own name before the definition has been completed. > python ignores the names inside a function when it creates the function. This "program" will not produce an error: def f(): print x python parses the file and creates the function object and assigns the function object to the variable f. It's not until you execute the function that python will raise an error. The same thing happens with the recursive function. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for professsional Windows GUI apps?
On Tue, 25 Aug 2009 13:24:39 +0200, Wolfgang Keller wrote: >The area of _desktop_ database application development indeed looks like a >vast and very hostile desert in the Python landscape. > >The only framework that seems to be worth trying is Dabo. Unfortunately >there's little documentation, and that's mostly outdated. > >There's also Kiwi, but that's even less well documented. > >And GNU Enterprise essentially seems to be dead. Combined with the comment above about issues with printing, it looks like Python for GUI apps isn't a very good idea :-/ I'd be interested in checking out commercial applications written in Python for the Windows OS, if there are any. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: basic thread question
On 25 Aug, 13:33, Piet van Oostrum wrote: > I have heard about that also, but is there a Python implementation that > uses this? (Just curious, I am not using Windows.) On Windows we have three different versions of Python 2.6: * Python 2.6 for Win32/64 (from python.org) does not have os.fork. * Python 2.6 for Cygwin has os.fork, but it is non-COW and sluggish. * Python 2.6 for SUA has a fast os.fork with copy-on-write. You get Python 2.6.2 for SUA prebuilt by Microsoft from http://www.interopsystems.com. Using Python 2.6 for SUA is not without surprices: For example, the process is not executed from the Win32 subsystem, hence the Windows API is inaccessible. That means we cannot use native Windows GUI. Instead we must run an X11 server on the Windows subsystem (e.g. X- Win32), and use the Xlib SUA has installed. You can compare SUA to a stripped down Linux distro, on which you have to build and install most of the software you want to use. I do not recommend using Python for SUA instead of Python for Windows unless you absolutely need a fast os.fork or have a program that otherwise requires Unix. But for running Unix apps on Windows, SUA is clearly superior to Cygwin. Licencing is also better: Programs compiled against Cygwin libraries are GPL (unless you buy a commercial license). Program compiled against SUA libraries are not. Sturla Molden -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
We could as consistenly explain that the syntax for n in range(10) if n%3==0: body means for n in range(10): if n%3==0: body This syntax has also the benefit of avoiding an extra level of indentation (the one for the if) that bears no real meaning on a structural level. I'm sorry, I don't see what you mean about avoiding the extra level of indentation? I can see a very real structural and logical distinction that the if-block makes, and IMO it's a good thing that that needs to be set apart. On Tue, 25 Aug 2009 10:25:27 -0700, seb wrote: Tx Chris for your reply ! i am still a bit puzzle by the following. I read in http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators """Python 3.0 unifies all collection types by introducing dict and set comprehensions, similar to list comprehensions: [ n*n for n in range(5) ] # regular list comprehension [0, 1, 4, 9, 16] { n*n for n in range(5) } # set comprehension {0, 1, 4, 16, 9} { n: n*n for n in range(5) } # dict comprehension {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} """ and we can add to this list the quite similar syntax for generator expressions. On all these loop constructs, one can consistenly add filtering on a condition by adding an "if ..." after the "for ... in ..." part (and it looks to me difficult to argue, for instance, that we should not allow filtering for dict comprehesion because we could get the same result by some other construct) If the "if ..." part after the "for ... in ..." is so much used in all these list/dict/set comprehensions and in the generator expressions, it makes sense to me to have it also for the "for as a statement" syntax : [ n*n for n in range(10) if n%3 == 0] { n*n for n in range(10) if n%3 == 0} { n: n*n for n in range(10) if n%3 == 0} ( n*n for n in range(10) if n%3 == 0) for n in range(10) if n%3 == 0: print n*n In fact, we often see the list comprehension [ n*n for n in range(10) if n%3 == 0] explained as being equivalent to l = [] for n in range(10): if n%3 == 0: l.append(n) We could as consistenly explain that the syntax for n in range(10) if n%3==0: body means for n in range(10): if n%3==0: body This syntax has also the benefit of avoiding an extra level of indentation (the one for the if) that bears no real meaning on a structural level. Maybe a PEP could do the job... Sébastien -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
Diez said: Classes are not scopes. So the above doesn't work because name resolution inside functions/methods looks for local variables first, then for the *global* scope. There is no class-scope-lookup. But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A First Look at Classes": When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. The following example confirms this: class Spam(object): clsvar_1 = 555 clsvar_2 = clsvar_1 + 222 def __init__(self): print "Spam instance initialized" sp = Spam() print sp.clsvar_1, sp.clsvar_2 output: Spam instance initialized 555 777 Does the OP (kj) have a legitimate gripe, though? I confess that I know nothing about Python's implementation -- I'm strictly a user. So it's just a suspicion of mine that something special enables a recursive function definition to refer to the function's own name before the definition has been completed. It works at the module-namespace (i.e. global) level, and Diez's "toy example" shows that it works at function-namespace level: class Demo(object): def fact(n): def inner(n): if n < 2: return 1 else: return n * inner(n - 1) return inner(n) _classvar = fact(5) So why can't it work at the class-namespace level, too? (BTW, Diez, your toy example is another demonstration that there *is* a class-scope-lookup: the "def" statement binds the name "fact" in the class scope, and the assignment statement looks up the name "fact" in that scope.) -John -- http://mail.python.org/mailman/listinfo/python-list
Re: Web Services examples using "raw" xml?
John Gordon wrote: > Any suggestions? Well, yes, see the link I posted. http://effbot.org/zone/element-soap.htm That might actually be the easiest way to get your stuff done, and it avoids external dependencies (well, except for ElementTree, if you continue to use Python <= 2.4). Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
On Aug 24, 12:05 am, Mel wrote: > seb wrote: > > On Aug 23, 6:18 pm, John Posner wrote: > [ ... ] > >> How about using a generator expression instead of a list? > > >> for i in (x for x in range(10) if x > 5): > >> print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > > body > > > Is there a special reason for not doing so ? A rejected PEP ? > > Well, the Zen of Python does say > > There should be one-- and preferably only one --obvious way to do it. > > Beyond that, I refer you to Gerald M. Weinberg's _The Psychology of Computer > Programming_, specifically chapters 11 and 12, about Programming Languages, > and their design. > > The proposal creates an case where one particular pair of syntactic > constructs can be mooshed together. OK for them, but everything else > becomes an exception; what about > > while a==c if b != d: > > why not > > if b != d while a==c: > what would be the unambiguous meaning of any of these forms ? they could be interesting but I do not understand them (yet!). > or > > for a in range(7) if os.name == 'posix': > > It winds up burdening the programmers with remembering which constructs are > and which are not mooshable. Weinberg gave an example: FORTRAN had some > stringent rules for what expressions were and were not allowed as array > subscripts. The result was that many programmers couldn't remember all the > rules, and often avoided using legal forms, having forgotten they were > legal. indeed, the language features should stay as orthogonal as possible (at least as a general rule) > > Maybe the line was already crossed when list comprehensions came into being, > still, the damage is localized in a particular context: building a list. It > isn't out creating wild options in the program control flow at large. > indeed and it proved to be very useful & successful. one cannot recommend to mix all features together as a general rule but using common sense and practice, we can have some exceptions that are definitely worth. > Mel.- Hide quoted text - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
On Aug 23, 11:02 pm, Chris Rebert wrote: > On Sun, Aug 23, 2009 at 1:36 PM, seb wrote: > > On Aug 23, 6:18 pm, John Posner wrote: > >> >> Hi, > > >> >> i was wondering if there is a syntax alike: > > >> >> for i in range(10) if i > 5: > >> >> print i > > >> > You can write > > >> > for i in filter(lambda i: i > 5, range(10)): > >> > print i > > >> > but > > >> > for i in range(10): > >> > if i > 5: > >> > print i > > >> > it' better readable, and > > >> > for i in range(6,10): > >> > print i > > >> > it's event better. > > >> How about using a generator expression instead of a list? > > >> for i in (x for x in range(10) if x > 5): > >> print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > > body > > > Is there a special reason for not doing so ? A rejected PEP ? > > It's not been added since it's completely unnecessary (see the several > alternatives already presented by others). > There have been a few other mailinglist threads on adding essentially > the same syntax. None have proved fruitful. > > Cheers, > Chris > --http://blog.rebertia.com- Hide quoted text - > > - Show quoted text - On Aug 23, 11:02 pm, Chris Rebert wrote: > On Sun, Aug 23, 2009 at 1:36 PM, seb wrote: > > On Aug 23, 6:18 pm, John Posner wrote: > >> >> Hi, > > >> >> i was wondering if there is a syntax alike: > > >> >> for i in range(10) if i > 5: > >> >> print i > > >> > You can write > > >> > for i in filter(lambda i: i > 5, range(10)): > >> > print i > > >> > but > > >> > for i in range(10): > >> > if i > 5: > >> > print i > > >> > it' better readable, and > > >> > for i in range(6,10): > >> > print i > > >> > it's event better. > > >> How about using a generator expression instead of a list? > > >> for i in (x for x in range(10) if x > 5): > >> print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > >body > > > Is there a special reason for not doing so ? A rejected PEP ? > > It's not been added since it's completely unnecessary (see the several > alternatives already presented by others). > There have been a few other mailinglist threads on adding essentially > the same syntax. None have proved fruitful. > > Cheers, > Chris > --http://blog.rebertia.com- Hide quoted text - > > - Show quoted text - Tx Chris for your reply ! i am still a bit puzzle by the following. I read in http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators """Python 3.0 unifies all collection types by introducing dict and set comprehensions, similar to list comprehensions: >>> [ n*n for n in range(5) ] # regular list comprehension [0, 1, 4, 9, 16] >>> >>> { n*n for n in range(5) } # set comprehension {0, 1, 4, 16, 9} >>> >>> { n: n*n for n in range(5) } # dict comprehension {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} """ and we can add to this list the quite similar syntax for generator expressions. On all these loop constructs, one can consistenly add filtering on a condition by adding an "if ..." after the "for ... in ..." part (and it looks to me difficult to argue, for instance, that we should not allow filtering for dict comprehesion because we could get the same result by some other construct) If the "if ..." part after the "for ... in ..." is so much used in all these list/dict/set comprehensions and in the generator expressions, it makes sense to me to have it also for the "for as a statement" syntax : [ n*n for n in range(10) if n%3 == 0] { n*n for n in range(10) if n%3 == 0} { n: n*n for n in range(10) if n%3 == 0} ( n*n for n in range(10) if n%3 == 0) for n in range(10) if n%3 == 0: print n*n In fact, we often see the list comprehension [ n*n for n in range(10) if n%3 == 0] explained as being equivalent to l = [] for n in range(10): if n%3 == 0: l.append(n) We could as consistenly explain that the syntax for n in range(10) if n%3==0: body means for n in range(10): if n%3==0: body This syntax has also the benefit of avoiding an extra level of indentation (the one for the if) that bears no real meaning on a structural level. Maybe a PEP could do the job... Sébastien -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
Jean-Michel Pichavant wrote: > Diez B. Roggisch wrote >> Classes are not scopes. >> >> > Too bad, could have been handy. Nope. Because then a lot of people would write something like this: class Foo(object): def bar(self): bar() # note the missing self. And this would lead to errors because self was missing from the call to "bar". And you'd need a disambiguation for methodname/global-name-clashes. The global-statement would work, but then code could break when all of a sudden a subclass defines a method that hitherto was only known as global. So via subclassing, you introduce *arbitray* and hard to debug errors. No. I'm certain, not a good idea. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
On Wed, Aug 26, 2009 at 2:14 AM, Diez B. Roggisch wrote: > > Classes are not scopes. > > So the above doesn't work because name resolution inside functions/methods > looks for local variables first, then for the *global* scope. There is no > class-scope-lookup. Sorry, I'm coming here with sincere ignorance. If local variables and global variables are not "scopes", then what would it be? Cheers, -Xav -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
I'm not really quite sure what voodoo I did here, but my code seems to work in Python 3.1.1 in the following way: class Demo(object): def func(self, n): return n * 5 _f = func(None, 5) d = Demo() print(d._f) print(d.func(5)) # OUTPUT 25 25 So, hmm? Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: cont...@xavierho.com Website: http://xavierho.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
Diez B. Roggisch wrote Classes are not scopes. Too bad, could have been handy. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
kj wrote: I have many years of programming experience, and a few languages, under my belt, but still Python scoping rules remain mysterious to me. (In fact, Python's scoping behavior is the main reason I gave up several earlier attempts to learn Python.) Here's a toy example illustrating what I mean. It's a simplification of a real-life coding situation, in which I need to initialize a "private" class variable by using a recursive helper function. class Demo(object): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) _classvar = fact(5) This code fails to compile, with the error "global name 'fact' not defined". [snip] fact is defined within the Demo class, so to access it, you'll need to prefix it with Demo: _classvar = Demo.fact(5). The problem is, Demo will raise a NameError exception. The solution is pretty simple, cause your fact function seems to be unrelated to the Demo class : def _fact(n): # some code class Demo(object): _classvar = _fact(5) It may happen that you *want* your fact within the Demo, in you example it's not that obvious, but I think Java would allow such following patern: class Color: def __init__(self, r, g,b): pass BLACK = Color(0,0,0) It make sens from a design point of view to put BLACK in the Color namespace. But I don't think it's possible with python. You could trick the system using inheritance: class Chrome: def __init__(self, r,g,b) pass Putting all your code in the Chrome class then: class Color(Chrome): BLACK = Chrome(0,0,0) I'm not sure this is satisfying. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Web Services examples using "raw" xml?
In <4a936e84$0$31337$9b4e6...@newsspool4.arcor-online.net> Stefan Behnel writes: > > I tried WSDL.Proxy() from the SOAPpy package and eventually end up > > with this error: > > > > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, > > column 6 > Is that while parsing the WSDL file? Have you tried pushing it through an > XML parser yourself (or opening it with an XML editor) to see if it really > is XML? The 'invalid token' error happens if the argument to WSDL.Proxy() is a string containing a URL beginning with https. (It doesn't happen with a http URL, but I'm stuck with https.) As a next step, I grabbed the content from the https url in a browser, saved it to a file, inserted it into the python code as a large string, and passed that string to WSDL.Proxy(). That produced a KeyError 'targetNamespace' from this snippet of XML: http://www.w3.org/2001/XMLSchema";> http://schemas.microsoft.com/exchange/services/2006/messages"; schemaLocation="messages.xsd"/> I looked at the code and it apparently requires that the parent tag of have a targetNamespace attribute. So I made one up and added it, like so: http://www.w3.org/2001/XMLSchema"; targetNamespace="xyz"> I have no idea if this was the right thing to do, but it did let me advance to the next error: Traceback (most recent call last): File "soappytest.py", line 1020, in ? server = jrgWSDL.Proxy(wsdlFile) File "/home/gordonj/wsdl/jrgSOAPpy/jrgWSDL.py", line 75, in __init__ service = self.wsdl.services[0] File "/home/gordonj/wsdl/jrgwstools/Utility.py", line 631, in __getitem__ return self.list[key] IndexError: list index out of range After poking around in the code a bit more, I think that self.wsdl.services is supposed to be a collection of all the services offered by the wsdl, but it's actually empty, which is why it throws an error when it tries to access the first element. So that's where I'm stuck at the moment. I have no idea why self.wsdl.services isn't getting populated correctly -- or even if that's the real problem! Any suggestions? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list