prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
is there any difference between foo is none and foo none is there any difference between if foo is none pass and if foo none pass the convention that have seen in most python code and the code myself write is the former but recently came across code which uses the latter none is an instance and the only instance iirc o...
for none there should not be difference between equality and identity is the nonetype probably returns identity for equality since none is the only instance you can make of nonetype think this is true the two operations are the same in the case of other types this is not always the case for example list list if list li...
QA
wxpython how do examine dragged data in ondragover am 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 couple of callbacks onenter and ondragover that purportedly allow me to inform the system whether the current mous...
one solution which is hack of limited usefulness is when drag is initiated store the dragged data in global or static reference somewhere this way in the onenter and ondragover handlers it is possible to get reference to the data being dragged this is of course only useful for drags within the same application the same...
QA
what is the best way to grab parse command line arguments passed to python script what is the easiest tersest and most flexible method or library for parsing python command line arguments
this answer suggests optparse which is appropriate for older python versions for python and above argparse replaces optparse see this answer for more information as other people pointed out you are better off going with optparse over getopt getopt is pretty much one to one mapping of the standard getopt library functio...
QA
find broken symlinks with python if call os stat on broken symlink python throws an oserror exception this makes it useful for finding them however there are few other reasons that os stat might throw similar exception is there more precise way of detecting broken symlinks with python under linux
common python saying is that it is easier to ask forgiveness than permission while am not fan of this statement in real life it does apply in lot of cases usually you want to avoid code that chains two system calls on the same file because you never know what will happen to the file in between your two calls in your co...
QA
is there any difference between foo is none and foo none is there any difference between if foo is none pass and if foo none pass the convention that have seen in most python code and the code myself write is the former but recently came across code which uses the latter none is an instance and the only instance iirc o...
jason recommend using something more along the lines of if foo foo is not none else foo is none do not like using if foo unless foo truly represents boolean value or if foo is string or an object or something else if foo may work but it looks like lazy shortcut to me if you are checking to see if is none say if is none
QA
where can learn more about pypy translation function have been having hard time trying to understand pypy translation it looks like something absolutely revolutionary from simply reading the description however am hard pressed to find good documentation on actually translating real world piece of code to something such...
are you looking for python specific translation or just the general how do you compile some code to bytecode if the latter is your case check the llvm tutorial especially find chapter two which teaches you to write compiler for your own language interesting
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very s...
if you want to share common functionality between pages suggest you look at custom tags they are quite easy to create and are very powerful also templates can extend from other templates this allows you to have base template to set up the layout of the page and to share this between other templates which fill in the bl...
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very s...
you can always create class override the call function and then point the url file to an instance of the class you can take look at the formwizard class to see how this is done
QA
how to use xpath in python what is the library is there full implementation how is the library used where is its website
libxml has number of advantages compliance to the spec active development and community participation speed this is really python wrapper around implementation ubiquity the libxml library is pervasive and thus well tested downsides include compliance to the spec it is strict things like default namespace handling are e...
QA
is there any difference between foo is none and foo none is there any difference between if foo is none pass and if foo none pass the convention that have seen in most python code and the code myself write is the former but recently came across code which uses the latter none is an instance and the only instance iirc o...
word of caution if foo do something is not exactly the same as if is not none do something the former is boolean value test and can evaluate to false in different contexts there are number of things that represent false in boolean value tests for example empty containers boolean values none also evaluates to false in t...
QA
does php have an equivalent to this type of python string substitution python has this wonderful way of handling string substitutions using dictionaries the site site adj because it adj site stackoverflow adj rocks the stackoverflow site rocks because it rocks love this because you can specify value once in the diction...
some of the user contributed notes and functions in php documentation for sprintf come quite close note search the page for sprintf
QA
does php have an equivalent to this type of python string substitution python has this wonderful way of handling string substitutions using dictionaries the site site adj because it adj site stackoverflow adj rocks the stackoverflow site rocks because it rocks love this because you can specify value once in the diction...
function subst str dict return preg replace array map create function return array keys dict array values dict str you call it like so echo subst the site site adj because it adj array site stackoverflow adj rocks
QA
does php have an equivalent to this type of python string substitution python has this wonderful way of handling string substitutions using dictionaries the site site adj because it adj site stackoverflow adj rocks the stackoverflow site rocks because it rocks love this because you can specify value once in the diction...
marius do not know if it is faster but you can do it without regexes function subst str dict foreach dict as key value str str replace key value str return str
QA
how to check what os am running on in python what do need to look at to see if am on windows unix etc
you can also use sys platform if you already have imported sys and you do not want to import another module import sys sys platform linux
QA
is safe eval really safe am looking for safe eval function to implement spreadsheet like calculations using numpy scipy the functionality to do this the rexec module has been removed from python since due to apparently unfixable security problems there are several third party hacks out there that purport to do this the...
writing your own parser could be fun it might be better option because people are expecting to use the familiar spreadsheet syntax excel etc and not python when they are entering formulas am not familiar with safe eval but would imagine that anything like this certainly has the potential for exploitation
QA
prototyping with python code before compiling have been mulling over writing peak fitting library for while know python fairly well and plan on implementing everything in python to begin with but envisage that may have to re implement some core routines in compiled language eventually iirc one of python original remits...
have not used swig or sip but find writing python wrappers with boost python to be very powerful and relatively easy to use am not clear on what your requirements are for passing types between and python but you can do that easily by either exposing type to python or by using generic boost python object argument to you...
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
maybe it is not terribly idiomatic but would be inclined to go with next while end do something with next but that is because find that sort of thing easy to read
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
what are you trying to do here if you are iterating over list you can use for in where is the element and is the list if you are filtering list you can use list comprehensions for in if to get all the even numbers in list
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
it depends bit what you want to do to match your example as far as possible would make next generator and iterate over it def next for num in range yield num for in next print
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
if you need to do this more than once the pythonic way would use an iterator for in iternext do something with where iternext would be defined using something like explicit is better than implicit def iternext next while end yield next
QA
best way to extract data from filemaker pro database in script my job would be easier or at least less tedious if could come up with an automated way preferably in python script to extract useful information from filemaker pro database am working on linux machine and the filemaker database is on the same lan running on...
it has been really long time since did anything with filemaker pro but know that it does have capabilities for an odbc and jdbc connection to be made to it however do not know how or if that translates to the linux perl python world though this article shows how to share expose your filemaker data via odbc jdbc sharing...
QA
accessing mp meta data with python what is the best way to retrieve mp metadata in python have seen couple frameworks out there but am unsure as to which would be the best to use any ideas
if you can use ironpython there is taglibsharp it can be used from any net language
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
short answer there is no way to do inline variable assignment in while loop in python meaning that cannot say while next do something here since that is not possible there are number of idiomatically correct ways of doing this while next if end blah else break obviously this is kind of ugly you can also use one of the ...
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
can you provide more information about what you are trying to accomplish it is not clear to me why you cannot just say for in everything and have the everything function return everything instead of writing next function to just return one thing at time generators can even do this quite efficiently
QA
pygame within pygtk application what is the best way to use pygame sdl within pygtk application am searching for method that allows me to have drawing area in the gtk window and at the same time being able to manage both gtk and sdl events
have never attempted it myself but hearing plenty about other people who have tried it is not road you want to go down there is the alternative of putting the gui in pygame itself there are plenty of gui toolkits built specifically for pygame that you could use most of them are rather unfinished but there are big activ...
QA
how to capture python interpreter and or cmd exe output from python script is it possible to capture python interpreter output from python script is it possible to capture windows cmd output from python script if so which librar ies should look into
actually you definitely can and it is beautiful ugly and crazy at the same time you can replace sys stdout and sys stderr with stringio objects that collect the output here is an example save it as evil py import sys import stringio stringio stringio sys stdout print hey this is not going to stdout at all print where i...
QA
how do create an xml document in python here is my sample code from xml dom minidom import def make xml doc document node doc createelement foo node innertext bar doc appendchild node return doc if name main make xml writexml sys stdout when run the above code get this xml version foo would like to get xml version foo ...
setting an attribute on an object will not give compile time or run time error it will just do nothing useful if the object does not access it node nosuchattr bar would also not give an error unless you need specific feature of minidom would look at elementtree import sys from xml etree celementtree import element elem...
QA
how do create an xml document in python here is my sample code from xml dom minidom import def make xml doc document node doc createelement foo node innertext bar doc appendchild node return doc if name main make xml writexml sys stdout when run the above code get this xml version foo would like to get xml version foo ...
daniel thanks for the reply also figured out how to do it with the minidom am not sure of the difference between the elementtree vs the minidom from xml dom minidom import def make xml doc document node doc createelement foo node appendchild doc createtextnode bar doc appendchild node return doc if name main make xml w...
QA
how do create an xml document in python here is my sample code from xml dom minidom import def make xml doc document node doc createelement foo node innertext bar doc appendchild node return doc if name main make xml writexml sys stdout when run the above code get this xml version foo would like to get xml version foo ...
found pretty verbose tutorial on the minidom method here is tutorial for the etree method it is much nicer to read and seems quite simple it also goes over parsing of xml briefly
QA
is safe eval really safe am looking for safe eval function to implement spreadsheet like calculations using numpy scipy the functionality to do this the rexec module has been removed from python since due to apparently unfixable security problems there are several third party hacks out there that purport to do this the...
although that code looks quite secure have always held the opinion that any sufficiently motivated person could break it given adequate time do think it will take quite bit of determination to get through that but am relatively sure it could be done
QA
python distutils does anyone know how to use it wrote quick program in python to add gtk gui to cli program was wondering how can create an installer using distutils since it is just gui frontend for command line app it only works in nix anyway so am not worried about it being cross platform my main goal is to create d...
see the distutils simple example that is basically what it is like except real install scripts usually contain bit more information have not seen any that are fundamentally more complicated though in essence you just give it list of what needs to be installed sometimes you need to give it some mapping dicts since the s...
QA
what refactoring tools do you use for python have bunch of classes want to rename some of them have names that are small and that name is reused in other class names where do not want that name changed most of this lives in python code but we also have some xml code that references class names simple search and replace...
in the meantime have tried it two tools that have some sort of integration with vim the first is rope python refactoring library that comes with vim and emacs plug in tried it for few renames and that definitely worked as expected it allowed me to preview the refactoring as different which is nice it is bit text driven...
QA
python distutils does anyone know how to use it wrote quick program in python to add gtk gui to cli program was wondering how can create an installer using distutils since it is just gui frontend for command line app it only works in nix anyway so am not worried about it being cross platform my main goal is to create d...
most python programs will use distutils django is one see http code djangoproject com svn django trunk setup py you should also read the documentation as it is very comprehensive and has some good examples
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to...
not sure entirely understand your question but cannot you simply build and install bit version and then create symbolic links so that library python and below point to your freshly built version of python
QA
what is the best way to grab parse command line arguments passed to python script what is the easiest tersest and most flexible method or library for parsing python command line arguments
think the best way for larger projects is optparse but if you are looking for an easy way maybe http werkzeug pocoo org documentation script is something for you from werkzeug import script actions go here def action foo name action foo does foo pass def action bar id title default title action bar does bar pass if nam...
QA
using in to match an attribute of python objects in an array do not remember whether was dreaming or not but seem to recall there being function which allowed something like foo in iter attr array of python objects attribute name have looked over the docs but this kind of thing does not fall under any obvious listed he...
you could always write one yourself def iterattr iterator attributename for obj in iterator yield getattr obj attributename will work with anything that iterates be it tuple list or whatever love python it makes stuff like this very simple and no more of hassle than neccessary and in use stuff like this is hugely elega...
QA
using in to match an attribute of python objects in an array do not remember whether was dreaming or not but seem to recall there being function which allowed something like foo in iter attr array of python objects attribute name have looked over the docs but this kind of thing does not fall under any obvious listed he...
if you plan on searching anything of remotely decent size your best bet is going to be to use dictionary or set otherwise you basically have to iterate through every element of the iterator until you get to the one you want if this is not necessarily performance sensitive code then the list comprehension way should wor...
QA
python distutils does anyone know how to use it wrote quick program in python to add gtk gui to cli program was wondering how can create an installer using distutils since it is just gui frontend for command line app it only works in nix anyway so am not worried about it being cross platform my main goal is to create d...
distutils really is not all that difficult once you get the hang of it it is really just matter of putting in some meta information program name author version etc and then selecting what files you want to include for example here is sample distutils setup py module from decently complex python library kamaelia setup p...
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to...
essentially yes was not sure you could do it like that current version does not do it like that when using the python install script however there is no option that can find to specify where to put directories and files eg prefix was hoping to match the current layout of python related files so as to avoid polluting my...
QA
how do threads work in python and what are common python threading specific pitfalls have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate may just be missing link or something but it seems like the official documentation is not very thorough on t...
below is basic threading sample it will spawn threads each thread will output its thread number run it and observe the order in which they print import threading class foo threading thread def init self self threading thread init self def run self print str self for in xrange foo start as you have hinted at python thre...
QA
how do threads work in python and what are common python threading specific pitfalls have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate may just be missing link or something but it seems like the official documentation is not very thorough on t...
python fairly easy language to thread in but there are caveats the biggest thing you need to know about is the global interpreter lock this allows only one thread to access the interpreter this means two things you rarely ever find yourself using lock statement in python and if you want to take advantage of multi proce...
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to...
personally would not worry about it until you see problem messing with the default python install on nix system can cause more trouble than it is worth can say from personal experience that you never truly understand what python has done for the nix world until you have problem with it you can also add second python in...
QA
how do threads work in python and what are common python threading specific pitfalls have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate may just be missing link or something but it seems like the official documentation is not very thorough on t...
yes because of the global interpreter lock gil there can only run one thread at time here are some links with some insights about this http www artima com weblogs viewpost jsp thread http smoothspan wordpress com guido is right to leave the gil in python not for multicore but for utility computing from the last link an...
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to...
the short answer is because can the long answer expanding on what the op said is to be more compatible with apache and mysql postgresql they are all bit apache is fat binary with ppc ppc and and the others just straight bit mysqldb and mod python will not compile unless they are all running the same architecture yes co...
QA
how do threads work in python and what are common python threading specific pitfalls have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate may just be missing link or something but it seems like the official documentation is not very thorough on t...
use threads in python if the individual workers are doing bound operations if you are trying to scale across multiple cores on machine either find good ipc framework for python or pick different language
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to...
hyposaurus it is possible to have multiple versions of python installed simultaneously installing two versions in parallel solves your problem and helps avoid the problems laid out by jason baker above the easiest way and the way recommend is to use macports which will install all its software separately by default for...
QA
how can create directly executable cross platform gui app using python python works on multiple platforms and can be used for desktop and web applications thus conclude that there is some way to compile it into an executable for mac windows and linux the problem being have no idea where to start or how to write gui wit...
another system not mentioned in the accepted answer yet is pyinstaller which worked for pyqt project of mine when py exe would not found it easier to use http www pyinstaller org pyinstaller is based on gordon mcmillan python installer which is no longer available
QA
what is the best way to use web services in python have medium sized application that runs as net web service which do not control and want to create loose pythonic api above it to enable easy scripting wanted to know what is the best most practical solution for using web services in python edit need to consume complex...
if have to expose apis prefer doing it as json python has excellent support for json objects json objects are infact python dictionaries
QA
pygame within pygtk application what is the best way to use pygame sdl within pygtk application am searching for method that allows me to have drawing area in the gtk window and at the same time being able to manage both gtk and sdl events
pygame works much better when it can manage its own window or even better use the whole screen gtk has flexible enough widgets to allow creation of drawing area this page may help though if you want to try it
QA
is safe eval really safe am looking for safe eval function to implement spreadsheet like calculations using numpy scipy the functionality to do this the rexec module has been removed from python since due to apparently unfixable security problems there are several third party hacks out there that purport to do this the...
daniel jinja implements sandboxe environment that may or may not be useful to you from what remember it does not yet comprehend list comprehensions sanbox info
QA
is safe eval really safe am looking for safe eval function to implement spreadsheet like calculations using numpy scipy the functionality to do this the rexec module has been removed from python since due to apparently unfixable security problems there are several third party hacks out there that purport to do this the...
depends on your definition of safe suppose lot of the security depends on what you pass in and what you are allowed to pass in the context for instance if file is passed in can open arbitrary files names open foo safe eval safe eval baz type baz names names baz open file baz mode at da furthermore the environment is ve...
QA
how can render tree structure recursive using django template have tree structure in memory that would like to render in html using django template class node name node name children there will be some object root that is node and children is list of nodes root will be passed in the content of the template have found t...
think the canonical answer is do not what you should probably do instead is unravel the thing in your view code so it is just matter of iterating over in de dents in the template think would do it by appending indents and dedents to list while recursing through the tree and then sending that travelogue list to the temp...
QA
programmatically editing python source this is something that think would be very useful basically would like there to be way to edit python source programmatically without requiring human intervention there are couple of things would like to do with this edit the configuration of python apps that use source modules fo...
python standard library provides pretty good facilities for working with python source note the tokenize and parser modules
QA
is it possible to run python script as service in windows if possible how am sketching the architecture for set of programs that share various interrelated objects stored in database want one of the programs to act as service which provides higher level interface for operations on these objects and the other programs t...
yes you can do it using the pythoncom libraries that come included with activepython or can be installed with pywin python for windows extensions this is basic skeleton for simple service import win serviceutil import win service import win event import servicemanager import socket class appserversvc win serviceutil se...
QA
how can render tree structure recursive using django template have tree structure in memory that would like to render in html using django template class node name node name children there will be some object root that is node and children is list of nodes root will be passed in the content of the template have found t...
this might be way more than you need but there is django module called mptt this stores hierarchical tree structure in an sql database and includes templates for display in the view code you might be able to find something useful there here is the link django mptt
QA
how to generate dynamic parametrized unit tests in python have some kind of test data and want to create an unit test for each item my first idea was to do it like this import unittest foo bar lee class testsequence unittest testcase def testsample self for name in print test name self assertequal if name main unittest...
use something like this import unittest foo bar lee class testsequense unittest testcase pass def test generator def test self self assertequal return test if name main for in test name test test test generator setattr testsequense test name test unittest main the nose parameterized package can be used to automate this...
QA
programmatically editing python source this is something that think would be very useful basically would like there to be way to edit python source programmatically without requiring human intervention there are couple of things would like to do with this edit the configuration of python apps that use source modules fo...
had the same issue and simply opened the file and did some replace then reload the file in the python interpreter this works fine and is easy to do otherwise afaik you have to use some conf objects
QA
ssh hangs when command invoked directly but exits cleanly when run interactive need to launch server on the remote machine and retrieve the port number that the server process is lsitening on when invoked the server will listen on random port and output the port number on stderr want to automate the process of logging ...
stderr readline suspect it is the above line when you invoke command directly through ssh you do not get your full pty assuming linux and thus no stderr to read from when you log in interactively stdin stdout and stderr are set up for you and so your script works
QA
extending base classes in python am trying to extend some base classes in python class xlist list def len self return len self def add self args self extend args return none class xint int def add self value self value return self xlist print len ok print ok add print ok xint print ok add print not ok print type class ...
ints are immutable and you cannot modify them in place so you should go with option because option is impossible without some trickery
QA
extending base classes in python am trying to extend some base classes in python class xlist list def len self return len self def add self args self extend args return none class xint int def add self value self value return self xlist print len ok print ok add print ok xint print ok add print not ok print type class ...
int is value type so each time you do an assignment both instances of above it does not modify the object you have on the heap but replaces the reference with one of the result of the right hand side of the assignment an int list is not value type so it is not bound by the same rules this page has more details on the d...
QA
extending base classes in python am trying to extend some base classes in python class xlist list def len self return len self def add self args self extend args return none class xint int def add self value self value return self xlist print len ok print ok add print ok xint print ok add print not ok print type class ...
your two xint examples do not work for two different reasons the first does not work because self value is equivalent to self self value which just reassigns the local variable self to different object an integer but does not change the original object you cannot really get this xint add to work with subclass of int si...
QA
ssh hangs when command invoked directly but exits cleanly when run interactive need to launch server on the remote machine and retrieve the port number that the server process is lsitening on when invoked the server will listen on random port and output the port number on stderr want to automate the process of logging ...
what if you do the following ssh remote host your command your regexp using awk or something for example ssh remote host your program ps aux awk root print this will connect to execute and then print each psid for any user root or any process with root in its description have used this method for running all kinds of c...
QA
ssh hangs when command invoked directly but exits cleanly when run interactive need to launch server on the remote machine and retrieve the port number that the server process is lsitening on when invoked the server will listen on random port and output the port number on stderr want to automate the process of logging ...
ben collins think you are right about stderr being an issue am pretty sure it is blocking on the readline call in the end gave up and decided to use the pxssh module from pexpect to automate my interaction with an ssh session misha unfortunately the semi colon trick does not work here it blocks on executing my program
QA
specifying mysql enum in django model how do go about specifying and using an enum in django model
using the choices parameter will not use the enum db type it will just create varchar or integer depending on whether you use choices with charfield or integerfield generally this is just fine if it is important to you that the enum type is used at the database level you have three options use manage py sql appname to ...
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very s...
have created and used my own generic view classes defining call so an instance of the class is callable really like it while django generic views allow some customization through keyword arguments oo generic views if their behavior is split into number of separate methods can have much more fine grained customization v...
QA
find out how much memory is being used by an object in python how would you go about finding out how much memory is being used by an object know it is possible to find out how much is used by block of code but not by an instantiated object anytime during its life which is what want
have not any personal experience with either of the following but simple search for python memory profiler yield pysizer memory profiler for python found at http pysizer org however the page seems to indicate that the project has not been updated for while and refers to heapy support ing debugging and optimization rega...
QA
are python threads buggy reliable coder friend told me that python current multi threading implementation is seriously buggy enough to avoid using altogether what can said about this rumor
as far as know there are no real bugs but the performance when threading in cpython is really bad compared to most other threading implementations but usually good enough if all most of the threads do is block due to the gil global interpreter lock so really it is implementation specific rather than language specific j...
QA
are python threads buggy reliable coder friend told me that python current multi threading implementation is seriously buggy enough to avoid using altogether what can said about this rumor
python threads are good for concurrent programming threads are swapped out of the cpu as soon as they block waiting for input from file network etc this allows other python threads to use the cpu while others wait this would allow you to write multi threaded web server or web crawler for example however python threads ...
QA
are python threads buggy reliable coder friend told me that python current multi threading implementation is seriously buggy enough to avoid using altogether what can said about this rumor
the gil global interpreter lock might be problem but the api is quite ok try out the excellent processing module which implements the threading api for separate processes am using that right now albeit on os have yet to do some testing on windows and am really impressed the queue class is really saving my bacon in term...
QA
how to generate dynamic parametrized unit tests in python have some kind of test data and want to create an unit test for each item my first idea was to do it like this import unittest foo bar lee class testsequence unittest testcase def testsample self for name in print test name self assertequal if name main unittest...
the nose testing framework supports this example the code below is the entire contents of the file containing the test param list def test generator for params in param list yield check em params params def check em assert the output of the nosetests command nosetests testgen test generator ok testgen test generator fa...
QA
how to specify an authenticated proxy for python http connection what is the best way to specify proxy with username and password for an http connection in python
this works for me import urllib proxy urllib proxyhandler http http username password proxyurl proxyport auth urllib httpbasicauthhandler opener urllib build opener proxy auth urllib httphandler urllib install opener opener conn urllib urlopen http python org return str conn read
QA
python descriptor protocol analog in other languages is there something like the python descriptor protocol implemented in other languages it seems like nice way to increase modularity encapsulation without bloating your containing class implementation but have never heard of similar thing in any other languages is it ...
have not heard of direct equivalent either you could probably achieve the same effect with macros especially in language like lisp which has extremely powerful macros would not be at all surprised if other languages start to incorporate something similar because it is so powerful
QA
how do make windows aware of service have written in python in another question posted yesterday got very good advice on how python script could be run as service in windows what am left wondering is how is windows aware of the services that can be managed in the native tools services window in administrative tools wha...
here is code to install python script as service written in python http code activestate com recipes this post could also help you out http essiene blogspot com python windows services html
QA
django imagefield core false in newforms admin in the transition to newforms admin am having difficulty figuring out how specify core false for imagefields get the following error typeerror init got an unexpected keyword argument core edit however by just removing the core argument get this field is required error in t...
this is simple started getting this problems few revisions ago basically just remove the core true parameter in the imagefield in the models and then follow the instructions here to convert to what the newforms admin uses
QA
how do make windows aware of service have written in python in another question posted yesterday got very good advice on how python script could be run as service in windows what am left wondering is how is windows aware of the services that can be managed in the native tools services window in administrative tools wha...
as with most aware things in windows the answer is registry take look at this microsoft knowledge base article http support microsoft com kb search for win program that can be started by the service controller and that obeys the service control protocol this is the kind of service you are interested in the service regi...
QA
how do make windows aware of service have written in python in another question posted yesterday got very good advice on how python script could be run as service in windows what am left wondering is how is windows aware of the services that can be managed in the native tools services window in administrative tools wha...
you can use srvany exe from windows nt resource kit to create user defined service that will show up in the admin tools http support microsoft com kb am using this method to run tracd python script server for trac here are some very clear instructions http www tacktech com display cfm ttid it does require some registry...
QA
finding what methods an object has given python object of any kind is there an easy way to get list of all methods that this object has or if this is not possible is there at least an easy way to check if it has particular method other than simply checking if an error occurs when the method is called
it appears you can use this code replacing object with the object you are interested in method for method in dir object if callable getattr object method discovered it at this site hopefully that should provide some further detail
QA
finding what methods an object has given python object of any kind is there an easy way to get list of all methods that this object has or if this is not possible is there at least an easy way to check if it has particular method other than simply checking if an error occurs when the method is called
you can use the built in dir function to get list of all the attributes module has try this at the command line to see how it works import modulename dir modulename also you can use the hasattr module name attr name function to find out if module has specific attribute see the guide to python introspection for more inf...
QA
finding what methods an object has given python object of any kind is there an easy way to get list of all methods that this object has or if this is not possible is there at least an easy way to check if it has particular method other than simply checking if an error occurs when the method is called
to check if it has particular method hasattr object method
QA
finding what methods an object has given python object of any kind is there an easy way to get list of all methods that this object has or if this is not possible is there at least an easy way to check if it has particular method other than simply checking if an error occurs when the method is called
on top of the more direct answers would be remiss if did not mention ipython hit tab to see the available methods with autocompletion and once you have found method try help object method to see the pydocs method signature etc ahh repl
QA
python sound bell would like to have python program alert me when it has completed its task by making beep noise currently use import os and then use command line speech program to say process complete much rather it be simple bell know that there is function that can be used in cocoa apps nsbeep but do not think that ...
if you have pyobjc the python objective bridge installed or are running on os system python which ships with pyobjc you can do from appkit import nsbeep nsbeep to play the system alert
QA
are python threads buggy reliable coder friend told me that python current multi threading implementation is seriously buggy enough to avoid using altogether what can said about this rumor
the standard implementation of python generally known as cpython as it is written in uses os threads but since there is the global interpreter lock only one thread at time is allowed to run python code but within those limitations the threading libraries are robust and widely used if you want to be able to use multiple...
QA
django imagefield core false in newforms admin in the transition to newforms admin am having difficulty figuring out how specify core false for imagefields get the following error typeerror init got an unexpected keyword argument core edit however by just removing the core argument get this field is required error in t...
the core attribute is not used anymore from brian rosner blog you can safely just remove any and all core arguments they are no longer used newforms admin now provides nice delete checkbox for exisiting instances in inlines
QA
scaffolding in pylons is there anything similar to rails scaffolding fo pylons have been poking around google but fofund only this thing caled dbsprockets which is fine although probably way to much for my needs what really need is basic crud thas is based on the sqlalchemy model
hear you have followed the pylons mailing list for while looking for something similar there have been some attempts in the past see adminpylon and restin but none have really kept up with sqlalchemy rapidly developing orm api since dbsprockets is likely to be incorporated into turbogears it will likely be maintained w...
QA
python super class reflection if have python code class pass class pass class pass and have class is there way to iterate through it is super classed and something like pseudocode magicgetsuperclasses type type one solution seems to be inspect module and getclasstree function def magicgetsuperclasses cls return for in ...
john your snippet does not work you are returning the class of the base classes which are also known as metaclasses you really just want cls bases class pass class pass class pass instance assert bases works assert class bases works def magicgetsuperclasses clz return tuple base class for base in clz bases assert magic...
QA
how to specify an authenticated proxy for python http connection what is the best way to specify proxy with username and password for an http connection in python
the best way of going through proxy that requires authentication is using urllib to build custom url opener then using that to make all the requests you want to go through the proxy note in particular you probably do not want to embed the proxy password in the url or the python source code unless it is just quick hack ...
QA
validate html in python what is the best way to go about validating that document follows some version of html prefereably that can specify would like to be able to know where the failures occur as in web based validator except in native python app
xhtml is easy use lxml html is harder since there is traditionally not been as much interest in validation among the html crowd run stackoverflow itself through validator yikes the easiest solution would be to execute external applications such as nsgmls or openjade and then parse their output
QA
validate html in python what is the best way to go about validating that document follows some version of html prefereably that can specify would like to be able to know where the failures occur as in web based validator except in native python app
think that html tidy will do what you want there is python binding for it
QA
validate html in python what is the best way to go about validating that document follows some version of html prefereably that can specify would like to be able to know where the failures occur as in web based validator except in native python app
try tidylib you can get some really basic bindings as part of the elementtidy module builds elementtrees from html documents http effbot org downloads elementtidy import elementtidy xhtml log elementtidy fixup html html print log line column warning missing doctype declaration line column warning discarding unexpected ...
QA
why does python iter on mapping return iterkeys instead of iteritems it seems like if you want to get the keys of mapping you ask for them otherwise give me the whole mapping constituted by set of key value pairs is there historical reason for this
check out this thread for discussion on the reasons behind this behavior including that guido likes it and it is not likely to change
QA
django imagefield core false in newforms admin in the transition to newforms admin am having difficulty figuring out how specify core false for imagefields get the following error typeerror init got an unexpected keyword argument core edit however by just removing the core argument get this field is required error in t...
to get rid of this field is required you need to make it not required by using blank true and possibly null true as well if it is not charfield
QA
ruby is equivalent is there ruby equivalent for python is it tests whether two objects are identical have the same memory location
use equal http www ruby doc org core classes object html unlike the equal method should never be overridden by subclasses it is used to determine object identity that is equal iff is the same object as
QA
find out how much memory is being used by an object in python how would you go about finding out how much memory is being used by an object know it is possible to find out how much is used by block of code but not by an instantiated object anytime during its life which is what want
there is no easy way to find out the memory size of python object one of the problems you may find is that python objects like lists and dicts may have references to other python objects in this case what would your size be the size containing the size of each object or not there are some pointers overhead and internal...
QA
how can graph the lines of code history for git repo basically want to get the number of lines of code in the repository after each commit the only really crappy ways have found is to use git filter branch to run wc and script that run git reset hard on each commit then ran wc to make it bit clearer when the tool is ru...
you may get both added and removed lines with git log like git log shortstat reverse pretty oneline from this you can write similar script to the one you did using this info in python usr bin python display the per commit size of the current git branch import subprocess import re import sys def main argv git subprocess...
QA
how do content discovery engines like zemanta and open calais work was wondering how as semantic service like open calais figures out the names of companies or people tech concepts keywords etc from piece of text is it because they have large database that they match the text against how would service like zemanta know...
am not familiar with the specific services listed but the field of natural language processing has developed number of techniques that enable this sort of information extraction from general text as sean stated once you have candidate terms it is not to difficult to search for those terms with some of the other entitie...
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing pytho...
in my opinion python is more than ready for developing complex applications see pythons strength more on the server side than writing graphical clients but have look at http www resolversystems com they develop whole spreadsheet in python using the net ironpython port if you are familiar with eclipse have look at pydev...
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing pytho...
really like python it is usually my language of choice these days for small non gui stuff that do on my own however for some larger python projects have tackled am finding that it is not quite the same as programming in say was working on language parser and needed to represent an ast in python this is certainly within...
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing pytho...
python is considered among python programmers to be great language for rapid prototyping there is not lot of extraneous syntax getting in the way of your thought processes so most of the work you do tends to go into the code there is far less idioms required to be involved in writing good python code than in writing go...
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing pytho...
you will find mostly two answers to that the religous one yes of course it is the best language ever and the other religious one you got to be kidding me python no it is not mature enough will maybe skip the last religion python use ruby the truth as always is far from obvious pros it is easy readable batteries include...
QA
programmatically editing python source this is something that think would be very useful basically would like there to be way to edit python source programmatically without requiring human intervention there are couple of things would like to do with this edit the configuration of python apps that use source modules fo...
most of these kinds of things can be determined programatically in python using modules like sys os and the special identifier which tells you where you are in the filesystem path it is important to keep in mind that when module is first imported it will execute everything in the file scope which is important for devel...