content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Why is "if not someobj:" better than "if someobj == None:" in Python? I've seen several examples of code like this: if not someobj: #do something But I'm wondering why not doing: if someobj == None: #do something Is there any difference? Does one have an advantage over the other? A: In the first test, ...
Why is "if not someobj:" better than "if someobj == None:" in Python?
I've seen several examples of code like this: if not someobj: #do something But I'm wondering why not doing: if someobj == None: #do something Is there any difference? Does one have an advantage over the other?
[ "In the first test, Python try to convert the object to a bool value if it is not already one. Roughly, we are asking the object : are you meaningful or not ? This is done using the following algorithm :\n\nIf the object has a __nonzero__ special method (as do numeric built-ins, int and float), it calls this method...
[ 207, 56, 39, 6, 3, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000100732_python.txt
Q: Building Python C extension modules for Windows I have a C extension module and it would be nice to distribute built binaries. Setuptools makes it easy to build extensions modules on OS X and GNU/Linux, since those OSs come with GCC, but I don't know how to do it in Windows. Would I need to buy a copy of Visual St...
Building Python C extension modules for Windows
I have a C extension module and it would be nice to distribute built binaries. Setuptools makes it easy to build extensions modules on OS X and GNU/Linux, since those OSs come with GCC, but I don't know how to do it in Windows. Would I need to buy a copy of Visual Studio, or does Visual Studio Express work? Can I just ...
[ "You can use both MinGW and VC++ Express (free, no need to buy it).\nSee:\n\nhttp://eli.thegreenplace.net/2008/06/28/compiling-python-extensions-with-distutils-and-mingw/\nhttp://eli.thegreenplace.net/2008/06/27/creating-python-extension-modules-in-c/\n\n", "Setuptools and distutils don't come with gcc, but they ...
[ 16, 3 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0000101061_python_windows.txt
Q: Is there a zip-like method in .Net? In Python there is a really neat function called zip which can be used to iterate through two lists at the same time: list1 = [1, 2, 3] list2 = ["a", "b", "c"] for v1, v2 in zip(list1, list2): print v1 + " " + v2 The above code should produce the following: 1 a 2 b 3 c I wo...
Is there a zip-like method in .Net?
In Python there is a really neat function called zip which can be used to iterate through two lists at the same time: list1 = [1, 2, 3] list2 = ["a", "b", "c"] for v1, v2 in zip(list1, list2): print v1 + " " + v2 The above code should produce the following: 1 a 2 b 3 c I wonder if there is a method like it availab...
[ "Update: It is built-in in C# 4 as System.Linq.Enumerable.Zip Method\nHere is a C# 3 version:\nIEnumerable<TResult> Zip<TResult,T1,T2>\n (IEnumerable<T1> a,\n IEnumerable<T2> b,\n Func<T1,T2,TResult> combine)\n{\n using (var f = a.GetEnumerator())\n using (var s = b.GetEnumerator())\n {\n ...
[ 26, 8, 6, 2 ]
[]
[]
[ ".net", "iteration", "list", "python" ]
stackoverflow_0000101174_.net_iteration_list_python.txt
Q: Python module functions used in unexpected ways Based on "Split a string by spaces in Python", which uses shlex.split to split a string with quotes smartly, I would be interested in hearing about other common tasks solved by non-obvious standard library functions. If this turns into Module of The Week, that's fi...
Python module functions used in unexpected ways
Based on "Split a string by spaces in Python", which uses shlex.split to split a string with quotes smartly, I would be interested in hearing about other common tasks solved by non-obvious standard library functions. If this turns into Module of The Week, that's fine too.
[ "I was quite surprised to learn that you could use the bisect module to do a very fast binary search in a sequence. It's documentation doesn't say anything about it:\n\nThis module provides support for maintaining a list in sorted order without having to sort the list after each insertion.\n\nThe usage is very simp...
[ 7, 4, 4, 2, 2, 1, 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000092533_python.txt
Q: What's a good way to find relative paths in Google App Engine? So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of: siteroot/ models/ controllers/ controller1/ controller2/ ... t...
What's a good way to find relative paths in Google App Engine?
So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of: siteroot/ models/ controllers/ controller1/ controller2/ ... templates/ template1/ template2/ ... ..etc. ...
[ "You can't use relative paths, as Toni suggests, because you have no guarantee that the path from your working directory to your app's directory will remain the same.\nThe correct solution is to either use os.path.split, as you are, or to use something like:\npath = os.path.join(os.path.dirname(__file__), '..', 'te...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000061894_google_app_engine_python.txt
Q: Sorting a dict on __iter__ I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys? A: How about something ...
Sorting a dict on __iter__
I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?
[ "How about something like this:\ndef itersorted(d):\n for key in sorted(d):\n yield d[key]\n\n", "By far the easiest approach, and almost certainly the fastest, is something along the lines of:\ndef sorted_dict(d):\n keys = d.keys()\n keys.sort()\n for key in keys:\n yield d[key]\n\nYou ...
[ 9, 3, 3 ]
[ "Assuming you want a default sort order, you can used sorted(list) or list.sort(). If you want your own sort logic, Python lists support the ability to sort based on a function you pass in. For example, the following would be a way to sort numbers from least to greatest (the default behavior) using a function.\nd...
[ -1 ]
[ "optimization", "python", "refactoring" ]
stackoverflow_0000102394_optimization_python_refactoring.txt
Q: Python implementation of Parsec? I recently wrote a parser in Python using Ply (it's a python reimplementation of yacc). When I was almost done with the parser I discovered that the grammar I need to parse requires me to do some look up during parsing to inform the lexer. Without doing a look up to inform the le...
Python implementation of Parsec?
I recently wrote a parser in Python using Ply (it's a python reimplementation of yacc). When I was almost done with the parser I discovered that the grammar I need to parse requires me to do some look up during parsing to inform the lexer. Without doing a look up to inform the lexer I cannot correctly parse the strin...
[ "I believe that pyparsing is based on the same principles as parsec.\n", "PySec is another monadic parser, I don't know much about it, but it's worth looking at here\n", "An option you may consider, if an LL parser is ok to you, is to give ANTLR a try, it can generate python too (actually it is LL(*) as they na...
[ 9, 6, 5, 2, 1, 0 ]
[]
[]
[ "combinators", "parsec", "parsing", "python" ]
stackoverflow_0000094952_combinators_parsec_parsing_python.txt
Q: Anyone used Dabo for a medium-big project? We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects? ...
Anyone used Dabo for a medium-big project?
We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects? Thanks for your time!
[ "I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply.\nDabo is indeed well-known in the Python community. I have presented it at 3 of the ...
[ 25, 2 ]
[]
[]
[ "dabo", "erp", "python" ]
stackoverflow_0000056417_dabo_erp_python.txt
Q: Are there any "nice to program" GUI toolkits for Python? I've played around with GTK, TK, wxPython, Cocoa, curses and others. They are are fairly horrible to use.. GTK/TK/wx/curses all seem to basically be direct-ports of the appropriate C libraries, and Cocoa basically mandates using both PyObjC and Interface Bui...
Are there any "nice to program" GUI toolkits for Python?
I've played around with GTK, TK, wxPython, Cocoa, curses and others. They are are fairly horrible to use.. GTK/TK/wx/curses all seem to basically be direct-ports of the appropriate C libraries, and Cocoa basically mandates using both PyObjC and Interface Builder, both of which I dislike.. The Shoes GUI library for Ruby...
[ "Have you looked at Qt/PyQt? Although PyQt is a direct port from the C++ library, I find it much more pythonic and nice to program with compared to the others you listed. It also has very good documentation.\nDabo has a nice ui library implemented on top of wxPython. It's a framework intended mostly for database-ce...
[ 14, 14, 2, 1, 1 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0000035922_python_user_interface.txt
Q: Why unicode() uses str() on my object only with no encoding given? I start by creating a string variable with some non-ascii utf-8 encoded data on it: >>> text = 'á' >>> text '\xc3\xa1' >>> text.decode('utf-8') u'\xe1' Using unicode() on it raises errors... >>> unicode(text) Traceback (most recent call last): F...
Why unicode() uses str() on my object only with no encoding given?
I start by creating a string variable with some non-ascii utf-8 encoded data on it: >>> text = 'á' >>> text '\xc3\xa1' >>> text.decode('utf-8') u'\xe1' Using unicode() on it raises errors... >>> unicode(text) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can...
[ "The behaviour does seem confusing, but intensional. I reproduce here the entirety of the unicode documentation from the Python Built-In Functions documentation (for version 2.5.2, as I write this):\n\nunicode([object[, encoding [, errors]]])\nReturn the Unicode string version of object using one of the following m...
[ 8, 5 ]
[]
[]
[ "encoding", "python", "unicode" ]
stackoverflow_0000106630_encoding_python_unicode.txt
Q: PLY: Token shifting problem in C parser I'm writing a C parser using PLY, and recently ran into a problem. This code: typedef int my_type; my_type x; Is correct C code, because my_type is defined as a type previously to being used as such. I handle it by filling a type symbol table in the parser that gets used by...
PLY: Token shifting problem in C parser
I'm writing a C parser using PLY, and recently ran into a problem. This code: typedef int my_type; my_type x; Is correct C code, because my_type is defined as a type previously to being used as such. I handle it by filling a type symbol table in the parser that gets used by the lexer to differentiate between types and...
[ "Not sure why you're doing that level of analysis in your lexer.\nLexical analysis should probably be used to separate the input stream into lexical tokens (number, line-change, keyword and so on). It's the parsing phase that should be doing that level of analysis, including table lookups for typedefs and such.\nT...
[ 3, 2, 1 ]
[]
[]
[ "parsing", "ply", "python", "yacc" ]
stackoverflow_0000108009_parsing_ply_python_yacc.txt
Q: Topological sort, recursive, using generators Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } I'd like to have a top-down, recursive soluti...
Topological sort, recursive, using generators
Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } I'd like to have a top-down, recursive solution to let's say, find the chain starting at 'a': ...
[ "Both answers give the same result, but if my reading of the question is correct give the wrong answer to a simple alteration to the given graph - if you add a dependency on 'c' from 'b' (which doesn't introduce a cycle as the graph is directed) the output is: \na\nc\nd\ne\ng\nf\nb\nd\ne\ng\nf\n\nwhich isn't totall...
[ 6, 4 ]
[]
[]
[ "generator", "python", "recursion", "topology" ]
stackoverflow_0000108586_generator_python_recursion_topology.txt
Q: Python signal woes: SIGQUIT handler delays execution if SIGQUIT received during execution of another signal handler? The following program is very simple: it outputs a single dot each half a second. If it recieves a SIGQUIT, it proceeds to output ten Qs. If it recieves a SIGTSTP (Ctrl-Z), it outputs ten Zs. If it ...
Python signal woes: SIGQUIT handler delays execution if SIGQUIT received during execution of another signal handler?
The following program is very simple: it outputs a single dot each half a second. If it recieves a SIGQUIT, it proceeds to output ten Qs. If it recieves a SIGTSTP (Ctrl-Z), it outputs ten Zs. If it recieves a SIGTSTP while printing Qs, it will print ten Zs after it's done with the ten Qs. This is a good thing. However,...
[ "Your larger problem is blocking in signal handlers.\nThis is usually discouraged since it can lead to strange timing conditions. But it's not quite the cause of your problem since the timing condition you're vulnerable to exists because of your choice of signal handlers.\nAnyway, here's how to at least minimize t...
[ 6, 1 ]
[]
[]
[ "python", "signals" ]
stackoverflow_0000109705_python_signals.txt
Q: How does one decrypt a PDF with an owner password, but no user password? Although the PDF specification is available from Adobe, it's not exactly the simplest document to read through. PDF allows documents to be encrypted so that either a user password and/or an owner password is required to do various things wit...
How does one decrypt a PDF with an owner password, but no user password?
Although the PDF specification is available from Adobe, it's not exactly the simplest document to read through. PDF allows documents to be encrypted so that either a user password and/or an owner password is required to do various things with the document (display, print, etc). A common use is to lock a PDF so that e...
[ "A plugin for GSview for viewing encrypted PDFs is here.\nIf this works for you, you may be able to look at the source.\n", "If I remember correctly, there is a fixed padding string of 32 (?) bytes to apply to any password. All passwords need to be 32 bytes at the start of computing the encryption key, either by ...
[ 1, 1, 0 ]
[]
[]
[ "c++", "encryption", "passwords", "pdf", "python" ]
stackoverflow_0000049455_c++_encryption_passwords_pdf_python.txt
Q: How do you load an embedded icon from an exe file with PyWin32? I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe: windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ... I tried loading the icon using: hinst = win32api.GetModuleHandle(Non...
How do you load an embedded icon from an exe file with PyWin32?
I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe: windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ... I tried loading the icon using: hinst = win32api.GetModuleHandle(None) hicon = win32gui.LoadImage(hinst, 0, win32con.IMAGE_ICON, 0, 0, wi...
[ "@efotinis: You're right. \nHere is a workaround until py2exe gets fixed and you don't want to include the same icon twice:\nhicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 1), True)\n\nBe aware that 1 is not the ID you gave the icon in setup.py (which is the icon group ID), b...
[ 5, 1, 1, 0 ]
[]
[]
[ "exe", "icons", "python", "pywin32" ]
stackoverflow_0000090775_exe_icons_python_pywin32.txt
Q: Report generation I am writing a web app using TurboGears, and in that app the users must be able to generate different reports. The data the reports need is stored in a database (MySQL). The reports must be returned either as a easily printable html document, or a pdf file. I have previously used jasper and iRepo...
Report generation
I am writing a web app using TurboGears, and in that app the users must be able to generate different reports. The data the reports need is stored in a database (MySQL). The reports must be returned either as a easily printable html document, or a pdf file. I have previously used jasper and iReport for creating the doc...
[ "Pod is my favorite solution to your problem.\n", "You can build some fancy PDFs from Python with the ReportLab toolkit.\n", "A partial answer: the easily readable format you are looking for might be DocBook. From there it is very easy to go to PDF, html, RTF, etc. etc.\n" ]
[ 5, 2, 1 ]
[]
[]
[ "python", "report" ]
stackoverflow_0000110760_python_report.txt
Q: Distributed python What is the best python framework to create distributed applications? For example to build a P2P app. A: I think you mean "Networked Apps"? Distributed means an app that can split its workload among multiple worker clients over the network. You probably want. Twisted A: You probably want Twi...
Distributed python
What is the best python framework to create distributed applications? For example to build a P2P app.
[ "I think you mean \"Networked Apps\"? Distributed means an app that can split its workload among multiple worker clients over the network.\nYou probably want.\nTwisted\n", "You probably want Twisted. There is a P2P framework for Twisted called \"Vertex\". While not actively maintained, it does allow you to tunn...
[ 9, 3, 2, 1, 1 ]
[]
[]
[ "distributed", "python" ]
stackoverflow_0000094334_distributed_python.txt
Q: How do I use genshi.builder to programmatically build an HTML document? I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the rig...
How do I use genshi.builder to programmatically build an HTML document?
I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the right way?
[ "It's not possible to build an entire page using just genshi.builder.tag -- you would need to perform some surgery on the resulting stream to insert the doctype. Besides, the resulting code would look horrific. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then...
[ 6, 3 ]
[]
[]
[ "genshi", "html", "python", "templates" ]
stackoverflow_0000112564_genshi_html_python_templates.txt
Q: How would one log into a phpBB3 forum through a Python script using urllib, urllib2 and ClientCookie? (ClientCookie is a module for (automatic) cookie-handling: http://wwwsearch.sourceforge.net/ClientCookie) # I encode the data I'll be sending: data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'})...
How would one log into a phpBB3 forum through a Python script using urllib, urllib2 and ClientCookie?
(ClientCookie is a module for (automatic) cookie-handling: http://wwwsearch.sourceforge.net/ClientCookie) # I encode the data I'll be sending: data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'}) # And I send it and read the page: page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login',...
[ "Have you tried fetching the login page first?\nI would suggest using Tamper Data to have a peek at exactly what's being sent when you request the login page and then log in normally using a web browser from a fresh start, with no initial cookies in place, so that your script can replicate it exactly.\nThat's the a...
[ 2, 0 ]
[]
[]
[ "post", "python", "urllib" ]
stackoverflow_0000112768_post_python_urllib.txt
Q: Writing to the windows logs in Python Is it possible to write to the windows logs in python? A: Yes, just use Windows Python Extension, as stated here. import win32evtlogutil win32evtlogutil.ReportEvent(ApplicationName, EventID, EventCategory, EventType, Inserts, Data, SID)
Writing to the windows logs in Python
Is it possible to write to the windows logs in python?
[ "Yes, just use Windows Python Extension, as stated here.\nimport win32evtlogutil\nwin32evtlogutil.ReportEvent(ApplicationName, EventID, EventCategory,\n EventType, Inserts, Data, SID)\n\n" ]
[ 20 ]
[]
[]
[ "logging", "python", "windows" ]
stackoverflow_0000113007_logging_python_windows.txt
Q: Python - When to use file vs open What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5) A: You should always use open(). As the documentation states: When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is mor...
Python - When to use file vs open
What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)
[ "You should always use open().\nAs the documentation states:\n\nWhen opening a file, it's preferable\n to use open() instead of invoking this\n constructor directly. file is more\n suited to type testing (for example,\n writing \"isinstance(f, file)\").\n\nAlso, file() has been removed since Python 3.0.\n", "...
[ 157, 33, 19, 7, 4, 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0000112970_file_python.txt
Q: What are the Python equivalents of the sighold and sigrelse functions found in C? It appears the Python signal module doesn't have anything similar to the sighold and sigrelse functions found in C, using signal.h. Are there Python equivalents of any sort? Many thanks! A: There is no way to ``block'' signals temp...
What are the Python equivalents of the sighold and sigrelse functions found in C?
It appears the Python signal module doesn't have anything similar to the sighold and sigrelse functions found in C, using signal.h. Are there Python equivalents of any sort? Many thanks!
[ "There is no way to ``block'' signals temporarily from critical sections (since this is not supported by all Unix flavors).\nhttps://docs.python.org/library/signal.html\n", "There are no direct bindings for this in Python. Accessing them through ctypes is easy enough; here is an example.\nimport ctypes, signal\nl...
[ 2, 2 ]
[]
[]
[ "python", "signals" ]
stackoverflow_0000113170_python_signals.txt
Q: How can I unit test responses from the webapp WSGI application in Google App Engine? I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using GAEUnit. How can I do this? I'd like to use the webapp frame...
How can I unit test responses from the webapp WSGI application in Google App Engine?
I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using GAEUnit. How can I do this? I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately WebTest does not...
[ "I have added a sample application to the GAEUnit project which demonstrates how to write and execute a web test using GAEUnit. The sample includes a slightly modified version of the 'webtest' module ('import webbrowser' is commented out, as recommended by David Coffin).\nHere's the 'web_tests.py' file from the sa...
[ 13, 2 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0000107675_google_app_engine_python_unit_testing.txt
Q: What is the fastest way to scale and display an image in Python? I am required to display a two dimensional numpy.array of int16 at 20fps or so. Using Matplotlib's imshow chokes on anything above 10fps. There obviously are some issues with scaling and interpolation. I should add that the dimensions of the array ar...
What is the fastest way to scale and display an image in Python?
I am required to display a two dimensional numpy.array of int16 at 20fps or so. Using Matplotlib's imshow chokes on anything above 10fps. There obviously are some issues with scaling and interpolation. I should add that the dimensions of the array are not known, but will probably be around thirty by four hundred. Thes...
[ "The fastest way to display 30x400 data points is to:\nUse OpenGL color arrays\nIf you can quickly transform your data to what OpenGL understands as color array, you could create a vertex array describing quads, one for each sensor, then update your color array and draw this orthographically on screen.\nUse OpenGL ...
[ 6 ]
[]
[]
[ "animation", "image_scaling", "matplotlib", "python" ]
stackoverflow_0000114597_animation_image_scaling_matplotlib_python.txt
Q: How do I overlap widgets with the Tkinter pack geometry manager? I want to put a Canvas with an image in my window, and then I want to pack widgets on top of it, so the Canvas acts as a background. Is it possible to have two states for the pack manager: one for one set of widgets and another for another set? A: ...
How do I overlap widgets with the Tkinter pack geometry manager?
I want to put a Canvas with an image in my window, and then I want to pack widgets on top of it, so the Canvas acts as a background. Is it possible to have two states for the pack manager: one for one set of widgets and another for another set?
[ "The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent. \nHowever, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas a...
[ 2, 1, 1, 0 ]
[]
[]
[ "geometry", "pack", "python", "tkinter" ]
stackoverflow_0000112263_geometry_pack_python_tkinter.txt
Q: Which is more pythonic, factory as a function in a module, or as a method on the class it creates? I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file. The calendar object just has a method that adds events as they get parsed. Now I want to create a factory...
Which is more pythonic, factory as a function in a module, or as a method on the class it creates?
I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file. The calendar object just has a method that adds events as they get parsed. Now I want to create a factory function that creates a calendar from a file object, path, or URL. I've been using the iCalendar python...
[ "[Note. Be very cautious about separating \"Calendar\" a collection of events, and \"Event\" - a single event on a calendar. In your question, it seems like there could be some confusion.]\nThere are many variations on the Factory design pattern.\n\nA stand-alone convenience function (e.g., calendarMaker(data))\n...
[ 13, 6, 2, 0, 0 ]
[]
[]
[ "factory", "python" ]
stackoverflow_0000115764_factory_python.txt
Q: How do you create an osx application/dmg from a python package? I want to create a mac osx application from python package and then put it in a disk image. Because I load some resources out of the package, the package should not reside in a zip file. The resulting disk image should display the background picture ...
How do you create an osx application/dmg from a python package?
I want to create a mac osx application from python package and then put it in a disk image. Because I load some resources out of the package, the package should not reside in a zip file. The resulting disk image should display the background picture to "drag here -> applications" for installation.
[ "I don't know the correct way to do it, but this manual method is the approach I've used for simple scripts which seems to have preformed suitably.\nI'll assume that whatever directory I'm in, the Python files for my program are in the relative src/ directory, and that the file I want to execute (which has the prop...
[ 7 ]
[]
[]
[ "macos", "packaging", "python" ]
stackoverflow_0000116657_macos_packaging_python.txt
Q: Python and POST data In PHP I simply write: $bob = $_POST['bob']; How do I do the same in Python? And yes, I do normally check that it exists etc, I'm just stripping it down specifically to the functionality I am after. Edit: I am not using a framework A: The simplest method is the 'cgi' module: import cgi dat...
Python and POST data
In PHP I simply write: $bob = $_POST['bob']; How do I do the same in Python? And yes, I do normally check that it exists etc, I'm just stripping it down specifically to the functionality I am after. Edit: I am not using a framework
[ "The simplest method is the 'cgi' module:\nimport cgi\ndata = cgi.FieldStorage()\ndata['bob']\n\nBut the context you are executing in (frameworks you're using, WSGI or even (heaven forbid) mod_python) may have different, more efficient or more direct methods of access.\n" ]
[ 10 ]
[]
[]
[ "http", "post", "python" ]
stackoverflow_0000117167_http_post_python.txt
Q: What is the scope for imported classes in python? Please excuse the vague title. If anyone has a suggestion, please let me know! Also please retag with more appropriate tags! The Problem I want to have an instance of an imported class be able to view things in the scope (globals, locals) of the importer. Since ...
What is the scope for imported classes in python?
Please excuse the vague title. If anyone has a suggestion, please let me know! Also please retag with more appropriate tags! The Problem I want to have an instance of an imported class be able to view things in the scope (globals, locals) of the importer. Since I'm not sure of the exact mechanism at work here, I can...
[ "In this example, you can simply hand over functions as objects to the methods in C1:\n>>> class C1(object):\n>>> def eval(self, x):\n>>> x()\n>>>\n>>> def f2(): print \"go f2\"\n>>> c = C1()\n>>> c.eval(f2)\ngo f2\n\nIn Python, you can pass functions and classes to other methods and invoke/create them th...
[ 2, 1 ]
[]
[]
[ "eval", "import", "python", "scope" ]
stackoverflow_0000117127_eval_import_python_scope.txt
Q: What's the Name of the Python Module that Formats arbitrary Text to nicely looking HTML? A while ago I came across a Python library that formats regular text to HTML similar to Markdown, reStructuredText and Textile, just that it had no syntax at all. It detected indentatations, quotes, links and newlines/paragra...
What's the Name of the Python Module that Formats arbitrary Text to nicely looking HTML?
A while ago I came across a Python library that formats regular text to HTML similar to Markdown, reStructuredText and Textile, just that it had no syntax at all. It detected indentatations, quotes, links and newlines/paragraphs only. Unfortunately I lost the name of the library and was unable to Google it. Anyone an...
[ "Okay. I found it now. It's called PottyMouth.\n", "Markdown in python is a python implementation of the perl based markdown utility.\nMarkown converts various forms of structured text to valid html, and one of the supported forms is just plain ascii. Use is pretty straight forward.\npython markdown.py input_fi...
[ 14, 1, 0 ]
[]
[]
[ "formatting", "markup", "python" ]
stackoverflow_0000117477_formatting_markup_python.txt
Q: Best practices for manipulating database result sets in Python? I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python'...
Best practices for manipulating database result sets in Python?
I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've w...
[ "The empty Record class and the free-floating function that (generally) applies to an individual Record is a hint that you haven't designed your class properly.\nclass Record( object ):\n \"\"\"Assuming rtda and pnl must exist.\"\"\"\n def __init__( self ):\n self.da= 0\n self.rt= 0\n sel...
[ 2, 1, 0 ]
[ "Using a ORM for an iPhone app might be a bad idea because of performance issues, you want your code to be as fast as possible. So you can't avoid boilerplate code. If you are considering a ORM, besides SQLAlchemy I'd recommend Storm.\n" ]
[ -2 ]
[ "database", "python" ]
stackoverflow_0000116894_database_python.txt
Q: How do I create a non-standard type with SOAPpy? I am calling a WSDL web service from Python using SOAPpy. The call I need to make is to the method Auth_login. This has 2 arguments - the first, a string being the API key; the second, a custom type containing username and password. The custom type is called Auth_cr...
How do I create a non-standard type with SOAPpy?
I am calling a WSDL web service from Python using SOAPpy. The call I need to make is to the method Auth_login. This has 2 arguments - the first, a string being the API key; the second, a custom type containing username and password. The custom type is called Auth_credentialsData which contains 2 values as stings - one ...
[ "The better method is to use the ZSI soap module which allows you to take a WDSL file and turn it into classes and methods that you can then use to call it. The online documentation is on their website but the latest documentation is more easily found in the source package. If you install in Debian/Ubuntu (package...
[ 0 ]
[]
[]
[ "python", "soap", "web_services" ]
stackoverflow_0000118467_python_soap_web_services.txt
Q: How to express this Bash command in pure Python I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive: find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \; I am familiar with the os....
How to express this Bash command in pure Python
I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive: find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \; I am familiar with the os.name and getpass.getuser for the most general cross-p...
[ "import os\nimport shutil\nfrom os import path\nfrom os.path import join, getmtime\nfrom time import time\n\narchive = \"bak\"\ncurrent = \"cur\"\n\ndef archive_old_versions(days = 3):\n for root, dirs, files in os.walk(current):\n for name in files:\n fullname = join(root, name)\n i...
[ 5, 3, 2, 0 ]
[]
[]
[ "language_comparisons", "python", "shell" ]
stackoverflow_0000118591_language_comparisons_python_shell.txt
Q: What is wrong with my snap to grid code? First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong. Here's the situation I have an abstract concept of a grid, with Y steps exactly Y_STEP a...
What is wrong with my snap to grid code?
First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong. Here's the situation I have an abstract concept of a grid, with Y steps exactly Y_STEP apart (the x steps are working fine so ignore t...
[ "Ok, I'm answering my own question here, as alexk mentioned, using int to truncate was my mistake. \nThe behaviour I'm after is best modeled by math.floor().\nApologies, the original question does not contain enough information to really work out what the problem is. I didn't have the extra bit of information at ...
[ 1, 0, 0 ]
[]
[]
[ "graphics", "grid", "python" ]
stackoverflow_0000118540_graphics_grid_python.txt
Q: Python-passing variable between classes I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how t...
Python-passing variable between classes
I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes. H...
[ "You may have \"Class\" and \"Instance\" confused. It's not clear from your example, so I'll presume that you're using a lot of class definitions and don't have appropriate object instances of those classes.\nClasses don't really have usable attribute values. A class is just a common set of definitions for a coll...
[ 8, 4, 2, 1, 0 ]
[]
[]
[ "oop", "python", "variables", "wxpython" ]
stackoverflow_0000113341_oop_python_variables_wxpython.txt
Q: Dynamically create variables inside function I want to create variables inside function from dictionary. Lets say I have a dictionary bar = {'a': 1, 'b': 2, 'c': 3} and function def foo(): pass What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as ...
Dynamically create variables inside function
I want to create variables inside function from dictionary. Lets say I have a dictionary bar = {'a': 1, 'b': 2, 'c': 3} and function def foo(): pass What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values So in the end it should be ...
[ "From your comment, perhaps what you're really looking for is something like a bunch object:\nclass Bunch(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\nb=Bunch(**form.cleaned_data)\n\nprint b.first_name, b.last_name\n\n(The ** syntax is because Bunch-type objects are usually u...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000119941_python.txt
Q: Does an application-wide exception handler make sense? Long story short, I have a substantial Python application that, among other things, does outcalls to "losetup", "mount", etc. on Linux. Essentially consuming system resources that must be released when complete. If my application crashes, I want to ensure the...
Does an application-wide exception handler make sense?
Long story short, I have a substantial Python application that, among other things, does outcalls to "losetup", "mount", etc. on Linux. Essentially consuming system resources that must be released when complete. If my application crashes, I want to ensure these system resources are properly released. Does it make sens...
[ "I like top-level exception handlers in general (regardless of language). They're a great place to cleanup resources that may not be immediately related to resources consumed inside the method that throws the exception.\nIt's also a fantastic place to log those exceptions if you have such a framework in place. Top-...
[ 11, 7, 2, 2, 1, 1 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0000095642_exception_handling_python.txt
Q: Using **kwargs with SimpleXMLRPCServer in python I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this: server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) ...
Using **kwargs with SimpleXMLRPCServer in python
I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this: server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() I then have a ServiceRemote cl...
[ "You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, examp...
[ 15, 4, 1, 1, 0 ]
[]
[]
[ "python", "simplexmlrpcserver", "xmlrpclib" ]
stackoverflow_0000119802_python_simplexmlrpcserver_xmlrpclib.txt
Q: Find matching sequences in two binary files Let me start off with a bit of background. This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another progr...
Find matching sequences in two binary files
Let me start off with a bit of background. This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem. A now...
[ "See the longest common substring problem. I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays.\nUsing perl Tree::Suffix might be easiest solution. Apparently it gives all common substrings in a specified length range:\n@lcs = $tr...
[ 5, 2, 1, 1, 0 ]
[]
[]
[ "antivirus", "binary", "diff", "python" ]
stackoverflow_0000119651_antivirus_binary_diff_python.txt
Q: Python idiom to chain (flatten) an infinite iterable of finite iterables? Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by infinite = itertools.cycle([[1,2,3]]) What is a good Python idiom to get an iterator (obviously infinite) that will return e...
Python idiom to chain (flatten) an infinite iterable of finite iterables?
Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by infinite = itertools.cycle([[1,2,3]]) What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc...
[ "Starting with Python 2.6, you can use itertools.chain.from_iterable:\nitertools.chain.from_iterable(iterables)\n\nYou can also do this with a nested generator comprehension:\ndef flatten(iterables):\n return (elem for iterable in iterables for elem in iterable)\n\n", "Use a generator:\n(item for it in infinit...
[ 52, 13 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0000120886_iterator_python.txt
Q: How can I join a list into a string (caveat)? Along the lines of my previous question, how can i join a list of strings into a string such that values get quoted cleanly. Something like: ['a', 'one "two" three', 'foo, bar', """both"'"""] into: a, 'one "two" three', "foo, bar", "both\"'" I suspect that the csv mo...
How can I join a list into a string (caveat)?
Along the lines of my previous question, how can i join a list of strings into a string such that values get quoted cleanly. Something like: ['a', 'one "two" three', 'foo, bar', """both"'"""] into: a, 'one "two" three', "foo, bar", "both\"'" I suspect that the csv module will come into play here, but i'm not sure how...
[ "Using the csv module you can do that way:\nimport csv\nwriter = csv.writer(open(\"some.csv\", \"wb\"))\nwriter.writerow(the_list)\n\nIf you need a string just use StringIO instance as a file:\nf = StringIO.StringIO()\nwriter = csv.writer(f)\nwriter.writerow(the_list)\nprint f.getvalue()\n\nThe output: a,\"one \"\"...
[ 7, 2, 1 ]
[]
[]
[ "csv", "list", "python", "string" ]
stackoverflow_0000118458_csv_list_python_string.txt
Q: Where can a save confirmation page be hooked into the Django admin? (similar to delete confirmation) I want to emulate the delete confirmation page behavior before saving certain models in the admin. In my case if I change one object, certain others should be deleted as they depend upon the object's now out-of...
Where can a save confirmation page be hooked into the Django admin? (similar to delete confirmation)
I want to emulate the delete confirmation page behavior before saving certain models in the admin. In my case if I change one object, certain others should be deleted as they depend upon the object's now out-of-date state. I understand where to implement the actual cascaded updates (inside the parent model's save...
[ "You could overload the get_form method of your model admin and add an extra checkbox to the generated form that has to be ticket. Alternatively you can override change_view and intercept the request.\n", "I'm by no means a Django expert, so this answer might misguide you. \nStart looking somewhere around django...
[ 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000114283_django_python.txt
Q: Python regular expression to split paragraphs How would one write a regular expression to use in Python to split paragraphs? A paragraph is defined by two line breaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph. I am using Python,...
Python regular expression to split paragraphs
How would one write a regular expression to use in Python to split paragraphs? A paragraph is defined by two line breaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph. I am using Python, so the solution can use Python's regular expressio...
[ "Unfortunately there's no nice way to write \"space but not a newline\".\nI think the best you can do is add some space with the x modifier and try to factor out the ugliness a bit, but that's questionable: (?x) (?: [ \\t\\r\\f\\v]*? \\n ){2} [ \\t\\r\\f\\v]*?\nYou could also try creating a subrule just for the c...
[ 5, 2, 2, 0 ]
[]
[]
[ "parsing", "python", "regex", "split", "text" ]
stackoverflow_0000116494_parsing_python_regex_split_text.txt
Q: Passing around urls between applications in the same project I am trying to mock-up an API and am using separate apps within Django to represent different web services. I would like App A to take in a link that corresponds to App B and parse the json response. Is there a way to dynamically construct the url to Ap...
Passing around urls between applications in the same project
I am trying to mock-up an API and am using separate apps within Django to represent different web services. I would like App A to take in a link that corresponds to App B and parse the json response. Is there a way to dynamically construct the url to App B so that I can test the code in development and not change to m...
[ "You could do something like\nif settings.DEBUG:\n other = \"localhost\"\nelse:\n other = \"somehost\"\n\nand use other to build the external URL. Generally you code in DEBUG mode and deploy in non-DEBUG mode. settings.DEBUG is a 'standard' Django thing.\n", "By \"separate apps within Django\" do you mean separ...
[ 1, 1 ]
[]
[]
[ "development_environment", "django", "python", "web_services" ]
stackoverflow_0000124108_development_environment_django_python_web_services.txt
Q: What is the intended use of the DEFAULT section in config files used by ConfigParser? I've used ConfigParser for quite a while for simple configs. One thing that's bugged me for a long time is the DEFAULT section. I'm not really sure what's an appropriate use. I've read the documentation, but I would really like t...
What is the intended use of the DEFAULT section in config files used by ConfigParser?
I've used ConfigParser for quite a while for simple configs. One thing that's bugged me for a long time is the DEFAULT section. I'm not really sure what's an appropriate use. I've read the documentation, but I would really like to see some clever examples of its use and how it affects other sections in the file (someth...
[ "I found an explanation here by googling for \"windows ini\" \"default section\". Summary: whatever you put in the [DEFAULT] section gets propagated to every other section. Using the example from the linked website, let's say I have a config file called test1.ini:\n[host 1]\nlh_server=192.168.0.1\nvh_hosts = Plon...
[ 56 ]
[]
[]
[ "configuration_files", "parsing", "python" ]
stackoverflow_0000124692_configuration_files_parsing_python.txt
Q: cx_Oracle: How do I iterate over a result set? There are several ways to iterate over a result set. What are the tradeoff of each? A: The canonical way is to use the built-in cursor iterator. curs.execute('select * from people') for row in curs: print row You can use fetchall() to get all rows at once. for ...
cx_Oracle: How do I iterate over a result set?
There are several ways to iterate over a result set. What are the tradeoff of each?
[ "The canonical way is to use the built-in cursor iterator.\ncurs.execute('select * from people')\nfor row in curs:\n print row\n\n\nYou can use fetchall() to get all rows at once.\nfor row in curs.fetchall():\n print row\n\nIt can be convenient to use this to create a Python list containing the values returne...
[ 55, 27, 6 ]
[]
[]
[ "cx_oracle", "database", "oracle", "python", "sql" ]
stackoverflow_0000000594_cx_oracle_database_oracle_python_sql.txt
Q: Adding New Element to Text Substring Say I have the following string: "I am the most foo h4ck3r ever!!" I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in: "I am the most <span class="special">foo></span> h4ck3r ever!!" BeautifulSoup seeme...
Adding New Element to Text Substring
Say I have the following string: "I am the most foo h4ck3r ever!!" I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in: "I am the most <span class="special">foo></span> h4ck3r ever!!" BeautifulSoup seemed like the way to go, but I haven't been a...
[ "How about this:\nPython 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def makeSpecial(mystring, special_substr):\n... return mystring.replace(special_substr, '<span class=\"special\">%s</span>...
[ 3, 1, 0 ]
[]
[]
[ "beautifulsoup", "javascript", "jquery", "python" ]
stackoverflow_0000125102_beautifulsoup_javascript_jquery_python.txt
Q: Python library for rendering HTML and javascript Is there any python module for rendering a HTML page with javascript and get back a DOM object? I want to parse a page which generates almost all of its content using javascript. A: The big complication here is emulating the full browser environment outside of a ...
Python library for rendering HTML and javascript
Is there any python module for rendering a HTML page with javascript and get back a DOM object? I want to parse a page which generates almost all of its content using javascript.
[ "The big complication here is emulating the full browser environment outside of a browser. You can use stand alone javascript interpreters like Rhino and SpiderMonkey to run javascript code but they don't provide a complete browser like environment to full render a web page.\nIf I needed to solve a problem like thi...
[ 8, 1 ]
[]
[]
[ "html", "javascript", "python" ]
stackoverflow_0000126131_html_javascript_python.txt
Q: How do I develop and create a self-contained PyGTK application bundle for MacOS, with native-looking widgets? I have read that it is possible to build GTK+ on MacOS X. I know that it's possible to create a bundle of a GTK+ application on MacOS. I also know that it's possible to create widgets that look sort of n...
How do I develop and create a self-contained PyGTK application bundle for MacOS, with native-looking widgets?
I have read that it is possible to build GTK+ on MacOS X. I know that it's possible to create a bundle of a GTK+ application on MacOS. I also know that it's possible to create widgets that look sort of native. However, searching around I am not really clear on how to create a bundle that includes the native theme st...
[ "Native looking widgets is quite complicated.\nThere's a beginning of quartz engine (for theming) found here http://git.gnome.org/browse/gtk+/tree/gdk/quartz\nFor self-contained applications check out the newly released bundle on http://live.gnome.org/GTK%2B/OSX\n", "I'm not sure if I'm grokking all the details o...
[ 3, 1, 1 ]
[]
[]
[ "gtk", "macos", "pygtk", "python" ]
stackoverflow_0000118138_gtk_macos_pygtk_python.txt
Q: How do I create a new signal in pygtk I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object. A: You can also define signals inside the class definition: class MyGObjectClass(gobject.GObject...
How do I create a new signal in pygtk
I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
[ "You can also define signals inside the class definition:\nclass MyGObjectClass(gobject.GObject):\n __gsignals__ = {\n \"some-signal\": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),\n }\n\nThe contents of the tuple are the the same as the three last arguments to gobject.signal_new.\n", "He...
[ 11, 4, 2 ]
[]
[]
[ "gobject", "gtk", "pygtk", "python" ]
stackoverflow_0000066730_gobject_gtk_pygtk_python.txt
Q: "cannot find -lpq" when trying to install psycopg2 Intro: I'm trying to migrate our Trac SQLite to a PostgreSQL backend, to do that I need psycopg2. After clicking past the embarrassing rant on www.initd.org I downloaded the latest version and tried running setup.py install. This didn't work, telling me I needed m...
"cannot find -lpq" when trying to install psycopg2
Intro: I'm trying to migrate our Trac SQLite to a PostgreSQL backend, to do that I need psycopg2. After clicking past the embarrassing rant on www.initd.org I downloaded the latest version and tried running setup.py install. This didn't work, telling me I needed mingw. So I downloaded and installed mingw. Problem: I no...
[ "Have you tried the binary build of psycopg2 for windows? If that works with your python then it mitigates the need to build by hand.\nI've seen random people ask this question on various lists and it seems one recommendation is to build postgresql by hand to work around this problem.\n", "Compiling extensions on...
[ 2, 1 ]
[]
[]
[ "postgresql", "python", "trac" ]
stackoverflow_0000126364_postgresql_python_trac.txt
Q: Checking for code changes in all imported python modules Almost every Python web framework has a simple server that runs a wsgi application and automatically reloads the imported modules every time the source gets changed. I know I can look at the code and see how it's done, but that may take some time and I'm ask...
Checking for code changes in all imported python modules
Almost every Python web framework has a simple server that runs a wsgi application and automatically reloads the imported modules every time the source gets changed. I know I can look at the code and see how it's done, but that may take some time and I'm asking just out of curiosity. Does anyone have any idea how this ...
[ "As the author of one of the reloader mechanisms (the one in werkzeug) I can tell you that it doesn't work. What all the reloaders do is forking one time and restarting the child process if a monitor thread notices that one module changed on the file system.\nInline reload()ing doesn't work because references to t...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000126787_python.txt
Q: How can i move an object drawn in device context python I have drawn an image in the device context using python and I want to move it smoothly/animate either vertically or horizontally. What algorithm should I use? Where can I get info for this kind of tasks in python? A: Once an object is drawn in a device con...
How can i move an object drawn in device context python
I have drawn an image in the device context using python and I want to move it smoothly/animate either vertically or horizontally. What algorithm should I use? Where can I get info for this kind of tasks in python?
[ "Once an object is drawn in a device context it stays there. If you want to move it you need to redraw it.\nYou can keep a background that's fixed and only redraw the movable elements each time they move. Basically that's how it's done.\nTo move an object smoothly over a line you have to do something like this (I d...
[ 1, 0 ]
[]
[]
[ "animation", "python" ]
stackoverflow_0000126738_animation_python.txt
Q: What is the best way to store set data in Python? I have a list of data in the following form: [(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type)) The data are loaded from files that belong to the same group. In each group there could be multiples of the sam...
What is the best way to store set data in Python?
I have a list of data in the following form: [(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type)) The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from different files. I don't care ab...
[ "Sets don't have keys. The element is the key.\nIf you think you want keys, you have a mapping. More-or-less by definition.\nSequential list lookup can be slow, even using a binary search. Mappings use hashes and are fast.\nAre you talking about a dictionary like this?\n{ 'id1': [ ('description1a', 'type1'), ('d...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "data_structures", "dictionary", "python", "set" ]
stackoverflow_0000128259_data_structures_dictionary_python_set.txt
Q: Getting Python to use the ActiveTcl libraries Is there any way to get Python to use my ActiveTcl installation instead of having to copy the ActiveTcl libraries into the Python/tcl directory? A: Not familiar with ActiveTcl, but in general here is how to get a package/module to be loaded when that name already exi...
Getting Python to use the ActiveTcl libraries
Is there any way to get Python to use my ActiveTcl installation instead of having to copy the ActiveTcl libraries into the Python/tcl directory?
[ "Not familiar with ActiveTcl, but in general here is how to get a package/module to be loaded when that name already exists in the standard library:\nimport sys\ndir_name=\"/usr/lib/mydir\"\nsys.path.insert(0,dir_name)\n\nSubstitute the value for dir_name with the path to the directory containing your package/modul...
[ 2 ]
[]
[]
[ "activetcl", "python" ]
stackoverflow_0000129912_activetcl_python.txt
Q: Example Facebook Application using TurboGears -- pyFacebook I have a TurboGears application I'd like to run through Facebook, and am looking for an example TurboGears project using pyFacebook or minifb.py. pyFacebook is Django-centric, and I can probably figure it out, but this is, after all, the lazy web. A: W...
Example Facebook Application using TurboGears -- pyFacebook
I have a TurboGears application I'd like to run through Facebook, and am looking for an example TurboGears project using pyFacebook or minifb.py. pyFacebook is Django-centric, and I can probably figure it out, but this is, after all, the lazy web.
[ "Why is pyFacebook django centric? Looks like it works perfectly fine with all kinds of WSGI apps or Python applications in general. No need to use Django.\n", "pyFacebook is Django-centric because it includes a Django example. I did not intend to irk, but am merely looking for a TurboGears example using pyFac...
[ 3, 1 ]
[]
[]
[ "facebook", "python", "turbogears" ]
stackoverflow_0000126356_facebook_python_turbogears.txt
Q: Do I have to cause an ValueError in Python I have this code: chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse I want to be able to do this because I don't like knowfully causing Exceptions: chars = #some list indx = chars.index(chars) if indx =...
Do I have to cause an ValueError in Python
I have this code: chars = #some list try: indx = chars.index(chars) except ValueError: #doSomething else: #doSomethingElse I want to be able to do this because I don't like knowfully causing Exceptions: chars = #some list indx = chars.index(chars) if indx == -1: #doSomething else: #doSomethingElse...
[ "Note that the latter approach is going against the generally accepted \"pythonic\" philosophy of EAFP, or \"It is Easier to Ask for Forgiveness than Permission.\", while the former follows it.\n", "if element in mylist:\n index = mylist.index(element)\n # ... do something\nelse:\n # ... do something els...
[ 9, 7, 0 ]
[]
[]
[ "exception", "list", "python" ]
stackoverflow_0000131449_exception_list_python.txt
Q: Contributing to Python I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute? A: Add to the docs. it is downright crappy Help out other users on the dev...
Contributing to Python
I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?
[ "\nAdd to the docs. it is downright crappy\nHelp out other users on the dev and user mailing lists. \nTEST PYTHON. bugs in programming languages are real bad. And I have seen someone discover atleast 1 bug in python\nFrequent the #python channel on irc.freenode.net\n\n", "Build something cool in Python and share ...
[ 7, 4, 3, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000127454_python.txt
Q: Generic Exception Handling in Python the "Right Way" Sometimes I find myself in the situation where I want to execute several sequential commands like such: try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... This same pattern occurs when exceptions simply nee...
Generic Exception Handling in Python the "Right Way"
Sometimes I find myself in the situation where I want to execute several sequential commands like such: try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... This same pattern occurs when exceptions simply need to be ignored. This feels redundant and the excessive sy...
[ "You could use the with statement if you have python 2.5 or above:\nfrom __future__ import with_statement\nimport contextlib\n\n@contextlib.contextmanager\ndef handler():\n try:\n yield\n except Exception, e:\n baz(e)\n\nYour example now becomes:\nwith handler():\n foo(a, b)\nwith handler():\...
[ 74, 15, 4, 3, 3 ]
[ "In your specific case, you can do this:\ntry:\n foo(a, b)\n bar(c, d)\nexcept Exception, e:\n baz(e)\n\nOr, you can catch the exception one step above:\ntry:\n foo_bar() # This function can throw at several places\nexcept Exception, e:\n baz(e)\n\n" ]
[ -4 ]
[ "exception", "python", "readability" ]
stackoverflow_0000129144_exception_python_readability.txt
Q: Reading 32bit Packed Binary Data On 64bit System I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture)...
Reading 32bit Packed Binary Data On 64bit System
I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way...
[ "Explicitly specify that your data types (e.g. integers) are 32-bit. Otherwise if you have two integers next to each other when you read them they will be read as one 64-bit integer.\nWhen you are dealing with cross-platform issues, the two main things to watch out for are:\n\nBitness. If your packed data is writte...
[ 4, 2, 2, 1, 0 ]
[]
[]
[ "64_bit", "c", "python" ]
stackoverflow_0000135246_64_bit_c_python.txt
Q: Style - When to serialize a Django model Instance: signals vs model's save method I plan to serialize a Django model to XML when it's saved or updated. (The XML's going to be imported into a flash movie). Is it better to listen for a post_save() or pre_save() signal and then perform the serialization, o...
Style - When to serialize a Django model Instance: signals vs model's save method
I plan to serialize a Django model to XML when it's saved or updated. (The XML's going to be imported into a flash movie). Is it better to listen for a post_save() or pre_save() signal and then perform the serialization, or to just handle it in the model's save() methon
[ "If it's core functionality for saving the model you'll want it as part of the save method. However, if you already have a functioning model and you want to extend it for other purposes then signals are your best bet since they allow for properly decoupled modules.\nA good example might be that you want to add even...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000131327_django_python.txt
Q: How do you make Python / PostgreSQL faster? Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: http://gist.github.com/12978. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled ver...
How do you make Python / PostgreSQL faster?
Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: http://gist.github.com/12978. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 second...
[ "Don't waste time profiling. The time is always in the database operations. Do as few as possible. Just the minimum number of inserts.\nThree Things.\nOne. Don't SELECT over and over again to conform the Date, Hostname and Person dimensions. Fetch all the data ONCE into a Python dictionary and use it in memory...
[ 10, 3, 3, 2, 1 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0000136789_postgresql_python.txt
Q: Regex to remove conditional comments I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments. I would also like to avoid using the .*? notation if possible. The text is foo <!--[if IE]> <style type="text/css"> ul.menu ul li{...
Regex to remove conditional comments
I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments. I would also like to avoid using the .*? notation if possible. The text is foo <!--[if IE]> <style type="text/css"> ul.menu ul li{ font-size: 10px; font-weight:norm...
[ ">>> from BeautifulSoup import BeautifulSoup, Comment\n>>> html = '<html><!--[if IE]> bloo blee<![endif]--></html>'\n>>> soup = BeautifulSoup(html)\n>>> comments = soup.findAll(text=lambda text:isinstance(text, Comment) \n and text.find('if') != -1) #This is one line, of course\n>>> [comment.extract()...
[ 5, 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000132488_python_regex.txt
Q: Is there something like Python's getattr() in C#? Is there something like Python's getattr() in C#? I would like to create a window by reading a list which contains the names of controls to put on the window. A: There is also Type.InvokeMember. public static class ReflectionExt { public static object GetAttr...
Is there something like Python's getattr() in C#?
Is there something like Python's getattr() in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.
[ "There is also Type.InvokeMember.\npublic static class ReflectionExt\n{\n public static object GetAttr(this object obj, string name)\n {\n Type type = obj.GetType();\n BindingFlags flags = BindingFlags.Instance | \n BindingFlags.Public | \n ...
[ 13, 5, 1, 0 ]
[]
[]
[ "c#", "python", "user_interface" ]
stackoverflow_0000138045_c#_python_user_interface.txt
Q: Python language API I'm starting with Python coming from java. I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it. I've found very helpul to use help( thing ) from the Python ( command line ) I have found this also: http://doc...
Python language API
I'm starting with Python coming from java. I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it. I've found very helpul to use help( thing ) from the Python ( command line ) I have found this also: http://docs.python.org/2/ https://d...
[ "pydoc?\nI'm not sure if you're looking for something more sophisticated, but it does the trick.\n", "The standard python library is fairly well documented. Try jumping into python and importing a module say \"os\" and running:\nimport os \nhelp(os)\n\nThis reads the doc strings on each of the items in the modu...
[ 5, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "documentation", "python", "python_2.x", "reference" ]
stackoverflow_0000136739_documentation_python_python_2.x_reference.txt
Q: wxpython: How do I examine dragged data in OnDragOver? I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system wheth...
wxpython: How do I examine dragged data in OnDragOver?
I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whate...
[ "One solution, which is a hack of limited usefulness, is when a drag is initiated, store the dragged data in a global or static reference somewhere. This way, in the OnEnter and OnDragOver handlers, it is possible to get a reference to the data being dragged. This is of course only useful for drags within the same ...
[ 1, 1 ]
[]
[]
[ "drag_and_drop", "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0000026706_drag_and_drop_python_user_interface_wxpython_wxwidgets.txt
Q: PyQt - QScrollBar Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks. A: >>> import sys >>> from PyQt4 import QtCore, QtGui >>> app = QtGui.QApplication(sys.argv) >>> sb = QtGui.QScrollBar() >>> sb.setMinimum(0) >>> sb.setMaximum(100) >>> def on_slider_moved(value): print "new sli...
PyQt - QScrollBar
Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks.
[ ">>> import sys\n>>> from PyQt4 import QtCore, QtGui\n>>> app = QtGui.QApplication(sys.argv)\n>>> sb = QtGui.QScrollBar()\n>>> sb.setMinimum(0)\n>>> sb.setMaximum(100)\n>>> def on_slider_moved(value): print \"new slider position: %i\" % (value, )\n>>> sb.connect(sb, QtCore.SIGNAL(\"sliderMoved(int)\"), on_slider_mo...
[ 2, 1, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0000139005_pyqt_python.txt
Q: How do I test a django database schema? I want to write tests that can show whether or not the database is in sync with my models.py file. Actually I have already written them, only to find out that django creates a new database each time the tests are run based on the models.py file. Is there any way I can make ...
How do I test a django database schema?
I want to write tests that can show whether or not the database is in sync with my models.py file. Actually I have already written them, only to find out that django creates a new database each time the tests are run based on the models.py file. Is there any way I can make the models.py test use the existing database ...
[ "What we did was override the default test_runner so that it wouldn't create a new database to test against. This way, it runs the test against whatever our current local database looks like. But be very careful if you use this method because any changes to data you make in your tests will be permanent. I made s...
[ 9 ]
[]
[]
[ "django", "model", "python", "unit_testing" ]
stackoverflow_0000138851_django_model_python_unit_testing.txt
Q: Why results of map() and list comprehension are different? The following test fails: #!/usr/bin/env python def f(*args): """ >>> t = 1, -1 >>> f(*map(lambda i: lambda: i, t)) [1, -1] >>> f(*(lambda: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda: i for i in t]) # -> [-1, -1] [1...
Why results of map() and list comprehension are different?
The following test fails: #!/usr/bin/env python def f(*args): """ >>> t = 1, -1 >>> f(*map(lambda i: lambda: i, t)) [1, -1] >>> f(*(lambda: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda: i for i in t]) # -> [-1, -1] [1, -1] """ alist = [a() for a in args] print(alist) ...
[ "They are different, because the value of i in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in f.\nBy that time, i is bound to the last value if t, which is -1.\nSo basically, this is what the list comprehension does (likewise for the genexp):\n...
[ 9, 6, 4 ]
[]
[]
[ "closures", "generator_expression", "late_binding", "list_comprehension", "python" ]
stackoverflow_0000139819_closures_generator_expression_late_binding_list_comprehension_python.txt
Q: Regular expressions but for writing in the match When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... Right now I'm doing this... def getExpandedText(pattern, text, replaceValue): """ ...
Regular expressions but for writing in the match
When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... Right now I'm doing this... def getExpandedText(pattern, text, replaceValue): """ One liner... really ugly but it's only used in here. ...
[ "sub (replacement, string[, count = 0])\n\nsub returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn't found, string is returned unchanged.\n p = re.compile( '(blue|white|red)')\n >>> p.sub( 'colour', 'blue sock...
[ 7, 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000140182_python_regex.txt
Q: Python reading Oracle path On my desktop I have written a small Pylons app that connects to Oracle. I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit. I was getting errors about loading the OCI dll, so I installed ...
Python reading Oracle path
On my desktop I have written a small Pylons app that connects to Oracle. I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit. I was getting errors about loading the OCI dll, so I installed the 32 bit client into C:\oracle...
[ "sys.path is python's internal representation of the PYTHONPATH, it sounds to me like you want to modify the PATH.\nI'm not sure that this will work, but you can try:\nimport os\nos.environ['PATH'] += os.pathsep + \"C:\\\\oracle32\\\\bin\"\n\n", "You need to append the c:\\Oracle32\\bin directory to the PATH vari...
[ 3, 0, 0 ]
[]
[]
[ "cx_oracle", "oracle", "pylons", "python" ]
stackoverflow_0000095950_cx_oracle_oracle_pylons_python.txt
Q: Using locale.setlocale in embedded Python without breaking file parsing in C thread We're using a third-party middleware product that allows us to write code in an embedded Python interpreter, and which exposes an API that we can call into. Some of these API calls allow us to load various kinds of file, and the lo...
Using locale.setlocale in embedded Python without breaking file parsing in C thread
We're using a third-party middleware product that allows us to write code in an embedded Python interpreter, and which exposes an API that we can call into. Some of these API calls allow us to load various kinds of file, and the loading code is implemented in C. File loading happens in a separate thread, and calls back...
[ "Setting the locale after multiple threads have started operating may have unexpected results. Unless I could figure out a more subtle approach, I'd probably just split file loading and the user interface into separate processes, communicating through a pipe or a file socket.\n" ]
[ 1 ]
[]
[]
[ "internationalization", "locale", "python" ]
stackoverflow_0000140295_internationalization_locale_python.txt
Q: Something like Explorer's icon grid view in a Python GUI I am making a Python gui project that needs to duplicate the look of a Windows gui environment (ie Explorer). I have my own custom icons to draw but they should be selectable by the same methods as usual; click, ctrl-click, drag box etc. Are any of the gui...
Something like Explorer's icon grid view in a Python GUI
I am making a Python gui project that needs to duplicate the look of a Windows gui environment (ie Explorer). I have my own custom icons to draw but they should be selectable by the same methods as usual; click, ctrl-click, drag box etc. Are any of the gui toolkits going to help with this or will I have to implement ...
[ "Python has extensions for accessing the Win32 API, but good luck trying to re-write explorer in that by yourself. Your best bet is to use a toolkit like Qt, but you'll still have to write the vast majority of the application from scratch.\nIs there any way you can re-use explorer itself in your project?\n\nUpdated...
[ 3, 2, 1 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0000145155_python_user_interface.txt
Q: Dynamic radio button creation In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later? For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried ...
Dynamic radio button creation
In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later? For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to...
[ "To make new list elements appear in correct places, you have to re-layout the grid after adding new elements to it. For example, to add a few new items, you could call:\ndef addNewSkills(self, newSkillList):\n '''newSkillList is a list of skill names you want to add'''\n for skillName in newSkillList:\n ...
[ 1, 0, 0 ]
[]
[]
[ "layout", "python", "user_interface", "wxpython" ]
stackoverflow_0000138353_layout_python_user_interface_wxpython.txt
Q: How do I successfully pass a function reference to Django’s reverse() function? I’ve got a brand new Django project. I’ve added one minimal view function to views.py, and one URL pattern to urls.py, passing the view by function reference instead of a string: # urls.py # ------- # coding=utf-8 from django.conf.ur...
How do I successfully pass a function reference to Django’s reverse() function?
I’ve got a brand new Django project. I’ve added one minimal view function to views.py, and one URL pattern to urls.py, passing the view by function reference instead of a string: # urls.py # ------- # coding=utf-8 from django.conf.urls.defaults import * from myapp import views urlpatterns = patterns('', url(r'...
[ "Got it!! The problem is that some of the imports are of myproject.myapp.views, and some are just of myapp.views. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main settings.py probably has a line like:\nROOT_URLCONF = `myproject.u...
[ 11, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000146522_django_python.txt
Q: How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern? In my urls.py file, I have: from myapp import views ... (r'^categories/$', views.categories) Where categories is a view function inside myapp/views.py. No other URLconf lines reference views.categories. In a un...
How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern?
In my urls.py file, I have: from myapp import views ... (r'^categories/$', views.categories) Where categories is a view function inside myapp/views.py. No other URLconf lines reference views.categories. In a unit test file, I’m trying to grab this URL using django.core.urlresolvers.reverse(), instead of just copying '...
[ "Jack M.'s example is nearly correct.\nIt needs to be a url function, not a tuple, if you want to use named urls.\nurl(r'^no_monkeys/$', 'views.noMonkeys', {}, \"no-monkeys\"),\n\n", "After futher investigation, turns out it was an issue with how I was importing the views module:\nHow do I successfully pass a fun...
[ 2, 2, 0 ]
[ "The reverse function actually uses the \"name\" of the URL. This is defined like so:\nurlpatterns = patterns('',\n (r'^no_monkeys/$', 'views.noMonkeys', {}, \"no-monkeys\"),\n (r'^admin/(.*)', admin.site.root),\n)\n\nNow you would call reverse with the string \"no-monkeys\" to get the correct url.\nNinja Ed...
[ -1 ]
[ "django", "python" ]
stackoverflow_0000134629_django_python.txt
Q: I'm using Python regexes in a criminally inefficient manner My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this: This input: The Web Should produce this output: The Web This Is A Test Variable I've got it working. But looking ...
I'm using Python regexes in a criminally inefficient manner
My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this: This input: The Web Should produce this output: The Web This Is A Test Variable I've got it working. But looking at my code, I'm running multiple identical regexes on the same st...
[ "The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled.\nAnother possibility is to use a single regex as below:\nMatchedQuotes = re.compile(r\"(['\\\"])(.*)\\1\", re.LOCALE)\nitem = Matched...
[ 12, 4, 2, 2, 1, 1, 1, 1, 0 ]
[ "Why not use XML and XSLT instead of creating your own template language? What you want to do is pretty easy in XSLT.\n" ]
[ -3 ]
[ "algorithm", "optimization", "python", "regex" ]
stackoverflow_0000146607_algorithm_optimization_python_regex.txt
Q: Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines? I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am ...
Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines?
I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use s=difflib.SequenceMatcher(isjunk,text1,text2) ratio =s.ratio() for this purpose. So, the ques...
[ "If you match all whitespaces the similarity is better:\ndifflib.SequenceMatcher(lambda x: x in \" \\t\\n\", doc1, doc2).ratio()\n\nHowever, difflib is not ideal to such a problem because these are two nearly identical documents, but typos and such produce differences for difflib where a human wouldn't see many.\nT...
[ 7, 2, 2, 1 ]
[]
[]
[ "difflib", "lambda", "python" ]
stackoverflow_0000147437_difflib_lambda_python.txt
Q: Adding Cookie to ZSI Posts I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an una...
Adding Cookie to ZSI Posts
I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fa...
[ "If you read the _Binding class in client.py of ZSI you can see that it has a variable cookies, which is an instance of Cookie.SimpleCookie. Following the ZSI example and the Cookie example that is how it should work:\nb = Binding(url='/cgi-bin/simple-test', tracefile=fp)\nb.cookies['foo'] = 'bar'\n\n", "Addition...
[ 1, 0 ]
[]
[]
[ "cookies", "python", "soappy", "web_services", "zsi" ]
stackoverflow_0000139212_cookies_python_soappy_web_services_zsi.txt
Q: What is the simplest way to offer/consume web services in jython? I have an application for Tomcat which needs to offer/consume web services. Since Java web services are a nightmare (xml, code generation, etc.) compared with what is possible in Python, I would like to learn from your experience using jython instea...
What is the simplest way to offer/consume web services in jython?
I have an application for Tomcat which needs to offer/consume web services. Since Java web services are a nightmare (xml, code generation, etc.) compared with what is possible in Python, I would like to learn from your experience using jython instead of java for offerring/consuming web services. What I have done so far...
[ "I've put together more details on how to use webservices in jython using axis. Read about it here: How To Script Webservices with Jython and Axis.\n", "PyServlet helps you configure Tomcat to serve up Jython scripts from a URL. You could use this is a \"REST-like\" way to do some basic web services without muc...
[ 2, 0 ]
[]
[]
[ "jython", "python", "soap", "web_services", "wsdl" ]
stackoverflow_0000115744_jython_python_soap_web_services_wsdl.txt
Q: Using OR comparisons with IF statements When using IF statements in Python, you have to do the following to make the "cascade" work correctly. if job == "mechanic" or job == "tech": print "awesome" elif job == "tool" or job == "rock": print "dolt" Is there a way to make Python accept multiple valu...
Using OR comparisons with IF statements
When using IF statements in Python, you have to do the following to make the "cascade" work correctly. if job == "mechanic" or job == "tech": print "awesome" elif job == "tool" or job == "rock": print "dolt" Is there a way to make Python accept multiple values when checking for "equals to"? For example...
[ "if job in (\"mechanic\", \"tech\"):\n print \"awesome\"\nelif job in (\"tool\", \"rock\"):\n print \"dolt\"\n\nThe values in parentheses are a tuple. The in operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.\nNote that when Python searches a tuple or list u...
[ 39, 4, 1, 1, 1, 0 ]
[]
[]
[ "boolean", "comparison", "python" ]
stackoverflow_0000148042_boolean_comparison_python.txt
Q: Is there a way to define which fields in the model are editable in the admin app? Assume the following: models.py class Entry(models.Model): title = models.CharField(max_length=50) slug = models.CharField(max_length=50, unique=True) body = models.CharField(max_length=200) admin.py class EntryAdmin(adm...
Is there a way to define which fields in the model are editable in the admin app?
Assume the following: models.py class Entry(models.Model): title = models.CharField(max_length=50) slug = models.CharField(max_length=50, unique=True) body = models.CharField(max_length=200) admin.py class EntryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':('title',)} I want the slug to be pr...
[ "For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not.\nConsider this example:\ndef save(self):\n from django.t...
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000149040_django_python.txt
Q: What is the difference between __reduce__ and __reduce_ex__? I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both? A: The docs say that If provided, at pickling time __reduce__() will be ...
What is the difference between __reduce__ and __reduce_ex__?
I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both?
[ "The docs say that\n\nIf provided, at pickling time\n__reduce__() will be called with no\narguments, and it must return either a\nstring or a tuple.\n\nOn the other hand,\n\nIt is sometimes useful to know the\nprotocol version when implementing\n__reduce__. This can be done by\nimplementing a method named\n__reduce...
[ 34, 9 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0000150284_pickle_python.txt
Q: Python scope: "UnboundLocalError: local variable 'c' referenced before assignment" I am trying to figure out this: c = 1 def f(n): print c + n def g(n): c = c + n f(1) # => 2 g(1) # => UnboundLocalError: local variable 'c' referenced before assignment Thanks! A: Within a function, variables that are a...
Python scope: "UnboundLocalError: local variable 'c' referenced before assignment"
I am trying to figure out this: c = 1 def f(n): print c + n def g(n): c = c + n f(1) # => 2 g(1) # => UnboundLocalError: local variable 'c' referenced before assignment Thanks!
[ "Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global statement:\ndef g(n):\n global c\n c = c + n\n\nThis is one of the quirky areas of Python that has never really sat well with me.\n", "Global state is something to avoi...
[ 52, 12, 9, 2 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0000146359_python_scope.txt
Q: How Does One Read Bytes from File in Python Similar to this question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python. I first read all ten bytes into a string. I then want to parse out the individual pieces of information. I can grab the two ver...
How Does One Read Bytes from File in Python
Similar to this question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python. I first read all ten bytes into a string. I then want to parse out the individual pieces of information. I can grab the two version number chars in the string, but then I have ...
[ "If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:\n>>> s = '\\0\\x02'\n>>> struct.unpack('>H', s)\n(2,)\n\nNote that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.\nFor other sizes of integer, you use diffe...
[ 16, 4, 2, 2 ]
[]
[]
[ "id3", "python" ]
stackoverflow_0000150532_id3_python.txt
Q: Can Regex be used for this particular string manipulation? I need to replace character (say) x with character (say) P in a string, but only if it is contained in a quoted substring. An example makes it clearer: axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k Let's assume, for the sake of simplicity, that quotes a...
Can Regex be used for this particular string manipulation?
I need to replace character (say) x with character (say) P in a string, but only if it is contained in a quoted substring. An example makes it clearer: axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k Let's assume, for the sake of simplicity, that quotes always come in pairs. The obvious way is to just process the str...
[ "I converted Greg Hewgill's python code to C# and it worked!\n[Test]\npublic void ReplaceTextInQuotes()\n{\n Assert.AreEqual(\"axbx'cPdPe'fxgh'iPj'k\", \n Regex.Replace(\"axbx'cxdxe'fxgh'ixj'k\",\n @\"x(?=[^']*'([^']|'[^']*')*$)\", \"P\"));\n}\n\nThat test passed.\n", "I was able to do this with Python:\...
[ 9, 8, 3, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "c#", "language_agnostic", "python", "regex" ]
stackoverflow_0000138552_c#_language_agnostic_python_regex.txt
Q: Is there any Visual Library alternative to wxPython that supports CSS/Style Sheets? I've developed a program that extensively uses wxPython - the wxWindow port for python. Even though it is as mature library it is still very primitive and very programming oriented. Which is time consuming and not flexible at all....
Is there any Visual Library alternative to wxPython that supports CSS/Style Sheets?
I've developed a program that extensively uses wxPython - the wxWindow port for python. Even though it is as mature library it is still very primitive and very programming oriented. Which is time consuming and not flexible at all. I would love to see if there is something like Flex/Action Script where all the visual d...
[ "PyQt with Qt style sheets might be a good fit. Naturally, you'd need to re-write quite a bit of your GUI layer for the toolkit change.\n", "You could try XUL, the language the Firefox GUI uses. It's XML styled with CSS and scripted with Javascript.\nhttp://www.mozilla.org/projects/xul/\nhttp://en.wikipedia.org/...
[ 4, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0000150705_python_wxpython.txt
Q: What exceptions might a Python function raise? Is there any way in Python to determine what exceptions a (built-in) function might raise? For example, the documentation (http://docs.python.org/lib/built-in-funcs.html) for the built-in int(s) says nothing about the fact that it might raise a ValueError if s is not ...
What exceptions might a Python function raise?
Is there any way in Python to determine what exceptions a (built-in) function might raise? For example, the documentation (http://docs.python.org/lib/built-in-funcs.html) for the built-in int(s) says nothing about the fact that it might raise a ValueError if s is not a validly formatted int. This is a duplicate of Doe...
[ "The only way to tell what exceptions something can raise is by looking at the documentation. The fact that the int() documentation doesn't say it may raise ValueError is a bug in the documentation, but easily explained by ValueError being exactly for that purpose, and that being something \"everybody knows\".\nTo ...
[ 8, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0000150743_exception_python.txt
Q: Looking for a regular expression including alphanumeric + "&" and ";" Here's the problem: split=re.compile('\\W*') This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like k&amp;auml;ytt&amp;auml;j&aml;auml;. What should I add to...
Looking for a regular expression including alphanumeric + "&" and ";"
Here's the problem: split=re.compile('\\W*') This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like k&amp;auml;ytt&amp;auml;j&aml;auml;. What should I add to the regex to include the & and ; characters?
[ "I would treat the entities as a unit (since they also can contain numerical character codes), resulting in the following regular expression:\n(\\w|&(#(x[0-9a-fA-F]+|[0-9]+)|[a-z]+);)+\n\nThis matches\n\neither a word character (including “_”), or\nan HTML entity consisting of\n\n\nthe character “&”,\n\n\nthe chara...
[ 6, 5, 2 ]
[ "Looks like this RegEx did the trick:\nsplit=re.compile('(\\\\\\W+&\\\\\\W+;)*')\n\nThanks for the suggestions. Most of them worked fine on Reggy, but I don't quite understand why they failed with re.compile.\n" ]
[ -1 ]
[ "encoding", "python", "regex" ]
stackoverflow_0000152218_encoding_python_regex.txt
Q: NSWindow launched from statusItem menuItem does not appear as active window I have a statusItem application written in PyObjC. The statusItem has a menuItem which is supposed to launch a new window when it is clicked: # Create statusItem statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableSt...
NSWindow launched from statusItem menuItem does not appear as active window
I have a statusItem application written in PyObjC. The statusItem has a menuItem which is supposed to launch a new window when it is clicked: # Create statusItem statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) statusItem.setHighlightMode_(TRUE) statusItem.setEnabled_(TRUE) s...
[ "You need to send the application an activateIgnoringOtherApps: message and then send the window makeKeyAndOrderFront:. \nIn Objective-C this would be:\n[NSApp activateIgnoringOtherApps:YES];\n[[self window] makeKeyAndOrderFront:self];\n\n", "I have no idea of PyObjC, never used that, but if this was Objective-C ...
[ 5, 1 ]
[]
[]
[ "cocoa", "pyobjc", "python" ]
stackoverflow_0000152344_cocoa_pyobjc_python.txt
Q: Is it OK to inspect properties beginning with underscore? I've been working on a very simple crud generator for pylons. I came up with something that inspects SomeClass._sa_class_manager.mapper.c Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though...
Is it OK to inspect properties beginning with underscore?
I've been working on a very simple crud generator for pylons. I came up with something that inspects SomeClass._sa_class_manager.mapper.c Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of...
[ "It is intentional (in Python) that there are no \"private\" scopes. It is a convention that anything that starts with an underscore should not ideally be used, and hence you may not complain if its behavior or definition changes in a next version.\n", "In general, this usually indicates that the method is effect...
[ 9, 9, 0, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0000152068_pylons_python_sqlalchemy.txt
Q: In Django, where is the best place to put short snippets of HTML-formatted data? This question is related to (but perhaps not quite the same as): Does Django have HTML helpers? My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example: I have ...
In Django, where is the best place to put short snippets of HTML-formatted data?
This question is related to (but perhaps not quite the same as): Does Django have HTML helpers? My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example: I have two classes, Person and Address. There are multiple Addresses for each Person, setup l...
[ "Sounds like an inclusion tag is what you're looking for. You could have a template and tag for each major variation and use the tag's arguments to customise the context for each template as required.\nBasic tag definition:\n@register.inclusion_tag('person/address.html')\ndef display_address(address):\n return {...
[ 13, 2, 1 ]
[]
[]
[ "design_patterns", "django", "model_view_controller", "python" ]
stackoverflow_0000146789_design_patterns_django_model_view_controller_python.txt
Q: What is the preferred way to redirect a request in Pylons without losing form data? I'm trying to redirect/forward a Pylons request. The problem with using redirect_to is that form data gets dropped. I need to keep the POST form data intact as well as all request headers. Is there a simple way to do this? A: R...
What is the preferred way to redirect a request in Pylons without losing form data?
I'm trying to redirect/forward a Pylons request. The problem with using redirect_to is that form data gets dropped. I need to keep the POST form data intact as well as all request headers. Is there a simple way to do this?
[ "Receiving data from a POST depends on the web browser sending data along. When the web browser receives a redirect, it does not resend that data along. One solution would be to URL encode the data you want to keep and use that with a GET. In the worst case, you could always add the data you want to keep to the ...
[ 2 ]
[]
[]
[ "header", "post", "pylons", "python", "request" ]
stackoverflow_0000153773_header_post_pylons_python_request.txt
Q: Extension functions and 'help' When I call help(Mod.Cls.f) (Mod is a C extension module), I get the output Help on method_descriptor: f(...) doc_string What do I need to do so that the help output is of the form Help on method f in module Mod: f(x, y, z) doc_string like it is for random.Random.shuffle, ...
Extension functions and 'help'
When I call help(Mod.Cls.f) (Mod is a C extension module), I get the output Help on method_descriptor: f(...) doc_string What do I need to do so that the help output is of the form Help on method f in module Mod: f(x, y, z) doc_string like it is for random.Random.shuffle, for example? My PyMethodDef entry is...
[ "You cannot. The inspect module, which is what 'pydoc' and 'help()' use, has no way of figuring out what the exact signature of a C function is. The best you can do is what the builtin functions do: include the signature in the first line of the docstring:\n>>> help(range)\nHelp on built-in function range in module...
[ 2, 1 ]
[]
[]
[ "cpython", "python" ]
stackoverflow_0000153227_cpython_python.txt
Q: Running a Python web server as a service in Windows I have a small web server application I've written in Python that goes and gets some data from a database system and returns it to the user as XML. That part works fine - I can run the Python web server application from the command line and I can have clients con...
Running a Python web server as a service in Windows
I have a small web server application I've written in Python that goes and gets some data from a database system and returns it to the user as XML. That part works fine - I can run the Python web server application from the command line and I can have clients connect to it and get data back. At the moment, to run the w...
[ "This is what I do:\nInstead of instancing directly the class BaseHTTPServer.HTTPServer, I write a new descendant from it that publishes an \"stop\" method:\nclass AppHTTPServer (SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):\n def serve_forever(self):\n self.stop_serving = False\n while ...
[ 4 ]
[]
[]
[ "python", "webserver", "windows" ]
stackoverflow_0000153221_python_webserver_windows.txt
Q: Python GUI Application redistribution I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints. What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working...
Python GUI Application redistribution
I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints. What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't ha...
[ "This may help:\nHow can I make an EXE file from a Python program?\n", "http://wiki.wxpython.org/CreatingStandaloneExecutables\nIt shouldn't be that large unless you have managed to include the debug build of wx.\nI seem to rememebr about 4Mb for the python.dll and similair for wx.\n", "Python has an embedded G...
[ 6, 6, 2, 1, 1, 0, 0 ]
[]
[]
[ "distribution", "freeze", "python", "user_interface", "wxpython" ]
stackoverflow_0000153956_distribution_freeze_python_user_interface_wxpython.txt
Q: Programmatically focusing a hippo.CanvasEntry? Consider this Python program which uses PyGtk and Hippo Canvas to display a clickable text label. Clicking the text label replaces it with a Hippo CanvasEntry widget which contains the text of the label. import pygtk pygtk.require('2.0') import gtk, hippo def textCl...
Programmatically focusing a hippo.CanvasEntry?
Consider this Python program which uses PyGtk and Hippo Canvas to display a clickable text label. Clicking the text label replaces it with a Hippo CanvasEntry widget which contains the text of the label. import pygtk pygtk.require('2.0') import gtk, hippo def textClicked(text, event, row): input = hippo.CanvasEnt...
[ "Underneath the CanvasEntry, there's a regular old gtk.Entry which you need to request the focus as soon as it's made visible. Here's a modified version of your textClicked function which does just that:\ndef textClicked(text, event, row):\n input = hippo.CanvasEntry()\n input.set_property('text', text.get_p...
[ 2 ]
[]
[]
[ "focus", "pygtk", "python" ]
stackoverflow_0000155822_focus_pygtk_python.txt
Q: .order_by() isn't working how it should / how I expect it to In my Django project I am using Product.objects.all().order_by('order') in a view, but it doesn't seem to be working properly. This is it's output: Product Name Sort ...
.order_by() isn't working how it should / how I expect it to
In my Django project I am using Product.objects.all().order_by('order') in a view, but it doesn't seem to be working properly. This is it's output: Product Name Sort Evolution 2 ...
[ "Your saving loop is wrong. You save Product outside of the loop. It should be:\nif request.method == 'POST':\n PostEntries = len(request.POST)\n x = 1 \n while x < PostEntries:\n p = Product.objects.get(pk=x)\n p.order = int(request.POST.get(str(x),''))\n print \...
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000156951_django_python.txt
Q: How can i parse a comma delimited string into a list (caveat)? I need to be able to take a string like: '''foo, bar, "one, two", three four''' into: ['foo', 'bar', 'one, two', 'three four'] I have an feeling (with hints from #python) that the solution is going to involve the shlex module. A: It depends how com...
How can i parse a comma delimited string into a list (caveat)?
I need to be able to take a string like: '''foo, bar, "one, two", three four''' into: ['foo', 'bar', 'one, two', 'three four'] I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
[ "It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes?\nYour syntax looks very much like the common CSV file format, which is supported by the Python standard library:\nimport csv\nreader = csv.reader(['''foo, bar, \"one, two\", three four'''], ...
[ 42, 27, 5, 1, 0 ]
[ "If it doesn't need to be pretty, this might get you on your way:\ndef f(s, splitifeven):\n if splitifeven & 1:\n return [s]\n return [x.strip() for x in s.split(\",\") if x.strip() != '']\n\nss = 'foo, bar, \"one, two\", three four'\n\nprint sum([f(s, sie) for sie, s in enumerate(ss.split('\"'))], [])...
[ -2 ]
[ "escaping", "python", "quotes", "split" ]
stackoverflow_0000118096_escaping_python_quotes_split.txt
Q: Python module dependency Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CPerson list of every one in the room. The...
Python module dependency
Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CPerson list of every one in the room. The CPerson class however sometim...
[ "No need to import CRoom\nYou don't use CRoom in person.py, so don't import it. Due to dynamic binding, Python doesn't need to \"see all class definitions at compile time\".\nIf you actually do use CRoom in person.py, then change from room import CRoom to import room and use module-qualified form room.CRoom. See Ef...
[ 22, 7, 4, 1, 0 ]
[]
[]
[ "circular_dependency", "module", "python" ]
stackoverflow_0000158268_circular_dependency_module_python.txt