Re: Detecting changes to a dict
On Sep 28, 1:11 am, Steven D'Aprano wrote: > On Sun, 27 Sep 2009 21:42:10 -0700, CTO wrote: > >> Is there a fast way to see that a dict has been modified? > > ... > > > d = {"a": "b", "c": "d"} > > d2 = d.copy() > > assert d == d2 > > d["e"] = "f" > > assert d == d2 > > > Is this what you're looking for? > > In general, no. I was hoping for an O(1) check. Yours test is only O(1) > if the length of the dict changes[1], and probably O(N) otherwise. > Perhaps I'm guilty of premature optimization, but the above simple check > may be expensive in both space and time if the dict is very large and the > modification doesn't change the length. If the dict is large enough, > duplicating it may cause swapping, which is O(N**2) or worse. > > In my case, the dict only has a few hundred items, so your suggestion is > probably perfectly adequate for my specific need. But as a general > solution, imagine checking a dict with tens of millions of key/values. If > the length is different, that's a fast check. But if the length is the > same, the equality test has to check every key/value pair in the dict > (presumably bailing out early if it finds a difference). > > For my specific need, I'll probably end up using your suggestion simply > because I'm lazy and it's more convenient than writing a subclass. > > [1] That is, I *assume* that dict equality checking uses that obvious > optimization. > > -- > Steven If you can enumerate the language of possible inputs you could generate a unique binary representation. Against a language of size l that would only take you O(l*n) to build the repr for a dict and for certain repr sizes the comparison could be O(1), making the entire operation O(l*n+l*m) vs O(n*m). Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting changes to a dict
On Sep 27, 5:36 am, Steven D'Aprano wrote: > I'm pretty sure the answer to this is No, but I thought I'd ask just in > case... > > Is there a fast way to see that a dict has been modified? I don't care > what the modifications are, I just want to know if it has been changed, > where "changed" means a key has been added, or deleted, or a value has > been set. (Modifications to mutable values aren't important.) In other > words, any of these methods count as modifying the dict: > > __setitem__ > __delitem__ > clear > pop > popitem > setdefault > update > > Of course I can subclass dict to do this, but if there's an existing way, > that would be better. > > -- > Steven d = {"a": "b", "c": "d"} d2 = d.copy() assert d == d2 d["e"] = "f" assert d == d2 Is this what you're looking for? Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Finite state machine in python
On Sep 12, 4:39 pm, Peng Yu wrote: > Hi, > > I have see some discussion on the implementation of finite state > machine in python. Can somebody point to me the best way in implenting > an FSM in python? > > http://code.activestate.com/recipes/146262/ > > Regards, > Peng I wrote an example of how to do it using Graphine a while back. Probably not the most efficient in the world, but pretty easy to read, and it allows you to add and remove states and transitions easily. URL: http://gitorious.org/graphine/pages/GraphineForPythonistas Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: No trees in the stdlib?
On Jun 26, 1:29 am, Tom Reed wrote: > Whynotrees in the standard library, if not as a built in? I searched > the archive but couldn't find a relevant discussion. Seems like a > glaring omission considering the batteries included philosophy, > particularly balanced binary search trees.Nointerest,nogood > implementations, something other reason? Seems like a good fit for the > collections module. Can anyone shed some light? > > Thanks. > -- > Tom I've written a graph library (trees being rooted connected acyclic graphs) called Graphine that you could try. Obviously not a part of the standard library, but it (or networkx) will almost certainly do what you're looking for. You can find graphine at graphine.org, or networkx at networkx.lanl.gov. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: graph edge generators
On Jun 9, 11:58 pm, William Clifford wrote: > I've become interested in basic graphs and networks and I'm wondering > about what algorithms are there for generating basic regular graphs > like the simplex graph or dodecahedron graph, etc (I'm sure there are > many). I'm particularly keen on understanding the very basic functions > for determining edges in the graphs. If one didn't want the complete > graph but just a function generates the edges connected to a given > node. > > I've been surfing around for this sort of info, but I'm having trouble > finding stuff at my level. If anyone knows of any resources or > tutorials or that sort of thing, I'd like to hear about those too. > > Thanks! > > -- > William Clifford Depending on how much of a basis you have in CS, you may want to take a look at http://www.amazon.com/Combinatorial-Algorithms-Enumeration-Mathematics-Applications/dp/084933988X which I found to be an excellent book that covers a lot of the ground you're talking about. Also, check out graphine (graphine.org)- I think its a pretty easy-to-use graph package for python, although as the primary author I'm pretty biased. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Q: finding distance between 2 time's
On May 30, 8:49 pm, John Machin wrote: > > import time > You are in a maze of twisty little functions, all alike. Quote of the week. Perhaps the year. I hope you don't mind me using it in the future. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Browser based Canvas UI?
On May 30, 4:12 am, Ken Seehart wrote: > A couple years ago I stumbled upon an interesting technology but I can't > seem to find it, and I can remember what it is called. Unfortunately > this makes it difficult to search for. I am am aware of several partial > matches (items that meet a subset of the requirement listed below). > Does anyone know what does /all/ of the following? > > 1. Works on at least FF and IE on XP and Linux out of the box, probably > others > > 2. Does not require /any/ plugin download at all of any kind to view > (this disqualifies flash, svg, silverlight, java, and others) > > 3. If you go to the web page for the first time on a freshly installed > operating system, without admin privileges, you will see the > functionality listed below immediately, and with no downloaded plugins > and installers. (I apologize for the redundancy, but I want to > preemptively avoid a flood of non-applicable responses). > > 4. Graphics, including sprite animation > > 5. Dynamic response to mouse motion: dragging sprites for example > > 6. Programmable in Python, of course > > Hints from what I can recall: > - Built from javascript as it's raw material under the hood (after all, > it can't very well be anything else given requirements 1,2,3) > - Seems quite magical since I didn't know the necessary graphical raw > materials existed in javascript > - I think it's based on Ajax, but I can't seem to find a relevant python > demo of it due to too much clutter in my google searches > > Ken Probably thinking of Pyjamas- http://pyjamas.sourceforge.net/>. It lets you interact with canvas- http://www.blobsallad.se/>- without writing any javascript. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding a Par construct to Python?
On May 28, 1:53 pm, Aaron Brady wrote: > On May 27, 11:07 pm, Steven D'Aprano > cybersource.com.au> wrote: > > On Wed, 27 May 2009 12:58:02 +, Albert van der Horst wrote: > > > >>And how is reduce() supposed to know whether or not some arbitrary > > >>function is commutative? > > > > Why would it or need it? A Python that understands the ``par'' keyword > > > is supposed to know it can play some tricks with optimizing reduce() if > > > the specific function is commutative. > > > Fine. Move the smarts out of reduce() into the compiler. How is the > > compiler supposed to know if an arbitrary function is commutative? > > Unit testing. I think this kind of gets to the heart of it, here- parallelization is not a toy, runs with scissors, and will eat your dog, but so will everything else if you don't know what you're doing. I just don't see this as being a valid argument- maybe I'm wrong. In the spirit of continuing to be wrong, would it be possible to just fork off and synchronize the passed-in variables at the end of the block via a container in shared memory? That sounds to me like the simple, safe route, if a route must be taken. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing string from python programs to external programs
On May 26, 2:12 pm, lone_eagle wrote: > Hi all, > > On Linux, I do something like this > > $ program_to_execute < input_file > ... get some output ... > > I have the content of the input_file as a string inside a python > program and would like to pass this string to the external program > from inside the python program and get back the programs output in a > string/file. Can someone tell me how to achieve this. I have been > through the documentation for Popen, but this one beats me. > > Cheers, > Chaitanya from subprocess import getstatusoutput cmd = 'echo ' str = 'Hello World!' status, output = getstatusoutput(cmd + repr(str)) Obviously, this is 3.x. I believe that in 2.x it was in the commands module. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Network programming ?
On May 25, 11:05 pm, thushiantha...@gmail.com wrote: > Hi everyone, > > I am planning to develop a chatting software in Python, for my college > project. I am using Windows Vista. Is it possible to do sockets > programming in Python ? Any books or websites ? Also, i want to > develop a gui for that program. What are the gui tool kits available > for windows? I already knew about PyGtk and PyQT, but will they work > properly in Windows platform? Any suggestions? > > Thank you. Excuse my English. There's a book called Foundations of Python Network Programming that is pretty much as good a book as you could ever ask for on the subject. I strongly recommend it, and I think you'll find many of the examples relevant. As far as PyGTK and PyQT, my understanding is that they will work, but require some effort. You may want to look at PyGUI, which I haven't used but have consistently heard good things about- they seem to have good windows support. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
On May 26, 3:23 am, Lawrence D'Oliveiro wrote: > In message , Steven > > D'Aprano wrote: > > On Tue, 26 May 2009 18:31:56 +1200, Lawrence D'Oliveiro wrote: > > >> In message >> b201-4b2445732...@v35g2000pro.googlegroups.com>, LittleGrasshopper > >> wrote: > > >>> ... I am looking for suitable syntax files for [editor of choice] ... > > >> I don't understand why people need "syntax files" to use a text editor. > > > Do you want syntax highlighting? > > Why? Provides a clear visual indicator of when you've screwed up, which is pretty important for me ;) Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: any lib to extract pages form pdf and then merge?
On May 26, 12:47 am, oyster wrote: > I want to extract some pages from vary pdf files, then write them > with/witout rotation into one new pdf file. something likes this > [py] > import gfx > doc = gfx.open("pdf", r"Theory.pdf") > pdf = gfx.PDF() > for pagenr in [1,5,7]: > page = doc.getPage(pagenr) > > if pagenr==1: > page.rotate(90) #for some > pages > > pdf.startpage(page.width, page.height) > page.render(pdf) > pdf.endpage() > pdf.save("new pdf.pdf") > [/py] > > I have tried pypdf, but it errs and exits on some of my pdfs(no, the > files have no password) > > can someone suggest on such a lib for python on windows/or a pure C-dll? > (I mean pdf page->pdf, not pdf page->pic->pdf) > > thanx I'd recommend reportlab http://www.reportlab.org/>. It is mostly geared towards creating new PDFs, but it is pretty much best-of-breed AFAICT. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance java vs. python
> Ah! I should have been careful before asking such "general" question about > performance. I agree with you. But mine was more academic. I should not given > a specific example. > > AFAIK, for java on the client side, JVM performance is one of the critical > things which has been tuned to death until now. Even Google's Android which > uses Java for the programming > language uses a Dalvik Virtual machine which was spefically designed to > handle low CPU, memory and power environments. Similarly, Python can also be > used to program on Nokia phones etc. > Of course programming natively (C/C++) > would make a difference in environments where CPU, memory and power are a big > constraint. Given the context, do we know how Python compares with > Java or even native programming. What is the overhead of Python's > interpreted code ? Some standard benchmarks would help compare apples to > apples though it may not help deciding which > framework to choose. > > -mohan Danger, will robinson- the dalvik jvm has precisely nothing to do with standard java. It uses the same syntax but otherwise operates entirely differently. Don't assume you'll get the same performance characteristics out of the other common jvm's. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Python system with exemplary organization/coding style
On May 14, 7:01 pm, TomF wrote: > I'm looking for a medium-sized Python system with very good coding > style and good code organization, so I can learn from it. I'm reading > various books on Python with advice on such things but I'd prefer to > see a real system. > > By medium-sized I mean 5-20 classes, 5-20 files, etc; a code base that > has some complexity but isn't overwhelming. > > Thanks, > -Tom I'd recommend screenlets. Good documentation and pretty good style, and they have some external dependencies so you can see how that operates, and of course you can see what your code is and isn't doing pretty quickly. http://www.screenlets.org> Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: How to see the code definiton in the shell ?
On May 13, 1:26 pm, "J. Cliff Dyer" wrote: > On Wed, 2009-05-13 at 09:40 -0700, Mohan Parthasarathy wrote: > > Hi, > > > I am new to Python. I tried searching this but could not find an > > answer. In the interactive shell, I write a new function and I want to > > be able to see all the code that I wrote at a later time. Just typing > > the function name only shows > > > >>> allmethods > > > > > How do I see the actual code ? > > > thanks > > mohan If you save your function to a file you can. Saying you have the following file: #! /usr/bin/env python3 def f(x, y): return x**y saved as f.py, you can go into the interpreter and do: >>> import inspect >>> from f import f >>> inspect.getsource(f) 'def f(x, y):\n\treturn x**y\n' However, trying this on a function written in the interpreter will bail on you. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Representing a Tree in Python
On May 13, 8:19 am, bearophileh...@lycos.com wrote: > godshorse, you may use the "shortestPaths" method of this graph class > of mine:http://sourceforge.net/projects/pynetwork/ > > (It uses the same Dijkstra code by Eppstein). > (Once you have all distances from a node to the other ones, it's not > too much difficult to find the tree you talk about). > > Also see the Minimum spanning > tree:http://en.wikipedia.org/wiki/Minimum_spanning_tree > > Bye, > bearophile Let me add a caution to what bearophile says here- a minimum spanning tree minimizes the weight of the *whole tree*, not the individual paths in that tree, which seems to be what you're going after. Those can be pretty different things. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Representing a Tree in Python
> But let me clear the my problem again. I have a graph. and I want to > find 'shortest path tree' from a root node to several nodes. as a > example if we have a graph of 5 nodes from 1 to 5, I need to build the > shortest path tree from node 1 to nodes 2,3,5. So my question is > instead of keeping separate lists for each destination node's shortest > path. How can I represent and store them in a tree structure using > python. Then I can easily find out what are the common nodes in the > path to each destination. A tree is just a connected acyclic rooted graph, so however you're representing graphs should be a perfectly natural representation for your shortest paths tree. In effect, you just treat the shortest paths operation as an subgraph operation which only preserves the edges that are part of a shortest path. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Representing a Tree in Python
On May 13, 12:10 am, godshorse wrote: > Hello, > > I want to find out the shortest path tree from a root to several nodes > in a graph data structure. I found a Dijkstra code from internet that > finds shortest path between only two nodes. How can i extend it to a > tree?. And what is the best way to represent a tree in Python?. > > Thank you, Well, I'm biased, but I like http://graphine.org>. As an example, to build a five node tree: >>> from graph.base import Graph >>> g = Graph() >>> for i in range(5): ... g.add_node(i) ... >>> g.add_edge(0, 1) >>> g.add_edge(0, 2) >>> g.add_edge(1, 3) >>> g.add_edge(1, 4) And to find the shortest path between, say, node 0 and node 4: >>> start = g[0] >>> end = g[4] >>> distance, edges = g.get_shortest_paths(start)[end] >>> distance 2 >>> edges [Edge(name=(0,1)), Edge(name=(1,4))] Let me know what you think if you decide to use it- I'm looking for feedback. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: ECG segmentation
On May 8, 2:04 pm, Filip Gruszczyński wrote: > Hi! > > I need to create a script, that performs ECG segmentation, but I can > hardly find any useful materials on the web. Did anyone try to do this > and could point me to some good materials/snippets about this? > > -- > Filip Gruszczyński How are you looking to do it? If you want an HMM-based solution I'd recommend http://ghmm.sourceforge.net/ghmm-python-tutorial.html>. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: [RELEASED] Python 3.1 beta 1
On May 7, 9:12 am, Scott David Daniels wrote: > Daniel Fetchinson wrote: > >> Other features include an ordered dictionary implementation > > > Are there plans for backporting this to python 2.x just as > > multiprocessing has been? > > Why not grab the 3.1 code and do it yourself for your 2.X's? > It should be far less work than attempting something as > fidgety as multiprocessing. > > --Scott David Daniels > scott.dani...@acm.org If OrderedDict winds up being backported, will you include it in 2.x? Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: help for documentation and license
On May 5, 2:30 pm, Gökhan SEVER wrote: > Hi, > > Even though I don't know what your project does, you will need to use > "Sphinx" to create semi-automatic documentation out of your project. > > I would recommend you to take a look a quality "free" Python module: > Matplotlib (http://matplotlib.sourceforge.net/index.html) > Go ahead, and check out the main svn trunk. There you will see all > what you need about documentation creation with Sphinx. > > Good luck... > > Gökhan > > On Tue, May 5, 2009 at 12:43 PM, Murali kumar wrote: > > hi all.. > > > I finished my application using python 2.6 and wxpython 2.8.9 > > >>> I want to generate documentation for my application.. > > please suggest me and provide links to generate documents in easy > > way.. > > >>> I want to host my product as open source.. I'dont know about licensing.. > > help me for this also.. You can autogenerate API docs using pydoc (builtin, usually ugly) or epydoc (external, not so ugly), or you can use a project like sphinx for hand written docs. As far as hosting goes, sourceforge is usually the way to go, although I'm a huge fan of gitorious (in fact, wrote a recipe to autogenerate API docs for markdown http://code.activestate.com/recipes/576733/>) but you have to be using git for it to work. Github is another choice. If that's the case. As far as licensing goes, you have a *LOT* of options, so you may want to check out http://en.wikipedia.org/wiki/Comparison_of_free_software_licenses> Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Can someone please explain to me this code?
> root.change_attributes(event_mask = X.KeyPressMask) This asks X to send this application keypress events > root.grab_key(keycode, X.AnyModifier, 1,X.GrabModeAsync, X.GrabModeAsync) This tells X to grab the keyboard if the given keycode is generated and any modifier is pressed, not to stop processing keyboard events, and not to stop processing pointer events. That's pretty safe, although I'm not sure if you'd need the modifier for your application. -- http://mail.python.org/mailman/listinfo/python-list
Re: Self function
On May 5, 2:08 am, Steven D'Aprano wrote: > On Mon, 04 May 2009 17:54:50 -0400, Terry Reedy wrote: > > bearophileh...@lycos.com wrote: > > >> Another possible syntax: > > >> def fact(n): > >> return 1 if n <= 1 else n * return(n - 1) > > >> But I guess most people don't see this problem as important&common > >> enough to justify changing the language. > > > Actually, I would like a way to refer to the current function from > > inside a function. but I would like support in the language, so that > > the compiler patched the code after the function object is created to > > directly refer to the function object (or can the code object call the > > code object?) without any name lookup at all. > > I don't know about avoiding name lookup, that smacks of deepest black > magic, and Python doesn't usually do that. It does however do parlour > tricks like `__name__` and `self`, suggests a solution. > > I propose a small piece of sugar. When a function is entered, Python > creates an ordinary local name in the function's local namespace, and > binds the function itself to that name. Two possibilities for the name > are `this` or `__this__`, analogous to `self` in methods and `__name__` > in modules. > > If there is any support for this, I propose to send the following (long) > post to python-ideas. Feedback, corrections and suggestions welcome. [snip proposal] I'm not all that in favor of this, but I think I've got another use case for you at http://code.activestate.com/recipes/576731/. The functions written to use it would be a lot more standard looking at least. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Any idea to emulate tail -f
On May 5, 2:00 am, Joel Juvenal Rivera Rivera wrote: > I want to make something very similar to the command tail -f (follow a > file), i have been trying with some while True and some microsleeps > (about .1 s); did someone has already done something like this? > > And about the file is the apache acceslog of a site with a lot of > traffic. > > Regards > > joe / Joel Rivera You might want to try http://pyinotify.sourceforge.net/. Works well on Linux systems. Otherwise, I'd watch the mtime on the file and fork to handle the change. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: local module-docs server on Linux?
On May 4, 10:30 pm, Soumen banerjee wrote: > Hello, > I had used python on windows and one of the features i liked best was > that you could start a module-docs server and then use firefox to > access it. pydoc -p -- http://mail.python.org/mailman/listinfo/python-list
Re: Database help needed
On May 4, 7:51 pm, Emile van Sebille wrote: > On 5/4/2009 4:30 PM Amber said... > > > > > > > My PHB is insane. > > > Today he drops 50,000 databases in MS Access format on my desk, and > > tells me that by Friday I need to: > > * Remove all of the "junk content" in the record fields; > > * Remove all records with blank fields in them; > > * Correct all fields in which the markup is "wrong"; > > * Correct all fields in which the data is "wrong"; > > * Ensure that all database include some specific tables; > > ** Add appropriate content to the records in the "new" tables; > > > And finally, said databases are to be in: > > > * MS Access 97 format; > > * MS Access 2000 format; > > * MS Access 2003 format; > > ** Is there any documentation anywhere on what the differences between > > those is? Won't a database created for Access 97 be openable in MS > > Access 2003? > > * SQLite format; > > * MySQL format; > > * PDB format, for use on his PalmPilot; > > * Commas separated values; > > * dBase 3; > > * Excell spreadsheets; > > * ODF spreadsheets; > > It wouldn't surprise me that you couldn't do all this with open office > using command line options which is where I'd start. There's also > python modules available, but I haven't yet gotten into them. I found > most of what I needed on groups.google.com though, so not having > internet access could be trouble -- some of the conversion structures > and requirements weren't quite so obvious nor documentation easily > available. > > Emile I was just about to recommend OO. PyUNO is pretty easy to use, IMHO, and while I obviously have no idea what your boss wants in specific, it shouldn't be too bad. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it better to use threads or fork in the following case
> Which brings us backs to the "20 questions"-part of my earlier post. It > could be, but it could also be that processing takes seconds. Or it takes > so long that even concurrency won't help. Who knows? Probably the OP ;) Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it better to use threads or fork in the following case
> In addition, the zip file format stores the directory at the end of the > file. So you can't process it until it's completely downloaded. > Concurrency doesn't help here. Don't think that's relevant, if I'm understanding the OP correctly. Lets say you've downloaded the file once and you're doing whatever the app does with it. Now, while that's happening the half an hour time limit comes up. Now you want to start another download, but you also want to continue to work with the old version. Voila, concurrency. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it better to use threads or fork in the following case
Probably better just to check HEAD and see if its updated within the time you're looking at before any unpack. Even on a 56k that's going to be pretty fast, and you don't risk unpacking an old file while a new version is on the way. If you still want to be able to unpack the old file if there's an update then you're probably right about needing to run it concurrently, and personally I'd just fork it for ease of use- it doesn't sound like you're trying to run 100,000 of these at the same time, and you're saving the file anyway. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: How to measure the memory cost in Python?
Alright, it's pretty obvious that I have a lot to learn before I'll be able to intelligently address this problem, but if somebody could point me at something that would help me figure out the terminology at least I'd really appreciate it. From what you're saying, it sounds like a combination of the above approaches would do what I'm asking- ie, get all the containers, then get the contents of each container- but I don't see why that would work unless gc tracks some kind of global container for small values, which, as I (poorly) understand it, are tracked separately? Thanks again, Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: eric not working on ubuntu 9.04
> File "/usr/lib/python2.6/email/message.py", line 790, in Message > from email.Iterators import walk Well, the module is called email.iterators (rather than email.Iterators), for starters. It looks like __all__ exports both names (which seems a little dodgy to me, but hey, y'all are the experts) but Ubuntu messes with Python a lot before it makes it to a package. I don't have a jaunty box handy, but my guess is that some heinous confluence of email.iterators.walk moving to Message.walk() in python 3, the module email.Iterators not existing anymore, and Ubuntu messing with Python has caused the whole house of cards to come crashing down. If I were you, I'd probably do the following: 1) file a ubuntu bug report 2) see if you can fire up the interpreter and see if the following works: >>> from email.Iterators import walk If not, try it with the 'i' lowercased. If that works, you've got your culprit. Otherwise, let me know and I'll take a look at it when I get back in front of my jaunty box. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Can someone please explain to me this code?
On Sat, May 2, 2009 at 9:41 PM, Soumen banerjee wrote: Hello, I was trying to find a method to make global hotkeys with python in linux. I found this one which uses a library called python-xlib. The point is that since i dont have much experience with this, i cant understand some of the code. Can someone please explain to me how this code works? According to the author, it is meant to reduce and increase volume. Im not interested in that specifically. All i want is to be ale to bind a hotkey to a function in my python program. It's not so hard. Just a little confusing at first. The thing is that X is a client-server protocol, so it doesn't call a function or anything to let you know that the user has pressed a key- it just sends all the events you've asked for to your application, and lets it handle them how it will. To get a better idea about how that happens, fire up xev (the X Event Viewer) on your console. from Xlib.display import Display from Xlib import X You still need these def handle_event(aEvent): keycode = aEvent.detail if aEvent.type == X.KeyPress: if keycode == vol_moins: changeVolume(-2) elif keycode == vol_plus: changeVolume(+2) (Spacing mine) You don't really care about this, but the important thing is how it's structured. It takes an event, then gets its detail attribute, which is where the key that is pressed will go if it is a keypress, then sees if its type is KeyPress, then performs the appropriate action based on that keycode. Your app will do pretty much the same thing, just with different actions. def main(): # current display disp = Display() root = disp.screen().root # we tell the X server we want to catch keyPress event root.change_attributes(event_mask = X.KeyPressMask) for keycode in keys: root.grab_key(keycode, X.AnyModifier, 1,X.GrabModeAsync, X.GrabModeAsync) while 1: event = root.display.next_event() handle_event(event) if __name__ == '__main__': main() (spacing mine) While I'd do things a little differently, this is pretty much boilerplate. You can use this as a template for what you want to do, assuming that you've appropriately defined your keycodes and handle_event function. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another list comprehension question
On May 2, 10:13 pm, Ross wrote: > I'm trying to set up a simple filter using a list comprehension. If I > have a list of tuples, a = [(1,2), (3,4), (5,None), (6,7), (8, None)] > and I wanted to filter out all tuples containing None, I would like to > get the new list b = [(1,2), (3,4),(6,7)]. try this: b = [i for i in a if None not in i] > I tried b = [i for i in a if t for t in i is not None] but I get the > error that "t is not defined". What am I doing wrong? You've got a "for" and an "if" backwards. t isn't defined when the if tries to evaluate it. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to measure the memory cost in Python?
> > PS) The asizeof(obj) function from this recipe > code.activestate.com/recipes/546530> does size the object plus its > > references, recursively. > > Correction, the last sentence should be: The asizeof(obj) ... plus its > referents, recursively. I will admit, I have *no idea* what that code is doing, but in looking through the gc module documentation, I'm seeing the gc.get_objects function. Would it be equivalent to what the OP is asking to track the size of every element returned by that? -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes: reference of a struct member?
ctypes.byref() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to measure the memory cost in Python?
> sys.getsizeof() [a suggested solution] isn't platform-specific. So, to answer the OP's question, you'd just do something like def get_totalsize(obj): total_size = sys.getsizeof(obj) for value in vars(obj).values(): try: total_size += get_total_size(value) except: total_size += sys.getsizeof(value) return totalSize def get_current_size(env): size = 0 for value in env.values(): try: size += get_total_size(value) except: pass return size get_current_size(vars()) and discount the weight of the interpreter? -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing a function as an argument from within the same class?
> Careful, bearophiles' answer remains the best one. > > The only reason your example worked is that you had already had > SomeClass defined (probably from a previous experiment). Scott is correct, and if bearophile and I ever give you conflicting advice, take bearophile's. A (corrected) bit of code that might serve your purpose would be as follows: class SomeClass: def doNothing(): pass def function1(self): print "running function 1" def function2(self, passedFunction=doNothing): print "running passed function" passedFunction() again, though- bearophile's is the best, and most standard, answer here -- http://mail.python.org/mailman/listinfo/python-list
Re: How to measure the memory cost in Python?
Not OP, but I'd actually like to know if there's an answer to this one that doesn't involve platform-specific tools. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing a function as an argument from within the same class?
Make doNothing a classmethod. class SomeClass: @classmethod def doNothing(cls): pass def function1(self): print "Running function 1" def function2(self, passedFunction=SomeClass.doNothing): print "Running passed function" passedFunction() someObject = SomeClass() someObject.function2() someObject.function2(someObject.function1) -- http://mail.python.org/mailman/listinfo/python-list
Re: where to start with
I'd add http://diveintopython.org/ to that list as you gain more experience with Python, or if you already know at least one language. -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes
At the risk of self-promotion, you may want to try this recipe . Then just do the following: >>> @C_function("/home/luca/Desktop/luca/progetti_eric/Pico/libusbtc08-1.7.2/src/.libs/libusbtc08.so") ... def usb_tc08_get_single(handle: "c_short", temp: "*c_float", overflow_flags: "*c_short", units: "c_short") -> "c_short": ... return usb_tc08_get_single.c_function(handle, temp, overflow_flags, units) Make sure to properly handle your arrays, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Recommendations on Pythonic tree data structure design techniques
I'm writing a Python graph library (called Graphine) that's pretty easy to use and does what you want. It is pre-alpha right now, but if you're interested please let me know- I'm very interested in hearing outside opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: safe eval of moderately simple math expressions
how about sympy? http://code.google.com/p/sympy/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get back an object from its id() value
Correction: the UserString will be dead on the final line. When I typed it in I had a strong reference still hanging around. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get back an object from its id() value
> I don't know what is the best: > * using an additional dict and maintaining it It works, but as you say, is somewhat inelegant. > * or using the "di" module proposed by CTO Let me be clear: I am not proposing that you use it. It *does* do what you ask- but what you are asking is, all by itself, not a good idea. The dict is a vastly superior- and standard- solution to the problem of mapping one object onto another. > If "di" is reliable, it seems a good solution for my initial constraint > which is the impossibility to store anything but strings in my data > structure. di is not reliable. Its author says so, and took a lot of heat for not saying so in Hollywood-sign letters, lit on fire and a thousand feet tall. If all you are worried about is storing a string, how about UserString? Notice the difference: >>> from collections import UserString >>> import weakref >>> weakref.ref("ABC") Traceback (most recent call last): File "", line 1, in TypeError: cannot create weak reference to 'str' object >>> weakref.ref(UserString("ABC")) This way you don't have to maintain a dictionary, only store your string once, and don't have to hack and kludge your way around id mappings. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get back an object from its id() value
> You could create a dict with the string as the key and the object as the > value. This will create a strong reference to the object, which is (I'm assuming) undesired behavior. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get back an object from its id() value
> But how do I get a usable reference from the id value? > For example, if "foo" has a method "bar()", how can I call "foo.bar()" > from "str(id(foo))" (say, 149466208). can you just use a weakref instead? It is certainly cleaner than trying to store id's, since an id is only guaranteed to be unique for the lifetime of the object in question, and the only way I know of correlating id's to objects involves some C- level trickery. for completeness- the trickery: http://www.friday.com/bbum/2007/08/24/python-di/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
> I just mean that there should be a > clear and easy way to do it, that it should be considered a basic > service, and that if the best way to satisfy all the goals is to > integrate it directly into the language, that shouldn't be shied away > from. Honestly, the programming language and the configuration languages should never, ever, ever be inseparable. I don't see a reason for it and I see some great reasons not to do it. > The example that I have on my blog post, I consider that 'syntax', > even though it's implemented as a function, mainly just because it > digs into the bytecode and modifies the normal way a function is > evaluated (the function's value is determined by where the output > would go). I don't particularly see why this is needed. To my mind the strongest argument you are making, by far, is the "discoverable" argument. If you were able to build a system which permitted other components to discover configuration options and give configurable levels of permanence and visibility to them, that would be great. If you were able to do it and make it easy for a programmer to interact with, you would most definitely have a module I would use. But I daresay you're going to have to build it (or at least mock it up) before you're going to get a lot of folks jumping on the bandwagon, and its a *long* slog before you hit the level of support and stability you're going to need to convince folks to trust their precious config files to it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating huge data in very less time.
1) How random is random enough? Some PRNGs are very fast, and some are very random, but theres always a compromise. 2) How closely related can the files be? It would be easy to generate 1GB of pseudorandom numbers, then just append UUIDs to them 3) Unique filenames can be generated with tmpnam -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On the one hand, I can 110% see why you want to reduce boilerplate code and provide a discoverable, common mechanism for automating the two and three-quarters parsers that a lot of applications have to write to handle a config file, CLI, and/or registry values, but why introduce a syntax for it? A module would do just fine in terms of function. Are you worried about the look of it, or do you want to make a change to make it seem more "mainstream"? I don't see the rationale. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ordered Sets
On Mar 28, 3:33 am, "Gabriel Genellina" wrote: > En Thu, 26 Mar 2009 12:20:17 -0300, Scott David Daniels > escribió: > > > (2) Why, oh why, do people feel so comforted adding double_underscores > > to data structures? Probably because other authors feel too comfortable using single underscores for things the end user should mess with, as in namedtuple. -- http://mail.python.org/mailman/listinfo/python-list