ANN: MoinMoin 1.5.4 (advanced wiki engine) released
__ /\/\ ___ (_)_ __ /\/\ ___ (_)_ __ /\ / _ \| | '_ \ /\ / _ \| | '_ \ __ / /\/\ \ (_) | | | | / /\/\ \ (_) | | | | | /| |_ \/\/\___/|_|_| |_\/\/\___/|_|_| |_| |.__) == MoinMoin 1.5.4 advanced wiki engine released == MoinMoin is an easy to use, full-featured and extensible wiki software package written in Python. It can fulfill a wide range of roles, such as a personal notes organizer deployed on a laptop or home web server, a company knowledge base deployed on an intranet, or an Internet server open to individuals sharing the same interests, goals or projects. A wiki is a collaborative hypertext environment with an emphasis on easy manipulation of information. MoinMoin 1.5.4 is a bug fix release and a recommended update. The 1.5 branch brings you several new features such as the GUI editor, which allows the users to edit pages in a WYSIWYG environment, and many bug fixes. The download page: http://moinmoin.wikiwikiweb.de/MoinMoinDownload New features in 1.5.4 = * Fixes in the GUI editor. * Dashes in the username were allowed. * EmbedObject macro for embedding of all kinds of multimedia formats into the page. * Speedup of the Twisted adapter. Major bug fixes in 1.5.4 * Many GUI editor related bug fixes. * Increased docutils compatiblity. Major new features in 1.5 = * The WYSIWYG editor for wiki pages allows you to edit pages without touching the markup. Furthermore, the wiki page is not stored as HTML after editing but kept as wiki markup in order to simplify the editing process for users that cannot or do not want to use the new editor. * AutoAdmin security policy allows users to gain admin permissions on particular pages. * The new authentication system allows to add short methods that check the credentials of the user. This allowed us to add eGroupware single sign on support. * Separation of homepages into a separate wiki (in a farm) and having a single user database is supported. * A DeSpam action to allow mass-reverting of spam attacks. * PackageInstaller support for simplified installation of plugins, themes and page bundles. This enables you to decide in which languages help pages should be installed. Note that Python 2.3.0 or newer is required. For a more detailed list of changes, see the CHANGES file in the distribution or http://moinmoin.wikiwikiweb.de/MoinMoinRelease1.5/CHANGES MoinMoin History MoinMoin has been around since year 2000. The codebase was initally started by Jürgen Hermann; it is currently being developed by a growing team. Being originally based on PikiPiki, it has evolved heavily since then (PikiPiki and MoinMoin 0.1 consisted of just one file!). Many large enterprises have been using MoinMoin as a key tool of their intranet, some even use it for their public web page. A large number of Open Source projects use MoinMoin for communication and documentation. Of course there are also many private installations. More Information * Project site: http://moinmoin.wikiwikiweb.de/ * Feature list: http://moinmoin.wikiwikiweb.de/MoinMoinFeatures * Download: http://moinmoin.wikiwikiweb.de/MoinMoinDownload * DesktopEdition: http://moinmoin.wikiwikiweb.de/DesktopEdition * This software is available under the GNU General Public License v2. * Changes: http://moinmoin.wikiwikiweb.de/MoinMoinRelease1.5/CHANGES * Known bugs: * http://moinmoin.wikiwikiweb.de/KnownIssues * http://moinmoin.wikiwikiweb.de/MoinMoinBugs sent by Alexander Schremmer for the MoinMoin team -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Augument assignment versus regular assignment
nagy wrote: Thanks, Kirk. I considered the += as only a shorthand notation for the assignment operator. Since for lists + is simply a concatetation, I am not sure it x=x+[2] is creating a brand new list. Could you refer me to any documentation on this? Thanks, Nagy My habit is to check the id. x = [1,2] id(x) -1209327188 x += [4] x [1,2,4] id(x) -1209327188 x = x + [6] x [1,2,4,6] id(x) -1209334664 So it looks as if x += [] modifies the list in place, while x = x + [] creates a new list. I am not sure if this is 100% guaranteed, as I have noticed in the past that id's can be reused under certain circumstances. Perhaps one of the resident gurus can comment. Frank Millman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python *Eggs* on Win32
I got the answers myself. Thanks to http://tinyurl.com/ld2c9. With just basic installation of Python on Win32 (i.e. http://www.python.org/ftp/python/2.4.3/python-2.4.3.msi) it is possible to install .egg files (Python Eggs). 1) download http://peak.telecommunity.com/dist/ez_setup.py 2) run ez_setup.py 3) download http://cheeseshop.python.org/packages/2.4/l/lxml/lxml-1.1alpha-py2.4-static-win32.egg 4) In dos command line go to the same directory where lxml-1.1alpha-py2.4-static-win32.egg has been downloaded 5) From dos command line type d:\python24\scripts\easy_install lxml-1.1alpha.win32-static-py2.4.exe That's all. But Note: a) for running ez_setup.py (which is a bootstrap module) unrestricted Internet connection is necessary. http://peak.telecommunity.com/DevCenter/EasyInstall?action=highlightvalue=EasyInstall has all the answers. I am still not sure: a) Whether it is always sufficient to have only MinGW GCC installation on my Win XP machine and not MS Visual Studio. Best Regards, Srijit Srijit Kumar Bhadra wrote: I have browsed the following links 1) http://peak.telecommunity.com/DevCenter/EasyInstall 2) When Python *Eggs* better than Python *distutils*?? What's Eggs? (http://tinyurl.com/m8dyd) But I am still not clear what to do with an .egg file. For example, if I have a basic Python installation (http://www.python.org/ftp/python/2.4.3/python-2.4.3.msi) what should I do with a typical .egg file (e.g. http://cheeseshop.python.org/packages/2.4/l/lxml/lxml-1.1alpha-py2.4-static-win32.egg)? I have only MinGW GCC compiler on my Win XP machine. Is it mandatory to have Internet connection during installation of .egg files? Best Regards, Srijit -- http://mail.python.org/mailman/listinfo/python-list
Re: first book about python
I read almost every published book about Python and I found Magnus' Beginning Python the best book to start with. As Alex said it is particularly appreciated by those who like learning by examples and by try and error: it is actually the opposite to what Alex believed as Beginning Python is meant to be a sort of update of the previous book Practical Python. In addition and maybe before of Magnus book I would suggest A byte of Python http://www.byteofpython.info/ the best fast introduction to Python I have ever seen. Alex Martelli [EMAIL PROTECTED] ha scritto nel messaggio news:[EMAIL PROTECTED] Jake Emerson [EMAIL PROTECTED] wrote: There have been lots of recommendations for the O'Reilly book, which is a good one. However, I would recommend Beginning Python by Magnus Lie Hetland. All I knew before starting Python was Mathematica, and this book was very helpful. It may seem to start out slow, but I've found that I'm going back to those first chapters occasionally to review and practice the syntax. It, and this group, have carried me through some pretty tough problems (for me anyway). It's been worth it. Good luck. Hetland's books are excellent, particularly if you like to learn by example -- I believe the current one Practical Python is meant to supersede the earlier Beginning Python (but I'm not sure). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Augument assignment versus regular assignment
Frank Millman wrote: nagy wrote: Thanks, Kirk. I considered the += as only a shorthand notation for the assignment operator. Since for lists + is simply a concatetation, I am not sure it x=x+[2] is creating a brand new list. Could you refer me to any documentation on this? Thanks, Nagy My habit is to check the id. x = [1,2] id(x) -1209327188 x += [4] x [1,2,4] id(x) -1209327188 x = x + [6] x [1,2,4,6] id(x) -1209334664 So it looks as if x += [] modifies the list in place, while x = x + [] creates a new list. I am not sure if this is 100% guaranteed, It is. This is true for any mutable type. as I have noticed in the past that id's can be reused under certain circumstances. Perhaps one of the resident gurus can comment. -- http://mail.python.org/mailman/listinfo/python-list
Scope, type and UnboundLocalError
Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing a list in similar circumstances. The documentation: http://docs.python.org/ref/naming.html does not give me enough info to determine why the difference exists as it does not seem to mention types at all.. The code: = scope_and_type.py === m = 0 n = [0] def int_access0(): m = m + 1 return m def int_access1(): m += 1 return m def list_access0(): n[0] = n[0] + 1 return n def list_access1(): n[0] += 1 return n try: print \nint_access0:, int_access0() except UnboundLocalError, inst: print ERROR:\n, inst try: print \nint_access1:, int_access1() except UnboundLocalError, inst: print ERROR:\n, inst try: print \nlist_access0:, list_access0() except UnboundLocalError, inst: print ERROR:\n, inst try: print \nlist_access1:, list_access1() except UnboundLocalError, inst: print ERROR:\n, inst print \n (m,n) = , (m,n) p = (0,) def tuple_access(): return p[0] try: print \ntuple_acces:, tuple_access() except UnboundLocalError, inst: print ERROR:\n, inst print \n p = , p = END scope_and_type.py === The output: int_access0: ERROR: local variable 'm' referenced before assignment int_access1: ERROR: local variable 'm' referenced before assignment list_access0: [1] list_access1: [2] (m,n) = (0, [2]) tuple_acces: 0 p = (0,) -- http://mail.python.org/mailman/listinfo/python-list
Running multiple versions of Python on the same host..
For my day job I am forced to run RHEL3 (and Centos3 on my desktop). I want to be able to use a few applications that require Python 2.4.X but RHEL3 ships with Python 2.2.3. I have tried to install and upgrade Python 2.4.X many ways like using PyVault and doing a source based install but each way has been fraught with problems from weird dependency issues to screwing up 'yum'. What is the best way to run multiple version of Python on the same system? thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Paddy wrote: Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing a list in similar circumstances. There has just been a long thread about this. I think I understand it now. Here is my explanation. Ignoring nested scopes for this exercise, references to objects (i.e. variable names) can exist in the local namespace or the global namespace. Python looks in the local namespace first, and if not found looks in the global namespace. Any name assigned to within the function is automatically deemed to exist in the local namespace, unless overridden with the global statement. With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. With the statement 'n[0] = n[0] + 1', n is not being assigned to, as it is mutable. Therefore Python looks in the global namespace, finds n there, and uses it successfully. My 2c Frank Millman -- http://mail.python.org/mailman/listinfo/python-list
subprocess returncode always None
Dear All, I'm currently working on a project that needs to collect the output of the JHOVE application. More information about the application is available at this website: http://hul.harvard.edu/jhove/ The application is written in Java and is executed by a shell script. There are occasions where this application may get stuck in an infinite loop. For this reason I've been trying to implement a simple class that I can use to execute the JHOVE application and if it doesn't complete in the required period of time to raise an exception and kill the process. The class is as follows, apologies for the odd line wrapping. snip class niceSubprocess(object): A class that implements a call to the subprocess method with a timeout - command, the command to execute - params, the parameters to pass to the application - timeout, the amount of time in seconds to wait def executeCommand(self, command, params, timeout): try: timeElapsed = 0 process = subprocess.Popen((command, params), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, close_fds = True) while process.poll() == None and timeElapsed timeout: print process.poll() #print process.stdout.read() timeElapsed = timeElapsed + 1 time.sleep(1) if process.poll() == None: # kill off the process, and don't be terribly nice about it os.kill(process.pid, signal.SIGKILL) raise timeoutError, timeout else: if process.stdout.read() == : raise executeError, process.stderr.read() else: return process.stdout.read() except Exception, errorInfo: # pass the exception to the calling code raise errorInfo /snip I'm running this on Linux and through the use of top can see the JAVA process start and complete. The problem I have is that process.poll() always returns None, even though the application has successfully ran and returned output. Can anyone shed some light on why the call to the shell script always returns None as a return code? With thanks. -Corey -- Corey Wallis RUBRIC Technical Officer University of Southern Queensland http://www.rubric.edu.au http://techxplorer.wordpress.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Frank Millman wrote: Paddy wrote: Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing a list in similar circumstances. With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. With the statement 'n[0] = n[0] + 1', n is not being assigned to, as it is mutable. Therefore Python looks in the global namespace, finds n there, and uses it successfully. My 2c Frank Millman So, to paraphrase to test my understanding: in the statement: ' n[0] = n[0] + 1' it is the object referenced by the name n that is being assigned to rather than n itself, so n is not 'tagged' as a local variable by the LHS of the assignment. Thanks Frank. all is is now clear :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: How properly manage memory of this PyObject* array?? (C extension)
[EMAIL PROTECTED] wrote: Suppose a C extension locally built an array of PyObject* 's as follows... my_array = malloc(n * sizeof(PyObject*)); for (i = 0; i n; i++) { my_array[i] = PyList_New(0); } Q1: Must I do a Py_DECREF(my_array[i]) on all elements before exiting this C extension function? if you're releasing my_array before existing, yes. (What if the elements got used in other objects?) if other parts of your program storing pointers to the elements in your array, those parts must make sure to increment the reference count when copying the pointer. that's the whole point of reference counting, of course: the count for an object should, at all times, match the number of *active* references your program has to that object. Q2: Must I do free(my_array); at end of function?? unless some other part of your program holds on to it, of course you have to release it. it's a bit surprising that you have to ask this, really -- any C tutorial should explain how malloc/free works. What if my_array[i]'s are used in other objects so that I can't necessarily just nuke it!!! if those other objects do proper reference counting, everything will work find. if they don't, your program will crash sooner or later, no matter what you do in the function that allocates my_array. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Augument assignment versus regular assignment
Frank Millman wrote: So it looks as if x += [] modifies the list in place, while x = x + [] creates a new list. objects can override the += operator (by defining the __iadd__ method), and the list type maps __iadd__ to extend. other containers may treat += differently, but in-place behaviour is recommended by the language reference: An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. /F -- http://mail.python.org/mailman/listinfo/python-list
xml aggregator
Hi all, I am trying to write an xml aggregator, but so far, i've been failing miserably. what i want to do : i have entries, in a list format :[[key1,value],[key2,value],[ key3,value]], value] example : [[route,23],[equip,jr2],[time,3pm]],my first value] [[route,23],[equip,jr1],[time,3pm]],my second value] [[route,23],[equip,jr2],[time,3pm]],my third value] [[route,24],[equip,jr2],[time,3pm]],my fourth value] [[route,25],[equip,jr2],[time,3pm]],'my fifth value] the tree i want in the end would be : results route id=23 equip id=jr2 time id=3pm datamy first value/data datamy third value/data /time /equip equip id=jr1 time id=3pm datamy second value/data /time /equip route id=24 equip id=jr2 time id=3pm datamy fourthvalue/data /time /equip route id=25 equip id=jr2 time id=3pm datamy fifth value/data /time /equip /results If anyone has an idea of implemetation or any code ( i was trying with ElementTree... thank you so much -- http://mail.python.org/mailman/listinfo/python-list
WANTED: logging of all file operations on Windows
I am aware, that it is maybe the wrong group to ask this question, but as I would like to know the history of past file operations from within a Python script I see a chance, that someone in this group was into it already and is so kind to share here his experience. I have put already much efforts into this subject googling around, but up to now in vain. Best option I encountered yet is usage of the Greyware 'System Change Log' service which monitors disks for changes (http://www.greyware.com/software/systemchangelog/index.asp), but in own tests it turned out, that the created log file does not cover all file events as e.g. it is not possible to detect when a file is moved to a new directory (creation of a new file is logged, but deletion is not, not mentioning I would expect a file 'move' event). The own Windows logging service rejected to start on my XP SP2 system for unknown to me reasons - I don't know how to get it to work (yes, I have used the administrator account). I can't believe, that using NTFS file system in Microsoft Windows 2000 or XP it is not possible to track file events as: - updating/modifying of an existing file/directory - deleting an existing file/directory - creating a new file/directory - _moving_ an existing file/directory (should _NOT_ be covered by the event duo of deleting an existing and creating a new file/directory) Any hints towards enlightenment? Claudio Grondi -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance error: class Foo has no attribute bar
Il Sun, 09 Jul 2006 04:24:01 GMT, crystalattice ha scritto: I can't see why it's saying this because Character.__init__(self) not only has self.attrib_dict = {} but it also calls the setAttribute method explicitly for each attribute name. If I do a print out of the dictionary just for Character, the attributes are listed. Are you sure attrib_dict is a class attribute? Aren't you defining it in charachter's __init__ method, thus making it an instance attribute? -- Alan Franzoni [EMAIL PROTECTED] - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E - Blog: http://laterradeglieroi.verdiperronchi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: I thought I'd 'got' globals but...
Luis M. González a écrit : Bruno Desthuilliers wrote: def doIt(name=None): global gname if name is None: name = gname else: gname = name Sorry for this very basic question, but I don't understand why I should add the global into the function body before using it. You have to do it if you intend to rebind the name in the function's body (else this would create the name in the local namespace). This function works even if I don't add the global. Just to try this out, I wrote this variant: gname = 'Luis' def doIt2(name=None): if name is None: name = gname return name Please read more carefully the OP's code: gname = 'Sue' def doIt(name = gname): global gname gname = name print 'doIt name', name, 'gname', gname As you can see, it rebinds gname. print doIt2() -- returns Luis. So, what's the point of writing the function this way instead? def doIt2(name=None): global gname if name is None: name = gname return name In this case, you don't need the global statement (but keeping it makes clear you're using a global name, which is not a bad thing in itself...) Now if it's about LOCs count, here's a shorter equivalent: doIt3 = lambda name : (name, gname)[name is None] -- http://mail.python.org/mailman/listinfo/python-list
Re: I thought I'd 'got' globals but...
Luis M. González a écrit : (snip) OK, so I should include the global only if I plan to modify it. Otherwise, I don't need to include it. Am I right? s/modify/rebind/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Frank Millman a écrit : Paddy wrote: Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing a list in similar circumstances. There has just been a long thread about this. I think I understand it now. Here is my explanation. Ignoring nested scopes for this exercise, references to objects (i.e. variable names) can exist in the local namespace or the global namespace. Python looks in the local namespace first, and if not found looks in the global namespace. Any name assigned to within the function is automatically deemed to exist in the local namespace, unless overridden with the global statement. And this even of the local bindings sequentially comes after another access to the name, ie: g = 0 def fun(): x = g # UnboundLocalError here g += 1 return x With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. Right With the statement 'n[0] = n[0] + 1', n is not being assigned to, Right as it is mutable. n is effectively mutable, but this is totally irrelevant. In your snippet, n is not 'assigned to', it's mutated (ie a state-modifying method is called). The snippet: n[0] = n[0] + 1 is syntactic sugar for n.__setitem__(0, n.__getitem__(0) + 1) IOW, it's just method calls on n. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Paddy a écrit : Frank Millman wrote: Paddy wrote: Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing a list in similar circumstances. With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. With the statement 'n[0] = n[0] + 1', n is not being assigned to, as it is mutable. Therefore Python looks in the global namespace, finds n there, and uses it successfully. My 2c Frank Millman So, to paraphrase to test my understanding: in the statement: ' n[0] = n[0] + 1' it is the object referenced by the name n that is being assigned to rather than n itself, so n is not 'tagged' as a local variable by the LHS of the assignment. Nope. You got it plain wrong - cf my answer to Frank in this thread. Thanks Frank. all is is now clear :-) It is obviously not. -- http://mail.python.org/mailman/listinfo/python-list
can't pickle instancemethod objects
Pickling an instance of a class, gives can't pickle instancemethod objects. What does this mean? How do I find the class method creating the problem? -- http://mail.python.org/mailman/listinfo/python-list
Re: first book about python
In article [EMAIL PROTECTED], IOANNIS MANOLOUDIS [EMAIL PROTECTED] wrote: I want to learn python. I plan to buy a book. I always find printed material more convenient than reading on-line tutorials. I don't know PERL or any other scripting language. I only know some BASH programming. I am looking for a book which will help me get started and should contain the foundations. I am not looking for the Python bible. Any recommendations? If you're willing to wait 1.5 months, _Python for Dummies_ will be the first book that really covers Python 2.5. (Alex's _Python in a Nutshell_ does cover some of Python 2.5, but there were a fair number of late changes that came after he needed to turn it in, most notably the inclusion of sqlite3. It's also not a beginner book.) -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ I saw `cout' being shifted Hello world times to the left and stopped right there. --Steve Gonedes -- http://mail.python.org/mailman/listinfo/python-list
HTTPBasicAuthHandler doesn't work
Hi ! I'm trying to add the HTTP basic authentification to my web spider but it doesn't work... The HTTPBasicAuthHandler don't send the headers for authentification :-( Here is the code : http://devloop.lyua.org/releases/lswww_urllib2.py def __init__(self,rooturl,firsturl=[],forbidden=[],proxy={},cookie=,auth_basic=[]): root=rooturl self.excluded=forbidden self.proxy=proxy self.cookie=cookie self.auth_basic=auth_basic if root[-1]!=/: root+=/ if(self.checklink(root)): print Invalid link argument sys.exit(0) for lien in firsturl: if(self.checklink(lien)): print Invalid link argument sys.exit(0) server=(root.split(://)[1]).split(/)[0] self.root=root self.server=server director = urllib2.OpenerDirector() director.add_handler(urllib2.HTTPHandler()) director.add_handler(urllib2.HTTPSHandler()) if self.proxy!={}: director.add_handler(urllib2.ProxyHandler(self.proxy)) if self.auth_basic!=[]: auth=urllib2.HTTPBasicAuthHandler(urllib2.HTTPPasswordMgrWithDefaultRealm()) auth.add_password(None, self.root, self.auth_basic[0], self.auth_basic[1]) director.add_handler(auth) if self.cookie!=: cj = cookielib.LWPCookieJar() if os.path.isfile(self.cookie): cj.load(self.cookie,ignore_discard=True) director.add_handler(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(director) Where is the problem ? Thanks ! -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
Antoon Pardon [EMAIL PROTECTED] (AP) wrote: AP It is conceptually different. In the line 'a = b' you don't need to AP search for the scope of a. You know it is the current scope, if you Except when it has been declared global. AP want to know the scope of b on the other hand, you need to search AP for statement where it is assigned to. AP Sure you can set things up in the interpreter so that the same search AP routine is used, but that is IMO an implementation detail. Well, it is not. But I can understand the confusion. Namely, `a = b' introduces a binding for `a' in the local scope, unless `a' was declared global. So the search will find `a' in the local scope and it stops there. On the other hand `a.b = c' will not introduce a binding for `a'. So the search for `a' may stop in the local space (if there was another binding for `a' in the local scope) or it may need to continue to outer scopes. The difference, however is not the complicatedness of the lefthand side but whether the local scope contains a binding for the variable. AP The complicatedness of the lefthand side, decided on whether the AP variable was introduced in the local scope or not during startup AP time. So that complicatedness decided whether the search was AP to stop at the local level or not. No, it doesn't. There could be another binding in the same scope. The complicatedness of this particular assignment doesn't decide anything about how to search for 'a', but rather the presence or absence of a binding anywhere in the scope. -- Piet van Oostrum [EMAIL PROTECTED] URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance error: class Foo has no attribute bar
On Sun, 09 Jul 2006 04:24:01 +, crystalattice wrote: I've finally figured out the basics of OOP; I've created a basic character creation class for my game and it works reasonably well. Now that I'm trying to build a subclass that has methods to determine the rank of a character but I keep getting errors. I want to redefine some attributes from the base class so I can use them to help determine the rank. However, I get the error that my base class doesn't have the dictionary that I want to use. I've tried several things to correct it but they don't work (the base class is called Character and the subclass is called Marine): Without seeing your class definitions, it is hard to tell what you are doing, but I'm going to take a guess: you're defining attributes in the instance instead of the class. E.g. class Character(): def __init__(self): self.attrib_dict = {} attrib_dict is now an instance attribute. Every instance will have one, but the class doesn't. I'm thinking you probably want something like this: class Character(): attrib_dict = {} def __init__(self): pass Now attrib_dict is an attribute of the class. However, it also means that all instances will share the same values! Here's one possible solution to that: class Character(): default_attribs = {} def __init__(self): self.attribs = self.default_attribs.copy() Now there is one copy of default character attributes, shared by the class and all it's instances, plus each instance has it's own unique set of values which can be modified without affecting the defaults. Hope this clears things up for you. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
scheduling accuracy for audio
Dear all, I have created a large Python-based GUI project and I'd like to use it as a GUI interface for real time audio sequencing (using the SuperCollider -SC- synthesis server). Python (the client) and SC (the server) can communicate via OSC protocol (there are available implementations). SC will generate events responding to Python messages. In order to have sequencing I have to send at precise timing messages from Python to SC. Obviously, being a musical application, I need millisecond time accuracy, with less latency as possible or at least a fixed (short) latency. More, I need to have multithreading, with many processes sending messages from Python to SC. I know that I can create a similar architecture in Python with sched and time modules, using scheduler class and .sleep method. But I was wondering: how precise will be timing? Is .sleep suitable for audio/music. Any hints? Thanks a lot Best -a- Andrea Valle DAMS - Facoltà di Scienze della Formazione Università degli Studi di Torino http://www.semiotiche.it/andrea [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: can't pickle instancemethod objects
On Sun, 09 Jul 2006 05:45:27 -0700, Jim Lewis wrote: Pickling an instance of a class, gives can't pickle instancemethod objects. What does this mean? It means you can't pickle instance methods. How do I find the class method creating the problem? How about you post the complete stack trace of the exception? Chances are it will contain much useful information. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: can't pickle instancemethod objects
How about you post the complete stack trace of the exception? Exception in Tkinter callback Traceback (most recent call last): File C:\program files\python\lib\lib-tk\Tkinter.py, line 1345, in __call__ return self.func(*args) File C:\Public\world.py, line 1832, in BtnGo DoBtnGo() File C:\Public\world.py, line 1812, in DoBtnGo if DoPickle: SavePickle () File C:\Public\world.py, line 1817, in SavePickle pickle.dump (pop,f) File C:\program files\python\lib\pickle.py, line 1382, in dump Pickler(file, protocol, bin).dump(obj) File C:\program files\python\lib\pickle.py, line 231, in dump self.save(obj) File C:\program files\python\lib\pickle.py, line 293, in save f(self, obj) # Call unbound method with explicit self File C:\program files\python\lib\pickle.py, line 739, in save_inst save(stuff) File C:\program files\python\lib\pickle.py, line 293, in save f(self, obj) # Call unbound method with explicit self File C:\program files\python\lib\pickle.py, line 663, in save_dict self._batch_setitems(obj.iteritems()) File C:\program files\python\lib\pickle.py, line 677, in _batch_setitems save(v) File C:\program files\python\lib\pickle.py, line 293, in save f(self, obj) # Call unbound method with explicit self File C:\program files\python\lib\pickle.py, line 614, in save_list self._batch_appends(iter(obj)) File C:\program files\python\lib\pickle.py, line 629, in _batch_appends save(x) File C:\program files\python\lib\pickle.py, line 293, in save f(self, obj) # Call unbound method with explicit self File C:\program files\python\lib\pickle.py, line 739, in save_inst save(stuff) File C:\program files\python\lib\pickle.py, line 293, in save f(self, obj) # Call unbound method with explicit self File C:\program files\python\lib\pickle.py, line 663, in save_dict self._batch_setitems(obj.iteritems()) File C:\program files\python\lib\pickle.py, line 677, in _batch_setitems save(v) File C:\program files\python\lib\pickle.py, line 313, in save rv = reduce(self.proto) File C:\program files\python\lib\copy_reg.py, line 69, in _reduce_ex raise TypeError, can't pickle %s objects % base.__name__ TypeError: can't pickle instancemethod objects -- http://mail.python.org/mailman/listinfo/python-list
Re: Mechanize-Browser question..
bruce wrote: r2 = br.follow_link(url_regex=re.compile(r\*),nr=1) Seems to me your regex is buggy. You are using a raw string yet you still escape the asterisk ('*') with a backslash? This will only match a string which contains an asterisk, while I'm guessing you're tring to match all strings. Try removing the backslash. P.S. In future postings, be more verbose: What are you trying to do? What is the unexpected behavior that you are seeing? etc. - Tal -- http://mail.python.org/mailman/listinfo/python-list
concatenate Numeric
Hi, I am trying to build a large array using concatenate function in python. So as I loop over the number of arrays, of which there are 12 (4 down and 3 across), I create 3 long arrays by concatenating them at the bottom and then concatenating them side by side: for ind in range(num_arrays): if ind == 0: bias_down1 = array(bias) ppslon1= array(ppslon) ppslat1= array(ppslat) elif ind 0 and = 3: bias_down1 = concatenate((bias_down1,bias),0) ppslon1= concatenate((ppslon1,ppslon),0) ppslat1= concatenate((ppslat1,ppslat),0) elif ind == 4: bias_down2 = array(bias) ppslon2= array(ppslon) ppslat2= array(ppslat) elif ind 4 and ind = 7: bias_down2 = concatenate((bias_down2,bias),0) ppslon2= concatenate((ppslon2,ppslon),0) ppslat2= concatenate((ppslat2,ppslat),0) elif ind == 8: bias_down3 = array(bias) ppslon3= array(ppslon) ppslat3= array(ppslat) elif ind 8: bias_down3 = concatenate((bias_down3,bias),0) ppslon3= concatenate((ppslon3,ppslon),0) ppslat3= concatenate((ppslat3,ppslat),0) bias_a = concatenate((bias_down1,bias_down2),1) # joining the arrays side by side bias_all = concatenate((bias_a,bias_down3),1) ppslat_a = concatenate((ppslat1,ppslat2),1) ppslat_all = concatenate((ppslat_a,ppslat3),1) ppslon_a = concatenate((ppslon1,ppslon2),1) ppslon_all = concatenate((ppslon_a,ppslon3),1) print 'Max lat', max(max(ppslat_all)), '\t','Min lat', min(min(ppslat_all)) print 'Max lon', max(max(ppslon_all)), '\t','Min lon', min(min(ppslon_all)) * Now this works, the array size is correct but the longitude values given for max and min are wrong. What is even stranger to me is that when I write the array in binary format to a file and read it with Matlab, the max and min are correct but when I read it back with python the max and min are again incorrect for only the longitude data. I saved the max and min for the longitude for each array and then check it in the python program and they are correct at the end but the max(max(ppslon)) values is incorrect. Does anyone knows why this is so? If I was doing something wrong then Matlab would not have returned correct values. Any help is appreciated! /Sheldon -- http://mail.python.org/mailman/listinfo/python-list
Re: python/xpath question...
(Damn gmane's authorizor, I think I lost four postings because the auth messages went to my work email address (and I thought the authorization was supposed to be one-time only per group anyway??). I deleted them as spam since I hadn't posted from there for days :-( Grrr. At least I could reconstruct this one...) bruce [EMAIL PROTECTED] writes: for guys with python/xpath expertise.. i'm playing with xpath.. and i'm trying to solve an issue... i have the following kind of situation where i'm trying to get certain data. i have a bunch of tr/td... i can create an xpath, that gets me all of the tr.. i only want to get the sibling tr up until i hit a 'tr' that has a 'th' anybody have an idea as to how this query might be created?.. [...] ((//tr/th)[2]/../following-sibling::tr/td/..)[count(.|((//tr/th)[3]/../preceding-sibling::*))=count((//tr/th)[3]/../preceding-sibling::*)] which makes use of the following idiom for writing an intersection: $set1[count(.|$set2)=count($set2)] and gets the second group in the sequence you describe. IMHO, this illustrates what happens when XPath is pushed too far ;-) I don't see an easier way, but perhaps I missed one. Example code: (Note that the expression used here doesn't get any trailing group of tr elements if there's no terminating tr/th -- that fits your specification, but may not be what you really wanted. To fix that, meditate on the above expression for an hour or two 0.8 wink.) #- def xpath(path, source): import StringIO import pprint from lxml import etree f = StringIO.StringIO(source) tree = etree.parse(f) r = tree.xpath(path) #return \n.join(etree.tostring(el) for el in r) return pprint.pformat([etree.tostring(el) for el in r]) simple = \ html trthA/th/tr trtdB/td/tr trtdC/td/tr trthD/th/tr trtdE/td/tr trtdF/td/tr trthG/th/tr trtdH/td/tr trtdI/td/tr /html for i in range(3): expr = '((//tr/th)[%s]/../following-sibling::tr/td/..)[count(.|((//tr/th)[%s]/../preceding-sibling::*))=count((//tr/th)[%s]/../preceding-sibling::*)]' % (i+1, i+2, i+2) print - print xpath(expr, simple) #- john[0]$ tst.py - ['trtdB/td/tr\n', 'trtdC/td/tr\n'] - ['trtdE/td/tr\n', 'trtdF/td/tr\n'] - [] Knowing what you're doing, though, you'd probably be better off with BeautifulSoup than XPath. Also note that mechanize (which I know you're using) only supports BeautifulSoup 2 at present. You can't use BeautifulSoup 3 yet (I hope to fix that 'RSN'). John -- http://mail.python.org/mailman/listinfo/python-list
Re: concatenate Numeric
Sheldon skrev: Hi, I am trying to build a large array using concatenate function in python. So as I loop over the number of arrays, of which there are 12 (4 down and 3 across), I create 3 long arrays by concatenating them at the bottom and then concatenating them side by side: for ind in range(num_arrays): if ind == 0: bias_down1 = array(bias) ppslon1= array(ppslon) ppslat1= array(ppslat) elif ind 0 and = 3: bias_down1 = concatenate((bias_down1,bias),0) ppslon1= concatenate((ppslon1,ppslon),0) ppslat1= concatenate((ppslat1,ppslat),0) elif ind == 4: bias_down2 = array(bias) ppslon2= array(ppslon) ppslat2= array(ppslat) elif ind 4 and ind = 7: bias_down2 = concatenate((bias_down2,bias),0) ppslon2= concatenate((ppslon2,ppslon),0) ppslat2= concatenate((ppslat2,ppslat),0) elif ind == 8: bias_down3 = array(bias) ppslon3= array(ppslon) ppslat3= array(ppslat) elif ind 8: bias_down3 = concatenate((bias_down3,bias),0) ppslon3= concatenate((ppslon3,ppslon),0) ppslat3= concatenate((ppslat3,ppslat),0) bias_a = concatenate((bias_down1,bias_down2),1) # joining the arrays side by side bias_all = concatenate((bias_a,bias_down3),1) ppslat_a = concatenate((ppslat1,ppslat2),1) ppslat_all = concatenate((ppslat_a,ppslat3),1) ppslon_a = concatenate((ppslon1,ppslon2),1) ppslon_all = concatenate((ppslon_a,ppslon3),1) print 'Max lat', max(max(ppslat_all)), '\t','Min lat', min(min(ppslat_all)) print 'Max lon', max(max(ppslon_all)), '\t','Min lon', min(min(ppslon_all)) * Now this works, the array size is correct but the longitude values given for max and min are wrong. What is even stranger to me is that when I write the array in binary format to a file and read it with Matlab, the max and min are correct but when I read it back with python the max and min are again incorrect for only the longitude data. I saved the max and min for the longitude for each array and then check it in the python program and they are correct at the end but the max(max(ppslon)) values is incorrect. Does anyone knows why this is so? If I was doing something wrong then Matlab would not have returned correct values. Any help is appreciated! /Sheldon Sorry, there is a small error when I wrote this part of the program: should say ind = 3 /sheldon -- http://mail.python.org/mailman/listinfo/python-list
Re: python/xpath question...
Stefan Behnel [EMAIL PROTECTED] writes: [...] I'm not quite sure how this is supposed to be related to Python, but if you're trying to find a sibling, what about using the sibling axis in XPath? nit There's no sibling axis in XPath. I'm sure you meant following-sibling and/or preceding-sibling. /nit John -- http://mail.python.org/mailman/listinfo/python-list
Re: first book about python
I thank everybody for your replies. I think I'll get Hertland's book since it's newer than O'reillys. I don't want to become a programmer. Neither Python is part of my studies. I've finished with my studies. I want to become a Unix/Linux admin and knowledge of either Python or Perl is an asset. Do you think that this book is the right one for me? Ioannis -- http://mail.python.org/mailman/listinfo/python-list
Remembering History in code.InteractiveConsole
I'd like to make code.InteractiveConsole function just like the normal Python console. However, when I try to use the arrow keys to recall command history, all I get is ^[[A^[[B. I've seen the example at http://docs.python.org/lib/readline-example.html but this doesn't seem to work at all, although I don't really want to persist command history across sessions anyways. Is it possible to remember command history with IC? I'm on Linux. Any help is appreciated. Thanks, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: xml aggregator
kepioo wrote: Hi all, I am trying to write an xml aggregator, but so far, i've been failing miserably. what i want to do : i have entries, in a list format :[[key1,value],[key2,value],[ key3,value]], value] example : [[route,23],[equip,jr2],[time,3pm]],my first value] [[route,23],[equip,jr1],[time,3pm]],my second value] [[route,23],[equip,jr2],[time,3pm]],my third value] [[route,24],[equip,jr2],[time,3pm]],my fourth value] [[route,25],[equip,jr2],[time,3pm]],'my fifth value] [snip example data] If anyone has an idea of implemetation or any code ( i was trying with ElementTree... (You should have posted the code you tried) The code below might help (though you should test it more than I have). The 'findall' function comes from here: http://gflanagan.net/site/python/elementfilter/elementfilter.py it's not the elementtree one. Gerard -- X = route,23],[equip,jr2],[time,3pm]],my first value], [[[route,23],[equip,jr1],[time,3pm]],my second value], [[[route,23],[equip,jr2],[time,3pm]],my third value], [[[route,24],[equip,jr2],[time,3pm]],my fourth value], [[[route,25],[equip,jr2],[time,3pm]],my fifth value], [[[route,25],[equip,jr2],[time,4pm]],my sixth value]] # reshape the data records = [] for info, data in X: record = [] for attr, val in info: record.append(val) record.append( data ) records.append( record ) for r in records: print r from elementtree.ElementTree import Element, SubElement, tostring from elementfilter import findall results = Element('results') for r in records: routeid, equipid, timeid, data = r route, equip, time = None, None, None existing_route = findall(results, [EMAIL PROTECTED]'%s'] % routeid) if existing_route: route = existing_route[0] existing_equip = findall(route, [EMAIL PROTECTED]'%s'] % equipid) if existing_equip: equip = existing_equip[0] existing_time = findall(equip, [EMAIL PROTECTED]'%s'] % timeid) if existing_time: time = existing_time[0] route = route or SubElement(results, 'route', id=routeid) equip = equip or SubElement(route, 'equip', id=equipid) time = time or SubElement(equip, 'time', id=timeid) data = SubElement(time,'data') data.text = item print tostring(results) --- -- http://mail.python.org/mailman/listinfo/python-list
Re: xpath question...
bruce [EMAIL PROTECTED] writes: i have the following section of test code where i'm trying to get the attribute of a frame frame src= i'm trying to print/get the src value. the xpath query that i have displays the src attribute in the Xpather/Firefox plugin. however, i can't quite figure out how to get the underlying value in my test app... sxpath = /html/frameset/frame[2]/attribute::src # s contains HTML not XML text d = libxml2dom.parseString(s, html=1) #get the tr list tr1 = d.xpath(sxpath) url = tr1[0] #get the url/link semester page #link = br.find_link(nr=1) #url = link.url print link = ,url sys.exit() err output link = libxml2dom.Attribute object at 0xb7b7680c -- i'm not sure what i need to add to the line url = tr1 to resolve the issue/error... It *looks* like err output is just a string you typed into your message? If so, that's not an error in the usual sense (there's no traceback): rather, it's just output you didn't expect. When somebody what you wrote, though, they must go through the following laborious thought process: Is that string part of the literal text output by your program, or are you indicating that you saw a traceback that contains the following line (link = ...)? Or is it something you just typed in to your message to indicate that the result is unexpected to you? If there's a traceback, post the full traceback. If that is the literal output, you should say so explicitly, or make it clear through copy/paste of a shell session: $ my-test-prog.py err output link = libxml2dom.Attribute object at 0xb7b7680c $ Back to your problem: The output is not unexpected, though (though I don't know libxml2dom). First, if you're bent on using XPath, you may be better off with module lxml, which I think is a more recent and friendlier wrapper of libxml2 / libxslt. Second, you're almost there: you're just getting back an object representing the attribute, rather than the string you're looking for. You simply need to ask the object for its string representation. How that's done depends on the module, but it looks like you have to call a method explicitly in this case (I can't find the libxml2dom docs easily). John -- http://mail.python.org/mailman/listinfo/python-list
Re: python guru for urllib/mechanize
bruce [EMAIL PROTECTED] writes: i'm trying to get the pages from a site axess.stanford.edu, and i'm running into problems. i've got some test code that allows me to get the 1st few pages. i'm having an issue when i run into a page that somehow interprets a url from a src of a frameset. i can't seem to mimic/implement this kind of function... if you have expertise with http/web fetching, i'd appreciate any thoughts/comments/etc... In the absence of a guru, you'll have to me ;-) I've replied on the wwwsearch-general list, where you also posted. John -- http://mail.python.org/mailman/listinfo/python-list
Re: can't pickle instancemethod objects
On Sun, 09 Jul 2006 07:06:25 -0700, Jim Lewis wrote: How about you post the complete stack trace of the exception? Exception in Tkinter callback Traceback (most recent call last): File C:\program files\python\lib\lib-tk\Tkinter.py, line 1345, in __call__ return self.func(*args) File C:\Public\world.py, line 1832, in BtnGo DoBtnGo() File C:\Public\world.py, line 1812, in DoBtnGo if DoPickle: SavePickle () File C:\Public\world.py, line 1817, in SavePickle pickle.dump (pop,f) I'd suggest that pop could be your culprit. At least, that's where I'd start looking. What is pop? A function or an instance method? I can't reproduce your error exactly -- the closest I get is TypeError: can't pickle function objects when I try to pickle a method. Possibly that's just a change in error message, which is not guaranteed to be constant across Python versions. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Module for creating a screenshot of a web page given a URL?
[EMAIL PROTECTED] writes: Untestetd, but I'm pretty sure something like this will do. If you need more control, and on windows, try pywinauto I do need it to run on Windows. I'll check out pywinauto. Thanks. Note he didn't say you *need* pywinauto to run on Windows. John -- http://mail.python.org/mailman/listinfo/python-list
class members vs instance members
Ive spent a few days going thru a couple of Python tutorials. No problem until I got to classes. I guess my java mindset is blocking my vision. I've borrowed another thread's code snippet and cannot explain the results: class MyClass: list = [] myvar = 10 def add(self, x): self.list.append(x) self.myvar = x def printer(self): print self.list print self.myvar a = MyClass() b = MyClass() for n in range(20): a.add(n) print list in a: a.printer() print list in b: b.printer() This produces: list in a: list in a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 19 list in b: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 10 WHY do the class members list and myvar seem to behave differently? Given the way that list[] is supposedly shared why doesnt myvar exhibit the same behavior? It seems that myvar is acting like a true instance member. Is this simply because of the underlying types? TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
On 2006-07-09, Piet van Oostrum [EMAIL PROTECTED] wrote: Antoon Pardon [EMAIL PROTECTED] (AP) wrote: AP It is conceptually different. In the line 'a = b' you don't need to AP search for the scope of a. You know it is the current scope, if you Except when it has been declared global. Yes, I ignored that possibilitym because as far as I understood we were discussing variables in intermediate scopes. AP want to know the scope of b on the other hand, you need to search AP for statement where it is assigned to. AP Sure you can set things up in the interpreter so that the same search AP routine is used, but that is IMO an implementation detail. Well, it is not. But I can understand the confusion. Namely, `a = b' introduces a binding for `a' in the local scope, unless `a' was declared global. So the search will find `a' in the local scope and it stops there. On the other hand `a.b = c' will not introduce a binding for `a'. So the search for `a' may stop in the local space (if there was another binding for `a' in the local scope) or it may need to continue to outer scopes. The difference, however is not the complicatedness of the lefthand side but whether the local scope contains a binding for the variable. AP The complicatedness of the lefthand side, decided on whether the AP variable was introduced in the local scope or not during startup AP time. So that complicatedness decided whether the search was AP to stop at the local level or not. No, it doesn't. There could be another binding in the same scope. Indeed there could be. But I hoped you would understand I was just keeping things simple, with a simple example. The complicatedness of this particular assignment doesn't decide anything about how to search for 'a', but rather the presence or absence of a binding anywhere in the scope. I'll word it differently. If the compiler encounters a line like 'a = b' then you know from that line alone that the search space for a will be limited to the local scope. If you encounter a line like 'a.c = b' then you have no such knowledge. A line like 'a = b' will cause the compilor that at call time variable a will be added to the local scope, a line like 'a.c = b' will not have that effect. So a line like 'a = b' has an influence on what the search space is for variable a, while a line like 'a.c = b' doesn't. So the complicatedness on the leftside decides whether or not the compilor will take certain actions with regards to the search space of the variable on the left side. And yes I'm again ignoring global. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: class members vs instance members
hdixon a écrit : Ive spent a few days going thru a couple of Python tutorials. No problem until I got to classes. I guess my java mindset is blocking my vision. Then http://dirtsimple.org/2004/12/python-is-not-java.html I've borrowed another thread's code snippet and cannot explain the results: class MyClass: class MyClass(object): list = [] This may not be too harmful in the given context, nut shadowing builtin types may not be a good idea. myvar = 10 def add(self, x): self.list.append(x) list is a class attribute. It's shared by all instances of MyClass. This is a FAQ AFAICT. self.myvar = x This creates an instance attribute named myvar that shadows the class attribute of the same name (snip expected results) WHY do the class members list and myvar seem to behave differently? cf above. And notice that in Python, binding (aka 'assignement') and name lookup on objects are different beasts. There have been quite a few threads about this recently. Given the way that list[] is supposedly shared why doesnt myvar exhibit the same behavior? Because binding to self.myvar creates the instance attribute myvar. Notice that you have not rebound list. It seems that myvar is acting like a true instance member. It is one. Is this simply because of the underlying types? Nope, it's because in the first case (MyClass.list, accessed as self.list) you just call methods on the list object, which has no effect on the binding. -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
you want a directory watching daemon. it isn't hard at all to build from scratch. first, determine which directories should be watched. then, os.walk each directory, building a mapping from filename to mtime [modified time; os.path.getmtime]. next is your main event loop. this while loop consists of os.walk-ing each directory again, comparing the current mtime to the corresponding entry in the mapping. if they differ, or if a filename isn't in the mapping, something happened, at which point you can logick out whether a file was moved, deleted, changed, or created. so many folks have looked for this that i'll just write a generic one and put it in the cheeseshop. look for dirmon in about a week. Claudio Grondi wrote: I am aware, that it is maybe the wrong group to ask this question, but as I would like to know the history of past file operations from within a Python script I see a chance, that someone in this group was into it already and is so kind to share here his experience. I have put already much efforts into this subject googling around, but up to now in vain. Best option I encountered yet is usage of the Greyware 'System Change Log' service which monitors disks for changes (http://www.greyware.com/software/systemchangelog/index.asp), but in own tests it turned out, that the created log file does not cover all file events as e.g. it is not possible to detect when a file is moved to a new directory (creation of a new file is logged, but deletion is not, not mentioning I would expect a file 'move' event). The own Windows logging service rejected to start on my XP SP2 system for unknown to me reasons - I don't know how to get it to work (yes, I have used the administrator account). I can't believe, that using NTFS file system in Microsoft Windows 2000 or XP it is not possible to track file events as: - updating/modifying of an existing file/directory - deleting an existing file/directory - creating a new file/directory - _moving_ an existing file/directory (should _NOT_ be covered by the event duo of deleting an existing and creating a new file/directory) Any hints towards enlightenment? Claudio Grondi -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
On 2006-07-08, Dennis Lee Bieber [EMAIL PROTECTED] wrote: On 8 Jul 2006 18:52:56 GMT, Antoon Pardon [EMAIL PROTECTED] declaimed the following in comp.lang.python: I'm not fooled by that phrase. I just think the mutate vs rebind explanation is not complete. If we have two statements a = b and c.d = b the fact that a is being rebound while c is mutated doesn't explain why we allow c to be searched out of the local scope. The search is not different, per se... It is only after the object is found that the difference becomes apparent -- a rebinding changes an object's ID, and is not permitted for a non-local UNLESS a global statement appears before any usage of the name. c.d =... has absolutely no effect on the ID of object C; in that aspect it is a read-only look-up of c. IOWs, the same look-up as would be used if c were on the RHS of the statement. be searched in local space so that code like the following would throw: UnboundLocalError: local variable 'c' referenced before assignment c = SomeObject def f(): c.a = 5 What would you say the behavior should be for: c.a = c.b vs la = c.b The look-up of c is the same on both sides of the statement; local (not found) then global (found), THEN the operation is applied. On both sides c is a read-only look-up (that is, no changes to the ID of c -- no rebinding -- take place). Are you suggesting we need to use global c in order to have c.b on the RHS? By that logic, we would also need global sys to reference sys.argv inside a function definition. Remember -- the modules loaded by import are just more SomeObject samples... I think you are misunderstanding what I was getting at. This example was not meant to illustrate how I think python should behave. I thought I had made that clear. When someone gets confused over the difference between rebinding or mutating a variable on an intermediate scope, the explanation he mostly seems to get boils down to: one is rebinding, the other is mutation, this is a fundametal difference in python. My impression is that they seem to say that the fundamental difference between mutation and rebinding implies the specific behaviour python has now. IMO this explanation is incomplete. The python developers could have chosen that a line like 'c.a = ...' would have resulted in c being included in the local scope. Then rebinding and mutation would still be fundamentally different from each other but the specific confusion over why 'k[0] = ...' worked as expeced but 'k = ...' didn't, will disappear. So I only used this example as an illustration why I think the usual explanation is not completed. This example is not to be taken as an illustration of how I think python should behave. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: can't pickle instancemethod objects
On Sun, 09 Jul 2006 08:39:29 -0700, Jim Lewis wrote: I'd suggest that pop could be your culprit. ...What is pop? A function or an instance method? Neither. pop is an instance of a class, like: class X: ... pop = X () pop surely is the culprit but it has arrays of objects, etc., and I don't know what to look for. I'd start by looking for an attribute of pop that holds a reference to some function or method. E.g. something like this: class X(): def method(self): pass def __init__(self): self.L = [1, a, X.method] # note the lack of ()s pop = X() Otherwise, I'm working blind without knowing more about your class. Here's a thought: comment out every attribute in your class, and then try pickling it. If it succeeds, uncomment just *one* attribute, and try pickling again. Repeat until pickling fails. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: xml aggregator
Gerard Flanagan wrote: kepioo wrote: Hi all, I am trying to write an xml aggregator, but so far, i've been failing miserably. what i want to do : i have entries, in a list format :[[key1,value],[key2,value],[ key3,value]], value] example : [[route,23],[equip,jr2],[time,3pm]],my first value] [[route,23],[equip,jr1],[time,3pm]],my second value] [[route,23],[equip,jr2],[time,3pm]],my third value] [[route,24],[equip,jr2],[time,3pm]],my fourth value] [[route,25],[equip,jr2],[time,3pm]],'my fifth value] [snip example data] If anyone has an idea of implemetation or any code ( i was trying with ElementTree... (You should have posted the code you tried) The code below might help (though you should test it more than I have). The 'findall' function comes from here: http://gflanagan.net/site/python/elementfilter/elementfilter.py it's not the elementtree one. Sorry, elementfilter.py was a bit broken - fixed now. Use the current one and change the code I posted to: [...] existing_route = findall(results, [EMAIL PROTECTED] % routeid) #changed line if existing_route: route = existing_route[0] existing_equip = findall(route, [EMAIL PROTECTED]'%s'] % equipid) if existing_equip: [...] ie. don't quote the route id since it's numeric. Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: first book about python
Aahz [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], IOANNIS MANOLOUDIS [EMAIL PROTECTED] wrote: I want to learn python. I plan to buy a book. I always find printed material more convenient than reading on-line tutorials. I don't know PERL or any other scripting language. I only know some BASH programming. I am looking for a book which will help me get started and should contain the foundations. I am not looking for the Python bible. Any recommendations? If you're willing to wait 1.5 months, _Python for Dummies_ will be the first book that really covers Python 2.5. (Alex's _Python in a Nutshell_ does cover some of Python 2.5, but there were a fair number of late changes that came after he needed to turn it in, most notably the inclusion of sqlite3. It's also not a beginner book.) I confirm on both scores: the Nutshell is not meant for beginners to programming (it _may_ be used by experienced programmers whose experience comes from other languages, but it may be a stretch even for them, depending on what other languages are exactly); and, the new 2nd edition of the Nutshell does not cover well the big additions to Python 2.5's standard library (ctypes and etree, as well as sqlite) -- it barely _mentions_ them as late-breaking developments, with pointers to online docs. Stef's and Aahz's for Dummies will be a good book for beginners (many people have prejudices against the whole for Dummies series, perhaps exactly because of their titles!, but, really, there ARE many good books in that series, if you can just accept the titles as well-natured, innocuous humor!) -- I only looked at a subset of its chapters, so I don't know in particular how well it teaches sqlite, ctypes and etree, but the materials I _did_ look at were excellent. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: first book about python
IOANNIS MANOLOUDIS [EMAIL PROTECTED] wrote: I thank everybody for your replies. I think I'll get Hertland's book since it's newer than O'reillys. I don't want to become a programmer. Neither Python is part of my studies. I've finished with my studies. I want to become a Unix/Linux admin and knowledge of either Python or Perl is an asset. Knowledge of _both_ languages is even better for this specific task: many existing sysadm scripts are in Perl, and you may well be working side by side with other, more senior admis who are dyed-in-the-wool Perl hackers (since Perl is so very popular with that crowd). Do you think that this book is the right one for me? Actually, particularly if you have any interest at all in possibly working in a mixed-platforms environment (including some Macs and/or Windows boxes as well as Linux), you might be better served by http://www.oreilly.com/catalog/perlsysadm/ -- at least if you accept my suggestion to get SOME familiarity with Perl as well as with Python. Yes, Perl IS harder to learn, BUT -- if you've already decided to learn both languages, starting with the harder one need not be a bad idea (the Romans' legions, back when they were the best soldiers in the world, trained with armor and weapons *heavier* than the ones they actually used in the field -- being used to heavier stuff gave them more agility and stamina when it most mattered, in battle and on long marches!-). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: cookielib incorrectly escapes cookie
BJörn Lindqvist [EMAIL PROTECTED] writes: I have some very serious trouble getting cookes to work. After a lot of work (urllib2 is severly underdocumented, arcane and overengineerd btw) I'm finally able to accept cookes from a server. But I'm still And a good day to you too ;-) In passing, there's a new HOWTO document on urllib2 here, which you may find helpful: http://svn.python.org/view/python/trunk/Doc/howto/urllib2.rst?rev=46062view=markup Doesn't seem to be part of the build process yet, so not available yet in nicely-formatted HTML form on the python.org website -- I guess it's included in HTML format in 2.5 beta1, though. Note that that document is substantially rewritten over the version that was originally on Michael's web site, from which the HOWTO originally came. I haven't checked the version on Michael's website has been updated recently, so use the version linked to above instead. unable to return them to a server. Specifically the script im trying to do logs on to a server, get a session cookie and then tries to access a secure page using the same session cookie. But the cookie header cookielib produces is very different from the header it received. Well (sigh), I didn't make all that up, you know ;-) Believe it or not, that's what's supposed to happen if you send Version=1 cookies (though few browsers ever supported it). In case it's your own server, I should note that I don't know of any reason for an internet server ever to send Version=1 cookies, given what the majority of browsers actually do. However, since the cookie protocols (plural) are, in practice, ill-defined (which is no individual's fault, really), cases that work in popular browsers should usually be fixed. Please test to make sure your problem goes away with Python 2.5 beta1: I believe this bug is already fixed. Please do try it though: it's unlikely that anybody else has tested the fix. I think beta2 is due on Wednesday 12th, so it's advisable to get in quick if you want this to work in 2.5 (please Cc: me personally to let me know whether it works for you). Note that it should work for you in Python 2.5 if and only if (not rfc2965 or rfc2109_as_netscape) is true, where rfc2109_as_netscape and rfc2965 are constructor arguments of DefaultCookiePolicy. To understand why (on some level, anyway), read the in-development docs for DefaultCookiePolicy here: http://docs.python.org/dev/lib/module-cookielib.html Thanks for the report. If you'd like a better workaround than the one you have for older Pythons, I'll be happy to post one if you'll test this with 2.5 (no good deed goes unpunished ;-) [...] # Here is where it doesn't work unless the hack is applied. The cookie # header that is sent without the hack looks like this: # # Cookie: $Version=1; SessionId=\66b908e5025d93ed\; $Path=/ # # It is not accepted by the server, probably because the SessionID # string is wrong. There is a bug here, I think: I think the quoting is indeed incorrect, but probably not for the reason you expect (also, on a separate point, the funny-looking $Version and $Path are at least strictly correct, and for example my copy of the lynx browser does send them). I won't try to explain the details here. Since the fix would likely be complicated and risky, and of benefit only in very unusual circumstances, I don't intend to fix it at this stage of the Python release process. It will not affect you when using Python 2.5, as long as (not rfc2965 or rfc2109_as_netscape) is true (see above for the definition of those names). That's true by default in 2.5, so all you should need is: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) opener.open(http://www.example.com/;) (Unless you want to get at the CookieJar, e.g. to load and save cookies), in which case go ahead and override the default CookieJar by passing one to the HTTPCookieProcessor as you do in the code you posted.) I also note that you're adding an HTTPCookieProcessor, *and* also calling .add_cookie_header(). HTTPCookieProcessor's job is to call .add_cookie_header() / .extract_cookies() for you (even on redirects, where you never get the opportunity to do it manually). You never need to call those functions yourself if using urllib2. HTH! John -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
Claudio Grondi wrote: I am aware, that it is maybe the wrong group to ask this question, but as I would like to know the history of past file operations from within a Python script I see a chance, that someone in this group was into it already and is so kind to share here his experience. I can't believe, that using NTFS file system in Microsoft Windows 2000 or XP it is not possible to track file events as: - updating/modifying of an existing file/directory - deleting an existing file/directory - creating a new file/directory - _moving_ an existing file/directory (should _NOT_ be covered by the event duo of deleting an existing and creating a new file/directory) Any hints towards enlightenment? Claudio Grondi On the offchance that you haven't seen it, you might look at this: http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges but since it doesn't fulfil your criterion of *not* representing renames by a delete and an add, it may well not be suitable. Apart from that, I think it does what you want. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: HTTPBasicAuthHandler doesn't work
[EMAIL PROTECTED] writes: Hi ! I'm trying to add the HTTP basic authentification to my web spider but it doesn't work... The HTTPBasicAuthHandler don't send the headers for authentification :-( Hi Several bugs were fixed with Basic auth in Python 2.5. I'd be most grateful if you can verify that your program works with Python 2.5 beta1: http://www.python.org/download/releases/2.5/ Please let me know either way whether or not it works for you with the 2.5 beta1 (beta2 is coming very soon, so get in quick if you want to help make sure this works right in future!). Below are a couple of tips unrelated to your question. By the way, s/authentification/authentication/ :-) Here is the code : http://devloop.lyua.org/releases/lswww_urllib2.py def __init__(self,rooturl,firsturl=[],forbidden=[],proxy={},cookie=,auth_basic=[]): root=rooturl self.excluded=forbidden self.proxy=proxy self.cookie=cookie self.auth_basic=auth_basic if root[-1]!=/: root+=/ if(self.checklink(root)): print Invalid link argument sys.exit(0) for lien in firsturl: if(self.checklink(lien)): More Pythonic for checklink to raise ValueError here than return non-zero. print Invalid link argument sys.exit(0) server=(root.split(://)[1]).split(/)[0] [...] Better to use module urlparse. John -- http://mail.python.org/mailman/listinfo/python-list
language design question
I am comparing Python to a few other scripting languages, and used a simple anagrams program as a sample. I was surprised ast a few python features that did not work as I would expect/wish; which caused less compact/expressive program styles that I wanted - reverting to a FORTRAN like series of assignments. For example, - why is len() not a member function of strings? Instead one says len(w). - Why doesn't sort() return a value? This would allow things like: key = '',join( list(word.lower().strip()).sort() ) instead: key = ... key.sort() key = ... - Another feature I assumed but it failed, is a nice default for dictionaries, and more += like operations; For example: to acculumate words in a dictionary - dict[key] += [word] Instead of: mark[key] = mark.get(key,[]) + [word] The former seems very intuitive, and clearer. I am a bit used to the compactness and convenient defaults of Perl, which would do this: my $key = join '', sort(split(//, lc($word))); push @{$anagrams{$key}}, $word I am curious why these obvious conveniences are not present. :-) Thansk for any context or insight. Best, Gregory Perl is great, and == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
Re: first book about python
[EMAIL PROTECTED] (Alex Martelli) writes: Yes, Perl IS harder to learn, BUT -- if you've already decided to learn both languages, starting with the harder one need not be a bad idea (the Romans' legions, back when they were the best soldiers in the world, Learning Perl is actually a very well-written book for beginning programmers. The only thing wrong with it is it's about Perl... -- http://mail.python.org/mailman/listinfo/python-list
Re: scheduling accuracy for audio
andrea valle [EMAIL PROTECTED] writes: In order to have sequencing I have to send at precise timing messages from Python to SC. Obviously, being a musical application, I need millisecond time accuracy, with less latency as possible or at least a fixed (short) latency. More, I need to have multithreading, with many processes sending messages from Python to SC. You really can't get that kind of accuracy with a non-realtime OS. The way this is handled in actual audio applications the sound board has a fair amount of buffering, so you send the right number of samples and precise scheduling isn't so important. -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Gregory Guthrie wrote: For example, - why is len() not a member function of strings? Instead one says len(w). Why would ``x.len()`` be any more convenient than ``len(x)``? Your preference here seems pretty arbitrary. - Why doesn't sort() return a value? This would allow things like: key = '',join( list(word.lower().strip()).sort() ) Use sorted(): key = ','.join(sorted(word.lower().strip())) - Another feature I assumed but it failed, is a nice default for dictionaries, and more += like operations; For example: to acculumate words in a dictionary - dict[key] += [word] Get Python 2.5 and use collections.defaultdict: Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import collections d = collections.defaultdict(int) d['a'] += 5 d['b'] += 2 d defaultdict(type 'int', {'a': 5, 'b': 2}) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Gregory Guthrie a écrit : I am comparing Python to a few other scripting languages, and used a simple anagrams program as a sample. I was surprised ast a few python features that did not work as I would expect/wish; which caused less compact/expressive program styles that I wanted - reverting to a FORTRAN like series of assignments. For example, - why is len() not a member function of strings? Instead one says len(w). The member function of strings is __len__, which itself is called by len() when passed a string. wrt/ why it is so, you'll have to ask to someone more knowledgeable, but I seriously don't see what difference it make in practice. - Why doesn't sort() return a value? If it's not in the FAQ, then it should - and the googling c.l.py archives for this should give some relevant answers. This would allow things like: key = '',join( list(word.lower().strip()).sort() ) key = ''.join(list(sorted(word.lower().strip())) - Another feature I assumed but it failed, is a nice default for dictionaries, and more += like operations; For example: to acculumate words in a dictionary - dict[key] += [word] Instead of: mark[key] = mark.get(key,[]) + [word] mark.setdefault(key, []).append(word) The former seems very intuitive, and clearer. and is much more error prone for few practical gain (assertion backed by experience with languages allowing it). I am a bit used to the compactness and convenient defaults of Perl, which would do this: my $key = join '', sort(split(//, lc($word))); push @{$anagrams{$key}}, $word key = ''.join(list(sorted(word.lower().strip())) anagrams.setdefault(key, []).append(word) I am curious why these obvious conveniences are not present. :-) You said ?-) -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
faulkner [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] you want a directory watching daemon. it isn't hard at all to build from scratch. first, determine which directories should be watched. then, os.walk each directory, building a mapping from filename to mtime [modified time; os.path.getmtime]. next is your main event loop. this while loop consists of os.walk-ing each directory again, comparing the current mtime to the corresponding entry in the mapping. if they differ, or if a filename isn't in the mapping, something happened, at which point you can logick out whether a file was moved, deleted, changed, or created. so many folks have looked for this that i'll just write a generic one and put it in the cheeseshop. look for dirmon in about a week. While I am a fan of brute force -- http://mail.python.org/mailman/listinfo/python-list
array of array of float
i used C too much and haven't used Python for a while... like in C, if we want an array of array of float, we use float a[200][500]; now in Python, seems like we have to do something like a = [ [ ] ] * 200 and then just use a[1].append(12.34) etc but it turns out that all 200 elements points to the same list... and i have to use a = [ ] for i in range (0, 200): a.append([ ]) is there a simpler way... i wonder... -- http://mail.python.org/mailman/listinfo/python-list
Re: array of array of float
[EMAIL PROTECTED] wrote: i used C too much and haven't used Python for a while... like in C, if we want an array of array of float, we use float a[200][500]; now in Python, seems like we have to do something like a = [ [ ] ] * 200 and then just use a[1].append(12.34) etc but it turns out that all 200 elements points to the same list... and i have to use a = [ ] for i in range (0, 200): a.append([ ]) is there a simpler way... i wonder... this is FAQ: http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list /F -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
faulkner [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] you want a directory watching daemon. it isn't hard at all to build from scratch. first, determine which directories should be watched. then, os.walk each directory, building a mapping from filename to mtime [modified time; os.path.getmtime]. next is your main event loop. this while loop consists of os.walk-ing each directory again, comparing the current mtime to the corresponding entry in the mapping. if they differ, or if a filename isn't in the mapping, something happened, at which point you can logick out whether a file was moved, deleted, changed, or created. so many folks have looked for this that i'll just write a generic one and put it in the cheeseshop. look for dirmon in about a week. Ahem... (sorry for premature usenet-post-ication...) While I am a big fan of brute force, there are OS services (at least on Windows) for doing just this function, with asynchronous callbacks when files are created, deleted, etc. Here is a link that does a much better comparison of several options than I could (including your brute force version): http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html Good luck! -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Size of hard drive and Mp3 tags functions
I'm creating a Python program to pick a random set of mp3s, to copy to my mp3 player, so I can regularly get a new set to listen to. Anyway, there are two sorts of functions that could be useful. 1) A function that gives the size of a hard drive (or other drive, in this case the mp3 player itself), and/or the space remaining. 2)A function/functions to read the ID tags of an MP3 file. Doesn't anyone here know if functions like that exist for Python? Ideally these would be built-in functions, or in the modules that come with Python. This is for Windows by the way. John Hicken -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Bruno Desthuilliers wrote: Frank Millman a écrit : Paddy wrote: Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing a list in similar circumstances. There has just been a long thread about this. I think I understand it now. Here is my explanation. Ignoring nested scopes for this exercise, references to objects (i.e. variable names) can exist in the local namespace or the global namespace. Python looks in the local namespace first, and if not found looks in the global namespace. Any name assigned to within the function is automatically deemed to exist in the local namespace, unless overridden with the global statement. And this even of the local bindings sequentially comes after another access to the name, ie: g = 0 def fun(): x = g # UnboundLocalError here g += 1 return x With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. Right With the statement 'n[0] = n[0] + 1', n is not being assigned to, Right as it is mutable. n is effectively mutable, but this is totally irrelevant. In your snippet, n is not 'assigned to', it's mutated (ie a state-modifying method is called). The snippet: n[0] = n[0] + 1 is syntactic sugar for n.__setitem__(0, n.__getitem__(0) + 1) IOW, it's just method calls on n. So, An assignment statement may assign an object to a name, in which case the name is 'tagged' as being local, An assignment statement may mutate a mutable object already bound to a name, in which case the assignment will not 'tag' the name as being local. I guess Bruno, you mean irrelevant as in 'although only mutable objects can have their state modified; if n has a mutable value but the assignment statement changed the object referred to by n, then the name would be tagged as local'? - Peace, Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Paddy wrote: So, An assignment statement may assign an object to a name, in which case the name is 'tagged' as being local, An assignment statement may mutate a mutable object already bound to a name, in which case the assignment will not 'tag' the name as being local. I guess Bruno, you mean irrelevant as in 'although only mutable objects can have their state modified; if n has a mutable value but the assignment statement changed the object referred to by n, then the name would be tagged as local'? - Peace, Paddy. No, that last paragraph still does not convey what I meant. ... irrelevant as in 'although only mutable objects can have their state modified; if n has a mutable value but the assignment statement changed n to refer to another object, then the name would be tagged as local'? Oh bosh, can anyone come at it from a different tack? Ta. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Paddy wrote: ... irrelevant as in 'although only mutable objects can have their state modified; if n has a mutable value but the assignment statement changed n to refer to another object, then the name would be tagged as local'? Oh bosh, can anyone come at it from a different tack? look for Assignment of an object to a single target is recursively defined as follows on this page (or at the corresponding page in the language reference): http://pyref.infogami.com/assignments /F -- http://mail.python.org/mailman/listinfo/python-list
Re: array of array of float
[EMAIL PROTECTED] wrote: i used C too much and haven't used Python for a while... like in C, if we want an array of array of float, we use float a[200][500]; now in Python, seems like we have to do something like a = [ [ ] ] * 200 and then just use a[1].append(12.34) etc but it turns out that all 200 elements points to the same list... and i have to use a = [ ] for i in range (0, 200): a.append([ ]) is there a simpler way... i wonder... Right, try the numpy module, and you can do: from numpy import * a = zeros((200,500), Float) documentation: http://numeric.scipy.org/numpydoc/numpy-6.html#pgfId-60291 download: http://sourceforge.net/project/showfiles.php?group_id=1369package_id=175103 main page: http://numeric.scipy.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: class members vs instance members
Bruno Desthuilliers wrote: hdixon a écrit : Ive spent a few days going thru a couple of Python tutorials. No problem until I got to classes. I guess my java mindset is blocking my vision. Then http://dirtsimple.org/2004/12/python-is-not-java.html I've borrowed another thread's code snippet and cannot explain the results: class MyClass: class MyClass(object): list = [] This may not be too harmful in the given context, nut shadowing builtin types may not be a good idea. myvar = 10 def add(self, x): self.list.append(x) list is a class attribute. It's shared by all instances of MyClass. This is a FAQ AFAICT. self.myvar = x This creates an instance attribute named myvar that shadows the class attribute of the same name (snip expected results) WHY do the class members list and myvar seem to behave differently? cf above. And notice that in Python, binding (aka 'assignement') and name lookup on objects are different beasts. There have been quite a few threads about this recently. Given the way that list[] is supposedly shared why doesnt myvar exhibit the same behavior? Because binding to self.myvar creates the instance attribute myvar. Notice that you have not rebound list. It seems that myvar is acting like a true instance member. It is one. Is this simply because of the underlying types? Nope, it's because in the first case (MyClass.list, accessed as self.list) you just call methods on the list object, which has no effect on the binding. ok - i think its beginning to dawn on me. BTW - the blog above was a good read for me. I _am_ trying to bring java into the mix and its screwing me up big time. I'll go back over the chapters that dicuss binding/name lookups. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
Antoon Pardon [EMAIL PROTECTED] (AP) wrote: AP When someone gets confused over the difference between rebinding or AP mutating a variable on an intermediate scope, the explanation he AP mostly seems to get boils down to: one is rebinding, the other is AP mutation, this is a fundametal difference in python. AP My impression is that they seem to say that the fundamental difference AP between mutation and rebinding implies the specific behaviour python AP has now. IMO this explanation is incomplete. The python developers AP could have chosen that a line like 'c.a = ...' would have resulted AP in c being included in the local scope. Then rebinding and mutation AP would still be fundamentally different from each other but the specific AP confusion over why 'k[0] = ...' worked as expeced but 'k = ...' didn't, AP will disappear. That seems nonsense to me. If they had chosen that 'c.a = ...' would imply that c would become a local variable, what would the value of c have to be then, if there was no prior direct assignment to c? Would it become a new binding like in 'c = ...'? From what class should it become an instance? Or would it become a copy of the value that 'c' has in an outer scope? I don't know any programming language where an assignment to c.a does create a new c, rather than modifying the existing value of c. That would have been a very strange language design. Similarly for 'k[0] = ...'. What would happen with the other elements of k? There are no situations in Python where an assignment to c.a or c[0] suddenly lets spring c into existence. You always need an already existing binding for c for this to be valid. And it always uses that binding, and doesn't move or copy it to a different block. Some of the confusing originates from the fact that assignment in Python is subtly different from assignment in other programming languages. In most languages variables denote memory locations or collections of memory locations. An assignment then means changing the contents of those memory locations. In python variables are bound to values, and assignment means (re)binding the name to a possibly different value. With an example: most other languages have boxes with the name of the variable on them. An assignment changes the contents of the box. In Python you have values (objects) and an assignment means sticking a label with the name of the variable on the object. Often the difference is unnoticable, but there are subtle cases where this really makes a difference. When the lefthandside of an assignment is an object attribute, subscription or slice then the assignment is syntactic sugar for a mutation operation implemented by the object, which usually changes the value of the object but could do something completely different. (Finally, the lefthandside can also be a [nested] tuple or list, in which case it is a collection of parallel assignments. And oh yes, there are also other binding operations e.g. a function or class definition.) -- Piet van Oostrum [EMAIL PROTECTED] URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Paddy a écrit : Bruno Desthuilliers wrote: Frank Millman a écrit : Paddy wrote: Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing a list in similar circumstances. There has just been a long thread about this. I think I understand it now. Here is my explanation. Ignoring nested scopes for this exercise, references to objects (i.e. variable names) can exist in the local namespace or the global namespace. Python looks in the local namespace first, and if not found looks in the global namespace. Any name assigned to within the function is automatically deemed to exist in the local namespace, unless overridden with the global statement. And this even of the local bindings sequentially comes after another access to the name, ie: g = 0 def fun(): x = g # UnboundLocalError here g += 1 return x With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. Right With the statement 'n[0] = n[0] + 1', n is not being assigned to, Right as it is mutable. n is effectively mutable, but this is totally irrelevant. In your snippet, n is not 'assigned to', it's mutated (ie a state-modifying method is called). The snippet: n[0] = n[0] + 1 is syntactic sugar for n.__setitem__(0, n.__getitem__(0) + 1) IOW, it's just method calls on n. So, An assignment statement may assign an object to a name, An assignment statement binds an object to a name. in which case the name is 'tagged' as being local, Unless that names has been declared as global or lives in another namespace (ie is an element of a mutable collection or an attribute of another object). An assignment statement may mutate a mutable object already bound to a name, in which case the assignment will not 'tag' the name as being local. consider this code: class Foo(object): def __init__(self, baaz): self.baaz = baaz def bar(foo, bak): foo.baaz = bak Which name is getting rebound here ? foo, or foo.baaz ? I guess Bruno, you mean irrelevant as in 'although only mutable objects can have their state modified; if n has a mutable value but the assignment statement changed the object referred to by n, then the name would be tagged as local'? Unless the name has been declared as global, yes. -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Gregory Guthrie wrote: I am comparing Python to a few other scripting languages, and used a simple anagrams program as a sample. I was surprised ast a few python features that did not work as I would expect/wish; which caused less compact/expressive program styles that I wanted - reverting to a FORTRAN like series of assignments. SNIP The former seems very intuitive, and clearer. I am a bit used to the compactness and convenient defaults of Perl, which would do this: my $key = join '', sort(split(//, lc($word))); push @{$anagrams{$key}}, $word I am curious why these obvious conveniences are not present. :-) Thansk for any context or insight. Best, Gregory Perl is great, and You might try looking for anagram programs written by Python programmers and compare them to anagram programs written by peoplle thatknow and use other languages. That way you might get around the fact that Python is a unique language with its own way of doing things. If you now one language and try and apply its idioms to another then you are bound to think that the other language is less good at solving prolblems in the first languages way. Googling for Python Anagram, brought up http://www.voidspace.org.uk/python/nanagram.html#demo-version maybe you should look at the source code to nanagram for comparison. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
tk filesave dialog triggers unexpected destroy event
The following behavior surprised me. I have a Tk window and launch a file save dialog from it. When the filesave dialog is finished, it calls callbacks bound to the destroy event on the main window. Is this expected, and can I avoid this? To expose the problem, run this script and click the mouse button over the application window. When the file save dialog is through, the function callback is called, which I did not expect because I bound this callback to the window destroy event. Thanks for any advice. Using Tk 1.177 JDH import Tkinter as Tk from tkFileDialog import asksaveasfilename def button(event): fname = asksaveasfilename( title='Save the figure' ) window = Tk.Tk() frame = Tk.Frame(window, width=500,height=500) frame.bind('Button-1', button) frame.pack() def callback(*args): print 'called callback' window.bind(Destroy, callback) window.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Weekly Python Patch/Bug Summary
Patch / Bug Summary ___ Patches : 393 open (+15) / 3315 closed (+17) / 3708 total (+32) Bugs: 908 open (+22) / 5975 closed (+49) / 6883 total (+71) RFE : 223 open ( -1) / 229 closed ( +2) / 452 total ( +1) New / Reopened Patches __ test_grp.py doesn't skip special NIS entry, fails (2006-06-22) http://python.org/sf/1510987 opened by Mat Martineau socket.gethostbyaddr fix for machines with incomplete DNS (2006-06-23) http://python.org/sf/1511317 opened by Charles Schwieters Speed up decimal object construction (2006-06-25) CLOSED http://python.org/sf/1511853 opened by Nick Coghlan ast branch changed interactive module name (2006-06-25) http://python.org/sf/1512007 opened by Jp Calderone Improves an error message from setattr (2006-06-26) http://python.org/sf/1512942 opened by Alexander Belopolsky [FIX][Bug 1512695] cPickle.loads seg. faults (2006-06-27) CLOSED http://python.org/sf/1513206 opened by Faik Uygur Remove reduce() (2006-06-27) CLOSED http://python.org/sf/1513249 opened by Collin Winter Clean up usage of map() in the stdlib (2006-06-27) http://python.org/sf/1513299 opened by Collin Winter new turtle module (2006-06-28) http://python.org/sf/1513695 opened by Lingl docs for xturtle.py (2006-06-28) CLOSED http://python.org/sf/1513699 opened by Lingl Move reduce() to functools (2006-06-28) http://python.org/sf/1513870 opened by Collin Winter mailbox (Maildir): avoid losing messages on name clash (2006-06-29) http://python.org/sf/1514543 opened by David Watson mailbox: use fsync() to ensure data is really on disk (2006-06-29) http://python.org/sf/1514544 opened by David Watson proposal for a new circle method (2006-06-29) CLOSED http://python.org/sf/1514737 opened by Lingl 1515163 fix - traceback and str exc (2006-06-30) http://python.org/sf/1515343 opened by Jim Jewett urllib2 redirection fix (2006-07-02) http://python.org/sf/1515745 opened by Petr Gladkikh tarfile.py fix for #1471427 and updates (2006-05-09) http://python.org/sf/1484695 reopened by gustaebel tarfile.py fix for #1471427 and updates (2006-05-09) http://python.org/sf/1484695 reopened by gustaebel Remove deprecated functions from operator (2006-07-03) http://python.org/sf/1516309 opened by Collin Winter Module uuid: reduce pickle footprint (2006-07-03) http://python.org/sf/1516327 opened by Michael Amrhein Module uuid: functions for retrieving MAC addres (2006-07-03) http://python.org/sf/1516330 opened by Michael Amrhein Remove sys.exitfunc (2006-07-03) http://python.org/sf/1516375 opened by Collin Winter OpenVMS patches Modules directory (2006-07-04) http://python.org/sf/1516912 opened by Piéronne Jean-François Fix for Lib/test/crashers/gc_inspection.py (2006-07-04) http://python.org/sf/1517042 opened by Collin Winter Patch to commands.py to enable callback support (2006-07-05) http://python.org/sf/1517586 opened by Brad Doctor Patch for ctypes to enable custom objects in function calls (2006-07-05) http://python.org/sf/1517790 opened by Thomas Heller Patch for bug #1514451 (2006-07-06) http://python.org/sf/1517891 opened by Thomas Lee assert for NULL in Py_INCREF Py_DECREF (2006-07-06) http://python.org/sf/1517947 opened by Rene Dudfield ext/win-cookbook.html has a broken link to distutils (2006-07-07) http://python.org/sf/1518772 opened by Johannes Gijsbers New ver. of 1102879: Fix for 926423: socket timeouts (2006-07-07) http://python.org/sf/1519025 opened by Tony Nelson turtle.py: correcting begin_fill (2006-07-09) http://python.org/sf/1519566 opened by Lingl Patches Closed __ MS Toolkit Compiler no longer available (2006-06-20) http://python.org/sf/1509163 closed by loewis Patch for 1506758 - popen2/subprocess MAXFD MemoryErrors (2006-06-15) http://python.org/sf/1506760 closed by astrand Speed up decimal object construction (2006-06-25) http://python.org/sf/1511853 closed by ncoghlan [FIX][Bug 1512695] cPickle.loads seg. faults (2006-06-27) http://python.org/sf/1513206 closed by gbrandl Remove reduce() (2006-06-27) http://python.org/sf/1513249 closed by collinwinter docs for xturtle.py (2006-06-28) http://python.org/sf/1513699 closed by loewis Make thread stack size runtime tunable (03/20/06) http://python.org/sf/1454481 closed by sf-robot proposal for a new circle method (2006-06-30) http://python.org/sf/1514737 closed by loewis 1515169 fix (ImportWarning flood) (2006-06-30) http://python.org/sf/1515361 closed by nnorwitz Alternative fix for ImportWarning (fix for 1515169) (2006-07-01) http://python.org/sf/1515609 closed by nnorwitz telnetlib timeout
RE: [wwwsearch-general] ClientForm request re ParseErrors
hi john... not sure exactly who i should talk to tabout this..but here goes... i have the following piece of code... i'm trying to do a select form, and my test throws an error... i have the actual form main in the html, so it should find it... as far as i can tell, i've followed the docs.. but i could be wrong. any thoughts? the code, output, and partial html is below... thoughts/comments/ideas/etc... thanks -bruce test code #get the semester page #get the 2nd semester/frame src url page br.open(url) response = br.response() # this is a copy of response s = response.read() print response.read() print s #we now have the semester page... d = libxml2dom.parseString(s, html=1) ff = d.xpath(fnamepath) fname = ff[0].nodeValue print fname = ,fname br.select_form(name=main) error happens output fname = main Traceback (most recent call last): File ./stest.py, line 156, in ? br.select_form(name=main) File build/bdist.linux-i686/egg/mechanize/_mechanize.py, line 352, in select_form File build/bdist.linux-i686/egg/mechanize/_mechanize.py, line 296, in forms File build/bdist.linux-i686/egg/mechanize/_html.py, line 510, in forms File build/bdist.linux-i686/egg/mechanize/_html.py, line 226, in forms File build/bdist.linux-i686/egg/ClientForm.py, line 922, in ParseResponse File build/bdist.linux-i686/egg/ClientForm.py, line 952, in ParseFile File /usr/lib/python2.4/sgmllib.py, line 95, in feed self.goahead(0) File /usr/lib/python2.4/sgmllib.py, line 165, in goahead k = self.parse_declaration(i) File /usr/lib/python2.4/markupbase.py, line 89, in parse_declaration decltype, j = self._scan_name(j, i) File /usr/lib/python2.4/markupbase.py, line 378, in _scan_name self.error(expected name token at %r File /usr/lib/python2.4/sgmllib.py, line 102, in error raise SGMLParseError(message) sgmllib.SGMLParseError: expected name token at '! Others/0/WIN; Too' partial html --- /table br / FORM NAME='main' METHOD=POST Action=/servlets/iclientservlet/a2k_prd/?ICType=PanelMenu=SA_LEARNER_SERVI CESMarket=GBLPanelGroupName=CLASS_SEARCH autocomplete=off INPUT TYPE=hidden NAME=ICType VALUE=Panel INPUT TYPE=hidden NAME=ICElementNum VALUE=0 INPUT TYPE=hidden NAME=ICStateNum VALUE=1 -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of John J Lee Sent: Sunday, July 09, 2006 9:51 AM To: [EMAIL PROTECTED] Subject: Re: [wwwsearch-general] ClientForm request re ParseErrors On Sun, 9 Jul 2006, Titus Brown wrote: [...] Define better patch...? The code I sent out before lets ClientForm parse otherwise unparseable HTML, and it works fine. I suppose it's less elegant than having two separate while loops; is that what you mean? No, I just hate going one char at a time in Python. Surely this should be fixed somewhere else? (I'm not sure where; I haven't looked recently) If you've determined that fixing it elsewhere pulls in too much code or requires a fix to stdlib code (if so, why?), maybe I should do as you suggest anyway, but I don't like it. - The problem I have is that there's literally no way to pass - configuration parameters like 'ignore_errors' down from the - mechanize.Factory.forms() call. - - You can reimplement FormsFactory. It's a trivial (if slightly verbose) - class, right? I could do that, yes. But I'd also need to redefine Factory.forms(), too, which calls FormsFactory. Why? You can supply your own FormsFactory, as DefaultFactory does. [...] - Separately, it'd be nice if ignore_errors wasn't hardcoded as False in - ParseFile ;). - - I'm not sure what you want here. Could you send a patch? Line 914 of ClientForm.py should be changed to 'ignore_errors,' Oh. Sure, if I apply a patch to enable ignore_errors, I'll of course do that too. John - Using Tomcat but need to do more? Need to support web services, security? Get stuff done quickly with pre-integrated technology to make your job easier Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo http://sel.as-us.falkag.net/sel?cmd=lnkkid=120709bid=263057dat=121642 ___ wwwsearch-general mailing list [EMAIL PROTECTED] https://lists.sourceforge.net/lists/listinfo/wwwsearch-general -- http://mail.python.org/mailman/listinfo/python-list
Re: concatenate Numeric
Sheldon wrote: Hi, I am trying to build a large array using concatenate function in python. So as I loop over the number of arrays, of which there are 12 (4 down and 3 across), I create 3 long arrays by concatenating them at the bottom and then concatenating them side by side: [snip] print 'Max lat', max(max(ppslat_all)), '\t','Min lat', min(min(ppslat_all)) print 'Max lon', max(max(ppslon_all)), '\t','Min lon', min(min(ppslon_all)) * Now this works, the array size is correct but the longitude values given for max and min are wrong. What is even stranger to me is that when I write the array in binary format to a file and read it with Matlab, the max and min are correct but when I read it back with python the max and min are again incorrect for only the longitude data. I saved the max and min for the longitude for each array and then check it in the python program and they are correct at the end but the max(max(ppslon)) values is incorrect. Does anyone knows why this is so? If I was doing something wrong then Matlab would not have returned correct values. Don't use min() and max() on multidimensional arrays. They won't give sensible answers. In [11]: a = RA.random([3,5]) In [12]: a Out[12]: array([[ 0.01721657, 0.64291363, 0.33210659, 0.89887972, 0.24437849], [ 0.88205348, 0.00839329, 0.35999039, 0.9966411 , 0.54957126], [ 0.59983864, 0.18983323, 0.13727718, 0.8987289 , 0.05425076]]) In [13]: min(a) Out[13]: array([ 0.59983864, 0.18983323, 0.13727718, 0.8987289 , 0.05425076]) The builtin min() and max() compare the values in the sequence. In this case, those values are the rows of the arrays. Numeric uses rich comparisons, so the result of a comparison is a boolean array. Numeric also has the convention that if any of the elements of an array are considered to be True, then the whole array is. In [16]: a[1] a[2] Out[16]: array([0, 1, 0, 0, 0]) In [17]: bool(_) Out[17]: True In [18]: a[2] a[1] Out[18]: array([1, 0, 1, 1, 1]) In [19]: bool(_) Out[19]: True This makes min(a) incorrect when len(a.shape) 1. Instead, use the minimum and maximum ufuncs provided with Numeric: In [21]: N.minimum.reduce(a.flat) Out[21]: 0.0083932917161983426 In [22]: N.maximum.reduce(a.flat) Out[22]: 0.99664110397663608 -- 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: array of array of float
[EMAIL PROTECTED] schrieb: i used C too much and haven't used Python for a while... like in C, if we want an array of array of float, we use float a[200][500]; now in Python, seems like we have to do something like a = [ [ ] ] * 200 and then just use a[1].append(12.34) etc but it turns out that all 200 elements points to the same list... and i have to use a = [ ] for i in range (0, 200): a.append([ ]) is there a simpler way... i wonder... a = [[] for in range(200)] -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Bruno Desthuilliers wrote: Paddy a écrit : Bruno Desthuilliers wrote: Frank Millman a écrit : Paddy wrote: Hi, I am trying to work out why I get UnboundLocalError when accessing an int from a function where the int is at the global scope, without explicitly declaring it as global but not when accessing a list in similar circumstances. There has just been a long thread about this. I think I understand it now. Here is my explanation. Ignoring nested scopes for this exercise, references to objects (i.e. variable names) can exist in the local namespace or the global namespace. Python looks in the local namespace first, and if not found looks in the global namespace. Any name assigned to within the function is automatically deemed to exist in the local namespace, unless overridden with the global statement. And this even of the local bindings sequentially comes after another access to the name, ie: g = 0 def fun(): x = g # UnboundLocalError here g += 1 return x With the statement 'm = m + 1', as m is assigned to on the LHS, it is deemed to be local, but as m does not yet have a value on the RHS, you get Unbound Local Error. Right With the statement 'n[0] = n[0] + 1', n is not being assigned to, Right as it is mutable. n is effectively mutable, but this is totally irrelevant. In your snippet, n is not 'assigned to', it's mutated (ie a state-modifying method is called). The snippet: n[0] = n[0] + 1 is syntactic sugar for n.__setitem__(0, n.__getitem__(0) + 1) IOW, it's just method calls on n. So, An assignment statement may assign an object to a name, An assignment statement binds an object to a name. in which case the name is 'tagged' as being local, Unless that names has been declared as global or lives in another namespace (ie is an element of a mutable collection or an attribute of another object). An assignment statement may mutate a mutable object already bound to a name, in which case the assignment will not 'tag' the name as being local. consider this code: class Foo(object): def __init__(self, baaz): self.baaz = baaz def bar(foo, bak): foo.baaz = bak Which name is getting rebound here ? foo, or foo.baaz ? I guess Bruno, you mean irrelevant as in 'although only mutable objects can have their state modified; if n has a mutable value but the assignment statement changed the object referred to by n, then the name would be tagged as local'? Unless the name has been declared as global, yes. Thanks Bruno, that clears it up for me (I had purposefully left out the global statement from my example, but should have included it in the explanation). -- http://mail.python.org/mailman/listinfo/python-list
Re: array of array of float
Schüle Daniel schrieb: [EMAIL PROTECTED] schrieb: i used C too much and haven't used Python for a while... like in C, if we want an array of array of float, we use float a[200][500]; now in Python, seems like we have to do something like a = [ [ ] ] * 200 and then just use a[1].append(12.34) etc but it turns out that all 200 elements points to the same list... and i have to use a = [ ] for i in range (0, 200): a.append([ ]) is there a simpler way... i wonder... a = [[] for in range(200)] correction :) a = [[] for i in range(200)] -- http://mail.python.org/mailman/listinfo/python-list
Re: array of array of float
Use nested list comprehensions: matrix = [[0.0 for x in xrange(n)] for y in xrange(m)] This is similar to float matrix[m][n] in C. All cells are independent of each other in doing this. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Dennis Lee Bieber wrote: On 9 Jul 2006 11:30:06 -0700, Paddy [EMAIL PROTECTED] declaimed the following in comp.lang.python: So, An assignment statement may assign an object to a name, in which case the name is 'tagged' as being local, Reverse... Python does not assign objects to names... It assigns names to objects. One object can have multiple names. In the absence of a global name statement, any unqualified name found on the left side of an = is a local name (the name -- not the object it is bound to -- is held as part of the current stack frame and is removed on return from the function; the object may or may not be garbage collected depending upon any other names bound to it). A qualified name is one with some sort of component specifier: name.component, name[component]. These access items that are inside the object that name is bound on. The component access basically is a function/method call telling the object itself to change the component binding, not the top-level name binding. Hi Dennis, in the last paragraph you do not state specifically where the name for the component name is looked for. Do you mean that for component name accesses,where the 'base' is not declared gobal, the 'base' name nevertheless is always looked for in the global scope? (Please excuse my pedantry). -- http://mail.python.org/mailman/listinfo/python-list
Re: scheduling accuracy for audio
Thanks Paul, that's what I suspected. -a- On 9 Jul 2006, at 19:22, Paul Rubin wrote: andrea valle [EMAIL PROTECTED] writes: In order to have sequencing I have to send at precise timing messages from Python to SC. Obviously, being a musical application, I need millisecond time accuracy, with less latency as possible or at least a fixed (short) latency. More, I need to have multithreading, with many processes sending messages from Python to SC. You really can't get that kind of accuracy with a non-realtime OS. The way this is handled in actual audio applications the sound board has a fair amount of buffering, so you send the right number of samples and precise scheduling isn't so important. -- http://mail.python.org/mailman/listinfo/python-list Andrea Valle DAMS - Facoltà di Scienze della Formazione Università degli Studi di Torino http://www.semiotiche.it/andrea [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Paddy a écrit : Dennis Lee Bieber wrote: On 9 Jul 2006 11:30:06 -0700, Paddy [EMAIL PROTECTED] declaimed the following in comp.lang.python: So, An assignment statement may assign an object to a name, in which case the name is 'tagged' as being local, Reverse... Python does not assign objects to names... It assigns names to objects. One object can have multiple names. In the absence of a global name statement, any unqualified name found on the left side of an = is a local name (the name -- not the object it is bound to -- is held as part of the current stack frame and is removed on return from the function; the object may or may not be garbage collected depending upon any other names bound to it). A qualified name is one with some sort of component specifier: name.component, name[component]. These access items that are inside the object that name is bound on. The component access basically is a function/method call telling the object itself to change the component binding, not the top-level name binding. Hi Dennis, in the last paragraph you do not state specifically where the name for the component name is looked for. First in the local namespace, then in enclosing namespaces until the global (read : module level) namespace, and finally in the builtins. Do you mean that for component name accesses,where the 'base' is not declared gobal, the 'base' name nevertheless is always looked for in the global scope? unless it's found in another namespace before - same rules apply as for a non-qualified name. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Fredrik Lundh wrote: Paddy wrote: ... irrelevant as in 'although only mutable objects can have their state modified; if n has a mutable value but the assignment statement changed n to refer to another object, then the name would be tagged as local'? Oh bosh, can anyone come at it from a different tack? look for Assignment of an object to a single target is recursively defined as follows on this page (or at the corresponding page in the language reference): http://pyref.infogami.com/assignments /F I had a look Frederick but the page lead to: http://pyref.infogami.com/subscriptions Which again failed to mention namespace issues. - Pad. -- http://mail.python.org/mailman/listinfo/python-list
Re: Scope, type and UnboundLocalError
Bruno Desthuilliers wrote: SNIP Ta. -- http://mail.python.org/mailman/listinfo/python-list
Re: can't pickle instancemethod objects
Here's a thought: comment out every attribute in your class, and then try pickling it. If it succeeds, uncomment just *one* attribute, and try pickling again. Repeat until pickling fails. Was trying to avoid that but you motivated me to do so and now I found the probem. In a utility routine I had: obj.act = act ActionSucceded = obj.act() Had to add: obj.act = None Thanks :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: looping question 4 NEWB
Thanks Marc, that was very helpful. Marc 'BlackJack' Rintsch wrote: In [EMAIL PROTECTED], manstey wrote: I often have code like this: data='asdfbasdf' find = (('a','f')('s','g'),('x','y')) for i in find: if i[0] in data: data = data.replace(i[0],i[1]) is there a faster way of implementing this? Also, does the if clause increase the speed? It decreases it. You search through `data` in the ``if`` clause. If it's `False` then you have searched the whole data and skip the replace. If it's `True` you searched into data until there's a match and the the `replace()` starts again from the start and searches/replaces through the whole data. You can get rid of the indexes and make the code a bit clearer by the way: for old, new in find: data = data.replace(old, new) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
faulkner wrote: you want a directory watching daemon. it isn't hard at all to build from scratch. first, determine which directories should be watched. then, os.walk each directory, building a mapping from filename to mtime [modified time; os.path.getmtime]. next is your main event loop. this while loop consists of os.walk-ing each directory again, comparing the current mtime to the corresponding entry in the mapping. if they differ, or if a filename isn't in the mapping, something happened, at which point you can logick out whether a file was moved, deleted, changed, or created. so many folks have looked for this that i'll just write a generic one and put it in the cheeseshop. look for dirmon in about a week. Yes, I _know_ about it and exactly this knowledge is the reason I am looking for tracking single file system related _events_ as I expect a professional operating system like Windows to provide such service. If there is none, this will be sure a severe reason to go for Linux if it has such one instead of going for a SVN server or special file systems if there are any. Has someone experience with SVN handling million(s) of files? The problem is, that brute force applied to large amount of files/directories is not a convenient way to backup/synchronize the few new/changed/deleted/moved files/directories multiple times a day as the brute force approach just makes the hard drive(s) unnecessary wasting much energy and getting hot. Claudio Grondi Claudio Grondi wrote: I am aware, that it is maybe the wrong group to ask this question, but as I would like to know the history of past file operations from within a Python script I see a chance, that someone in this group was into it already and is so kind to share here his experience. I have put already much efforts into this subject googling around, but up to now in vain. Best option I encountered yet is usage of the Greyware 'System Change Log' service which monitors disks for changes (http://www.greyware.com/software/systemchangelog/index.asp), but in own tests it turned out, that the created log file does not cover all file events as e.g. it is not possible to detect when a file is moved to a new directory (creation of a new file is logged, but deletion is not, not mentioning I would expect a file 'move' event). The own Windows logging service rejected to start on my XP SP2 system for unknown to me reasons - I don't know how to get it to work (yes, I have used the administrator account). I can't believe, that using NTFS file system in Microsoft Windows 2000 or XP it is not possible to track file events as: - updating/modifying of an existing file/directory - deleting an existing file/directory - creating a new file/directory - _moving_ an existing file/directory (should _NOT_ be covered by the event duo of deleting an existing and creating a new file/directory) Any hints towards enlightenment? Claudio Grondi -- http://mail.python.org/mailman/listinfo/python-list
Re: Size of hard drive and Mp3 tags functions
Dennis Lee Bieber wrote: On 9 Jul 2006 11:14:25 -0700, John Hicken [EMAIL PROTECTED] declaimed the following in comp.lang.python: Anyway, there are two sorts of functions that could be useful. 1) A function that gives the size of a hard drive (or other drive, in this case the mp3 player itself), and/or the space remaining. Presuming the device shows up as a disk device in Windows... From the win32api (ActiveState) help file: win32file.GetDiskFreeSpaceEx long, long, long = GetDiskFreeSpaceEx(rootPathName) Determines the free space on a device. Parameters rootPathName : PyUnicode address of root path Return Value The result is a tuple of long integers: Items [0] long integer : freeBytes The total number of free bytes on the disk that are available to the user associated with the calling thread. [1] long integer : totalBytes The total number of bytes on the disk that are available to the user associated with the calling thread. Windows 2000: If per-user quotas are in use, this value may be less than the total number of bytes on the disk. [2] long integer : totalFreeBytes The total number of free bytes on the disk. 2)A function/functions to read the ID tags of an MP3 file. http://www.google.com/search?hl=enq=python+mp3+ID+tagbtnG=Google+Search -- WulfraedDennis Lee Bieber KD6MOG [EMAIL PROTECTED] [EMAIL PROTECTED] HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: [EMAIL PROTECTED]) HTTP://www.bestiaria.com/ Thanks for the help. As you gathered, the mp3 player just appears as a hard drive, and the GetDiskFreeSpaceEx function does exactly what I want. Also, the first id tag program for python from the google seach, id3reader, seems to match what I want, as I won't need to alter the ID3 tags. Thanks John Hicken -- http://mail.python.org/mailman/listinfo/python-list
Re: please remove posting we are receiving unsolicited emails
homeprice maps [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] dear python , Python is a language, not a person that can act in in this universe. as a result of the following posting we are receiving emails from people regarding services and websites we have no relation to. Join the club please please have this posting removed asap. Posts to python-list are sent to comp.lang.python, which is archived for months or longer by numerous newsgroup servers and indefinitely by google. Any of these are the most likely places checked by spammers. Posts also go to gmane.comp.python.general and get archived by news.gmane.com. But, given how email addresses come and go, spammers will check current postings, not things 6 months old. So you will probably get a few more from this removal request ;-). Sorry. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: WANTED: logging of all file operations on Windows
Tim Golden wrote: Claudio Grondi wrote: I am aware, that it is maybe the wrong group to ask this question, but as I would like to know the history of past file operations from within a Python script I see a chance, that someone in this group was into it already and is so kind to share here his experience. I can't believe, that using NTFS file system in Microsoft Windows 2000 or XP it is not possible to track file events as: - updating/modifying of an existing file/directory - deleting an existing file/directory - creating a new file/directory - _moving_ an existing file/directory (should _NOT_ be covered by the event duo of deleting an existing and creating a new file/directory) Any hints towards enlightenment? Claudio Grondi On the offchance that you haven't seen it, you might look at this: http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges but since it doesn't fulfil your criterion of *not* representing renames by a delete and an add, it may well not be suitable. Apart from that, I think it does what you want. TJG It seems, that it will be necessary to use some logic based on the sequence of events to exactly detect rename and move changes done to files/directories, but in principle it is the best approach I know about yet. Thank you! By the way: Is there something similar/same available for Linux? Claudio Grondi -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Gregory Guthrie [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] - why is len() not a member function of strings? Instead one says len(w). Consider map(len, ('abc', (1,2,3), [1,2], {1:2})) [3, 3, 2, 1] Now try to rewrite this using methods (member functions). - Why doesn't sort() return a value? Because it is an in-place mutation method and Guido decided that such methods should return None rather that the mutated object to lessen bugs. It is a tradeoff that has been debated ever since ;-) For example: to acculumate words in a dictionary - dict[key] += [word] This expands to dict[key] = dict[key] + [word]. When the latter is valid (when dict[key] exists and is a list), then the former works fine also. k='a' d = {k:[]} d[k]+=['b'] d {'a': ['b']} I presume the new-in-2.5 default dicts will do the same, and also work when the key does not exist and the default is a list. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Terry Reedy wrote: Consider map(len, ('abc', (1,2,3), [1,2], {1:2})) [3, 3, 2, 1] Now try to rewrite this using methods (member functions). [a.len() for a in ('abc', (1,2,3), [1,2], {1:2})] -- --OKB (not okblacke) Brendan Barnwell Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail. --author unknown -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Terry Reedy [EMAIL PROTECTED] writes: Consider map(len, ('abc', (1,2,3), [1,2], {1:2})) [3, 3, 2, 1] Now try to rewrite this using methods (member functions). [x.len() for x in ('abc', (1,2,3), [1,2], {1:2})] - Why doesn't sort() return a value? Because it is an in-place mutation method and Guido decided that such methods should return None rather that the mutated object to lessen bugs. It is a tradeoff that has been debated ever since ;-) Nah, we have sorted() now, a functionalista victory ;-) I presume the new-in-2.5 default dicts will do the same, and also work when the key does not exist and the default is a list. Man, it's hard to keep track of these new features. Default dicts do sound like a good addition; I've used those d.setdefault/d.get idioms way too often. -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 on Windows Vista
Rune Strand wrote: My wil guess is that it is a firewall problem. Perhaps you'll have to specify that python.exe is trusted. Tried that - it didn't work. I also tried turning off the User Account Control and ran as full administrator - that didn't work too. -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
On Sun, 09 Jul 2006 12:19:13 -0500, Gregory Guthrie wrote: I am comparing Python to a few other scripting languages, and used a simple anagrams program as a sample. I was surprised ast a few python features that did not work as I would expect/wish; which caused less compact/expressive program styles that I wanted - reverting to a FORTRAN like series of assignments. For example, - why is len() not a member function of strings? Instead one says len(w). Length is an obvious property of any one-dimensional non-scalar, not just strings. As such, it makes sense to have a length function that takes an argument. As a design decision, it could go either way, but early Python wasn't fully object-oriented. If Guido was designing Python from scratch today, who knows whether he'd still make len a function? - Why doesn't sort() return a value? Because if you have a 100 MB list of objects which you want to sort, why go to the significant expense of making a sorted copy only to throw the original away? In general, Python never copies data unless you explicitly tell it too. If you want to keep the original, unsorted list around, you need to make a copy of it explicitly. This would allow things like: key = '',join( list(word.lower().strip()).sort() ) instead: key = ... key.sort() key = ... One liners are over-rated. - Another feature I assumed but it failed, is a nice default for dictionaries, and more += like operations; What default should this dictionary have? {'key1' = 'alpha', 'key2' = 1, 'key3' = [4, 7, 3]} Should it be '', 0, [], None or something else? Be prepared to justify why your choice is suitable not just for *this* dictionary, but for *all* dictionaries. I am curious why these obvious conveniences are not present. :-) Thansk for any context or insight. Perhaps the best way to understand the Python philosophy is to call up an interpreter and execute import this at the prompt. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Validating Python - need doctype HTML strict
Hello, I am trying to validate the following .py webpage as HTML (through W3C). I put: - print Content-type: text/html; charset=utf-8 import time print print htmlhead titleCurrent Time/title /head body h1Current Time/h1 print pRight now, it is print strong, time.asctime(), /strong/p print /body/html --- However, the .py page should also be valid (X)HTML - it needs a doctype... When I add the doctype, and other necessities to the .py page (i.e., !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd; html xmlns=http://www.w3.org/1999/xhtml; xml:lang=en lang=en) I get an invalid script error. Can anyone help me to get the XHTML doctype to validate and execute on Python web page? Thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
On Sun, 09 Jul 2006 22:45:53 +, OKB (not okblacke) wrote: Terry Reedy wrote: Consider map(len, ('abc', (1,2,3), [1,2], {1:2})) [3, 3, 2, 1] Now try to rewrite this using methods (member functions). [a.len() for a in ('abc', (1,2,3), [1,2], {1:2})] Did you actually try that? 'abc'.len() Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'str' object has no attribute 'len' In any case, list comprehensions are a recent (version 2.2 I think?) addition to Python. You have to think about the functionality available back in the days when the decision to make len() a function was made, not based on what functionality is available a decade later. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
help a newbie with a IDE/book combination
Hi, I already have a couple of newbie books on Python itself, but would rather get started with a nice to use IDE and I am therefore looking for a good IDE to learn Python. On my computer I have installed eric (http://ericide.python-hosting.com/) but it lacks any kind of useful documentation on its use. Is there a good IDE which would be well documented out there? Many thanks Mamadu PS: I use Debian GNU/Linux on all my computers, a 500MHz proc, 256MB RAM. -- http://mail.python.org/mailman/listinfo/python-list
Re: pyXLWriter - grid lines and if formula
Gregory Piñero escreveu: On 7/7/06, Luis P. Mendes [EMAIL PROTECTED] wrote: Hi, I know that pyExelerator is the supported project now, but I can't use it because I'd need it to generate files from a web platform. Since I can not save a file to a file-like object, I have to use pyXLWriter. I don't really know what I'm talking about, but maybe have a Python script that uses pyExelerator and saves the file to Sdout, name that script with an .xls extension and the browser will present it to the user as an Excel file? Maybe, maybe?? -Greg pinero I'll try that option and see what I can get. Still, there's an open patch at http://sourceforge.net/tracker/index.php?func=detailaid=1481069group_id=134081atid=730645 that says: Summary: (?) pass file-like objects to write In a cgi script you use mosty sys.stdout to write to the client with this little patch this is possible. but it has not been submitted yet. So, perhaps you could show me how to generate an excel file as a http response in django? Luis P. Mendes -- http://mail.python.org/mailman/listinfo/python-list
unistall python mechanize
hi.. i'm trying to figure out how to uninstall mechanize. i don't see an unistall from the python --help-commands function... i'm looking to rebuild/reinstall mechanize from the svn repos to try to see if an apparent parsing issue that i mentioned is fixed... thanks -bruce -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Steven D'Aprano wrote: On Sun, 09 Jul 2006 22:45:53 +, OKB (not okblacke) wrote: Terry Reedy wrote: Consider map(len, ('abc', (1,2,3), [1,2], {1:2})) [3, 3, 2, 1] Now try to rewrite this using methods (member functions). [a.len() for a in ('abc', (1,2,3), [1,2], {1:2})] Did you actually try that? He was answering a hypothetical. He wasn't suggesting that was valid syntax today. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis Don't try to confuse me with the facts. -- Bill McNeal -- http://mail.python.org/mailman/listinfo/python-list
Re: language design question
Steven D'Aprano [EMAIL PROTECTED] writes: Now try to rewrite this using methods (member functions). [a.len() for a in ('abc', (1,2,3), [1,2], {1:2})] Did you actually try that? No of course not. It's in a hypothetical python where .len() is a class operation instead of a global function. In any case, list comprehensions are a recent (version 2.2 I think?) addition to Python. You have to think about the functionality available back in the days when the decision to make len() a function was made, not based on what functionality is available a decade later. Correct, so the answer to the OP's question might well be it's that way because of historical accidents. -- http://mail.python.org/mailman/listinfo/python-list