prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
would start by writing generator method def grid objects alist blist for in range len alist for in range len alist yield alist blist then whenever you need to iterate over the lists your code looks like this for in grid objects alist blist if is whatever do something
QA
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
generator expressions and izip from itertools module will do very nicely here from itertools import izip for in pair for aline bline in izip alist blist for pair in izip aline bline if iswhatever dosomething the line in for statement above means take each line from combined grids alist and blist and make tuple from them aline bline now combine these lists with izip again and take each element from them pair this method has two advantages there are no indices used anywhere you do not have to create lists with zip and use more efficient generators with izip instead
QA
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
do not get stuck in the mindset of server side page layout consider technologies like sproutcore gwt or extjs which put the layouting code fully on the client making the server responsible only for data marshalling and processing and easily replaced and you really really need to know which server platform you want do not pick one because it is the flavor of the month pick one because you are comfortable with it flavors do not last solidly built codebase will
QA
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
as slight style change you could use enumerate for arow in enumerate alist for aval in enumerate arow if aval iswhatever blist dosomething do not think you will get anything significantly simpler unless you rearrange your data structures as federico suggests so that you could turn the last line into something like aval dosomething
QA
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
if the two lists remain constant during the lifetime of your game and you cannot enjoy python multiple inheritance to join the alist and blist object classes as others have suggested you could add pointer to the corresponding item in each item after the lists are created like this for row row in itertools izip alist blist for item item in itertools izip row row item item item various optimisations can apply here like your classes having slots defined or the initialization code above could be merged with your own initialization code after that your loop will become for row in alist for item in row if item iswhatever item item dosomething that should be more efficient
QA
change django templates based on user agent have made django site but have drank the koolaid and want to make an iphone version after putting much thought into have come up with two options make whole other site like xxxx com tie it into the same database using django sites framework find some time of middleware that reads the user agent and changes the template directories dynamically would really prefer option however have some reservations mainly because the django documentation discourages changing settings on the fly found snippet that would do the what would like my main issue is having it as seamless as possible would like it to be automagic and transparent to the user has anyone else come across the same issue would anyone care to share about how they have tackled making iphone versions of django sites update went with combination of middleware and tweaking the template call for the middleware used minidetector like it because it detects plethora of mobile user agents all have to do is check request mobile in my views for the template call tweak def check mobile request template name if request mobile return mobile template name return template name use this for any view that know have both versions todo figure out how to access request mobile in an extended version of render to response so do not have to use check mobile template name html using the previous automagically fallback to the regular template if no mobile version exists
you should take look at the django mobileadmin source code which solved exactly this problem
QA
python how to use conch to create virtual ssh server am looking at creating server in python that can run and will work as an ssh server this will then let different users login and act as if they would logged in normally but only had access to one command want to do this so that can have system where can add users to without having to create system wide account so that they can then for example commit to vcs branch or similar while can work out how to do this with conch to get it to custom she will cannot figure out how to make it so that the ssh stream works as if it were real one am preferably wanting to limit to bin bzr so that bzr ssh will work it needs to be in python which can get to do the authorisation but do not know how to do the linking to the app this needs to be in python to work within the app its designed for and to be able to be used for those without access to add new users
when you write conch server you can control what happens when the client makes she will request by implementing isession openshell the conch server will request iconchuser from your realm and then adapt the resulting avatar to isession to call openshell on it if necessary isession openshell job is to take the transport object passed to it and associate it with protocol to interpret the bytes received from it and if desired to write bytes to it to be sent to the client in an unfortunate twist the object passed to openshell which represents the transport is actually an iprocessprotocol provider this means that you need to call makeconnection on it passing an iprocesstransport provider when data is received from the client the iprocessprotocol will call writetochild on the transport you pass to makeconnection when you want to send data to the client you should call childdatareceived on it to see the exact behavior suggest reading the implementation of the iprocessprotocol that is passed in do not depend on anything that is not part of iprocessprotocol but seeing the implementation can make it easier to understand what is going on you may also want to look at the implementation of the normal she will creation to get sense of what you are aiming for this will give you clue about how to associate the stdio of the bzr child process you launch with the ssh channel
QA
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
if anyone is interested in performance of the above solutions here they are for grids from fastest to slowest brian modified with izip instead of zip john dzinx but object initialization took eugene robert brian original with zip edit added brian scores with izip modification and it won by large amount john solution is also very fast although it uses indices was really surprised to see this whereas robert and brian with zip are slower than the question creator initial solution so let us present brian winning function as it is not shown in proper form anywhere in this thread from itertools import izip for row row in izip alist blist for item item in izip row row if item iswhatever item dosomething
QA
base binary representation using python building on how do you express binary literals in python was thinking about sensible intuitive ways to do that programming chestnut of displaying integers in base form this is the best came up with but would like to replace it with better algorithm or at least one that should have screaming fast performance def num bin places def bit at find the bit at place for number two using bitshift will have exactly one bit set at place two binary composition will be one where both numbers have at that bit this can only happen at position will yield two if has at bit return int bits bit at for in xrange places return join str for in bits or more consisely return join str int for in xrange places
not screaming fast but straightforward def bin sign if else abs bits while rmost divmod bits append rmost return sign join str for in reversed bits or it is also faster than num bin import timeit bin timeit timer bin xf from main import bin print bin timeit number num bin timeit timer num bin xf from main import num bin print num bin timeit number even more it actually works correctly for my definition of correctness bin num bin
QA
how to use python to login to webpage and retrieve cookies for later usage want to download and parse webpage using python but to access it need couple of cookies set therefore need to login over https to the webpage first the login moment involves sending two post params username password to login php during the login request want to retrieve the cookies from the response header and store them so can use them in the request to download the webpage data php how would do this in python preferably if possible only want to use builtin modules
import urllib urllib cookielib username myuser password mypassword cj cookielib cookiejar opener urllib build opener urllib httpcookieprocessor cj login data urllib urlencode username username password password opener open http www example com login php login data resp opener open http www example com hiddenpage php print resp read resp read is the straight html of the page you want to open and you can use opener to view any page using your session cookie
QA
how to break out of multiple loops in python given the following code that does not work while true snip print out current state while true ok get input is this ok if ok or ok break this does not work if ok or ok break do more processing with menus and stuff is there way to make this work or do have do one check to break out of the input loop then another more limited check in the outside loop to break out all together if the user is satisfied edit fyi get input is short function wrote that supports showing prompt and default values and all that fanciness and returns stdin readline strip
first ordinary logic is helpful if for some reason the terminating conditions cannot be worked out exceptions are fall back plan class getoutofloop exception pass try done false while not done isok false while not done or isok ok get input is this ok if ok in or ok in done true probably better raise getoutofloop other stuff except getoutofloop pass for this specific example an exception may not be necessary on other other hand we often have and options in character mode applications for the option we want an immediate exit that is more exceptional
QA
how to break out of multiple loops in python given the following code that does not work while true snip print out current state while true ok get input is this ok if ok or ok break this does not work if ok or ok break do more processing with menus and stuff is there way to make this work or do have do one check to break out of the input loop then another more limited check in the outside loop to break out all together if the user is satisfied edit fyi get input is short function wrote that supports showing prompt and default values and all that fanciness and returns stdin readline strip
first you may also consider making the process of getting and validating the input function within that function you can just return the value if its correct and keep spinning in the while loop if not this essentially obviates the problem you solved and can usually be applied in the more general case breaking out of multiple loops if you absolutely must keep this structure in your code and really do not want to deal with bookkeeping booleans you may also use goto in the following way using an april fools module from here import the stuff from goto import goto label while true snip print out current state while true ok get input is this ok if ok or ok goto breakall if ok or ok break do more processing with menus and stuff label breakall know know thou shalt not use goto and all that but it works well in strange cases like this
QA
how to break out of multiple loops in python given the following code that does not work while true snip print out current state while true ok get input is this ok if ok or ok break this does not work if ok or ok break do more processing with menus and stuff is there way to make this work or do have do one check to break out of the input loop then another more limited check in the outside loop to break out all together if the user is satisfied edit fyi get input is short function wrote that supports showing prompt and default values and all that fanciness and returns stdin readline strip
my first instinct would be to refactor the nested loop into function and use return to break out
QA
how to break out of multiple loops in python given the following code that does not work while true snip print out current state while true ok get input is this ok if ok or ok break this does not work if ok or ok break do more processing with menus and stuff is there way to make this work or do have do one check to break out of the input loop then another more limited check in the outside loop to break out all together if the user is satisfied edit fyi get input is short function wrote that supports showing prompt and default values and all that fanciness and returns stdin readline strip
keeplooping true while keeplooping do stuff while keeplooping do some other stuff if finisheddoingstuff keeplooping false or something like that you could set variable in the inner loop and check it in the outer loop immediately after the inner loop exits breaking if appropriate kind of like the goto method provided you do not mind using an april fool joke module its not pythonic but it does make sense
QA
how to break out of multiple loops in python given the following code that does not work while true snip print out current state while true ok get input is this ok if ok or ok break this does not work if ok or ok break do more processing with menus and stuff is there way to make this work or do have do one check to break out of the input loop then another more limited check in the outside loop to break out all together if the user is satisfied edit fyi get input is short function wrote that supports showing prompt and default values and all that fanciness and returns stdin readline strip
this is not the prettiest way to do it but in my opinion it is the best way def loop while true snip print out current state while true ok get input is this ok if ok or ok return if ok or ok break do more processing with menus and stuff am pretty sure you could work out something using recursion here as well but do not know if that is good option for you
QA
generator expressions vs list comprehension when should you use generator expressions and when should you use list comprehensions in python generator expression for in range list comprehension for in range
the benefit of generator expression is that it uses less memory since it does not build the whole list at once generator expressions are best used when the list is an intermediary such as summing the results or creating dict out of the results for example sum for in xrange dict some func for in some list of keys the advantage there is that the list is not completely generated and thus little memory is used and should also be faster you should though use list comprehensions when the desired final product is list you are not going to save any memeory using generator expressions since you want the generated list you also get the benefit of being able to use any of the list functions like sorted or reversed for example reversed for in xrange
QA
what property returns the regular expression used when re compile was called def foo re compile abc foo def foo how do get to return abc logging info is
pattern
QA
google app engine and error have setup static website on gae using hints found elsewhere but cannot figure out how to return error my app yaml file looks like url static files static index html upload static index html url static dir static with all the static html jpg files stored under the static directory the above works for files that exist but returns null length file if they do not the answer is probably to write python script to return error but how do you set things up to serve the static files that exist but run the script for files that do not here is the log from fetching non existent file nosuch html on the development application server error dev appserver py error encountered reading file usr home ctuffli www tufflinet static nosuch html errno no such file or directory usr home ctuffli www tufflinet static nosuch html info dev appserver py get nosuch html http
you need to register catch all script handler append this at the end of your app yaml url script main py in main py you will need to put this code from google appengine ext import webapp from google appengine ext webapp util import run wsgi app class notfoundpagehandler webapp requesthandler def get self self error self response out write your error html page application webapp wsgiapplication notfoundpagehandler debug true def main run wsgi app application if name main main replace your error html page with something meaningful or better use template you can read how to do that here please let me know if you have problems setting this up
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
simple solution encode the image as jpeg and look for substantial change in filesize have implemented something similar with video thumbnails and had lot of success and scalability
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
think you could simply compute the euclidean distance sqrt sum of squares of differences pixel by pixel between the luminance of the two images and consider them equal if this falls under some empirical threshold and you would better do it wrapping function
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
earth movers distance might be exactly what you need it might be abit heavy to implement in real time though
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
what about calculating the manhattan distance of the two images that gives you values then you could do something like an row average to reduce to values and function over that to get one single value
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
have you seen the algorithm for finding similar images question check it out to see suggestions would suggest wavelet transformation of your frames have written extension for that using haar transformation then comparing the indexes of the largest proportionally wavelet factors between the two pictures you should get numerical similarity approximation
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
was reading about this on processing org recently and found it stashed in my favorites maybe it helps you http processing org discourse yabb beta yabb cgi board video action display num
QA
daemon threads explanation in the python documentation it says thread can be flagged as daemon thread the significance of this flag is that the entire python program exits when only daemon threads are left the initial value is inherited from the creating thread does anyone have clearer explanation of what that means or practical example showing where you would want to set threads as daemonic to clarify for me so the only time you would not set threads as daemonic is if you wanted them to continue running after the main thread exits
some threads do background tasks like sending keepalive packets or performing periodic garbage collection or whatever these are only useful when the main program is running and it is okay to kill them off once the other non daemon threads have exited without daemon threads you would have to keep track of them and tell them to exit before your program can completely quit by setting them as daemon threads you can let them run and forget about them and when your program quits any daemon threads are killed automatically
QA
daemon threads explanation in the python documentation it says thread can be flagged as daemon thread the significance of this flag is that the entire python program exits when only daemon threads are left the initial value is inherited from the creating thread does anyone have clearer explanation of what that means or practical example showing where you would want to set threads as daemonic to clarify for me so the only time you would not set threads as daemonic is if you wanted them to continue running after the main thread exits
let us say you are making some kind of dashboard widget as part of this you want it to display the unread message count in your email box so you make little thread that will connect to the mail server and ask how many unread messages you have signal the gui with the updated count sleep for little while when your widget starts up it would create this thread designate it daemon and start it because it is daemon you do not have to think about it when your widget exits the thread will stop automatically
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
trivial thing to try resample both images to small thumbnails and compare the thumbnails pixel by pixel with certain threshold if the original images are almost the same the resampled thumbnails will be very similar or even exactly the same this method takes care of noise that can occur especially in low light scenes it may even be better if you go grayscale
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
two popular and relatively simple methods are the euclidean distance already suggested or normalized cross correlation normalized cross correlation tends to be noticeably more robust to lighting changes than simple cross correlation wikipedia gives formula for the normalized cross correlation more sophisticated methods exist too but they require quite bit more work using numpy like syntax dist euclidean sqrt sum size dist manhattan sum abs size dist ncc sum mean mean size stdev stdev assuming that and are grayscale image arrays
QA
how to break out of multiple loops in python given the following code that does not work while true snip print out current state while true ok get input is this ok if ok or ok break this does not work if ok or ok break do more processing with menus and stuff is there way to make this work or do have do one check to break out of the input loop then another more limited check in the outside loop to break out all together if the user is satisfied edit fyi get input is short function wrote that supports showing prompt and default values and all that fanciness and returns stdin readline strip
pep proposes labeled break continue guido rejected it because code so complicated to require this feature is very rare the pep does mention some workarounds though such as the exception technique while guido feels refactoring to use return will be simpler in most cases
QA
how can quantify difference between two images here is what would like to do am taking pictures with webcam at regular intervals sort of like time lapse thing however if nothing has really changed that is the picture pretty much looks the same do not want to store the latest snapshot imagine there is some way of quantifying the difference and would have to empirically determine threshold am looking for simplicity rather than perfection am using python
most of the answers given will not deal with lighting levels would first normalize the image to standard light level before doing the comparison
QA
daemon threads explanation in the python documentation it says thread can be flagged as daemon thread the significance of this flag is that the entire python program exits when only daemon threads are left the initial value is inherited from the creating thread does anyone have clearer explanation of what that means or practical example showing where you would want to set threads as daemonic to clarify for me so the only time you would not set threads as daemonic is if you wanted them to continue running after the main thread exits
simpler way to think about it perhaps when main returns your process will not exit if there are non daemon threads still running bit of advice clean shutdown is easy to get wrong when threads and synchronization are involved if you can avoid it do so use daemon threads whenever possible
QA
idle does start in python if have no connection to internet does that mean cannot start idle which comes with python
idle displays warning message about firewall programs because it connects to the interpreter over the loopback interface but that interface is always connected and does not require you to be on the internet if idle is not working for you with python you might consult python issue
QA
how can capture all exceptions from wxpython application am writing little debug app for bit of kit we are developing and would like to roll it out to few users to see if they can provoke any crashes does anyone know way of effectively wrapping wxpython app to catch any and all unhandled exceptions that would cause the app to crash ideally would want to capture all output not just errors and log it to file any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual the logging process ought to be transparent am sure someone must have done something along these lines before but have not managed to turn up anything that looks useful via google
for the exception handling assuming your log file is opened as log import sys import traceback def excepthook type value tb message uncaught exception message join traceback format exception type value tb log write message sys excepthook excepthook
QA
how to make ruby or python web sites to use multiple cores even though python and ruby have one kernel thread per interpreter thread they have global interpreter lock gil that is used to protect potentially shared data structures so this inhibits multi processor execution even though the portions in those languajes that are written in or can be free threaded that is not possible with pure interpreted code unless you use multiple processes what is the best way to achieve this using fastcgi creating cluster or farm of virtualized servers using their java equivalents jruby and jython
in python and ruby it is only possible to use multiple cores is to spawn new heavyweight processes the java counterparts inherit the possibilities of the java platform you could imply use java threads that is for example reason why sometimes often java application server like glassfish are used for ruby on rails applications
QA
read colors of image with python gae how can read the colors of an image with python using google app engine example like to build function to determine the most striking colors of an image to set harmonic background color for it
the images api does not currently contain pixel level functions to quote the overview document note in order to use the images api in your local environment you must first download and install pil the python imaging library pil is not available on app engine it is only used as stub for the images api in your local environment only the transforms provided in the images api are available on app engine the community has been asking for full pil support for some time but it looks like we will have to wait
QA
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
when you are operating with grids of numbers and want really good performance you should consider using numpy it is surprisingly easy to use and let us you think in terms of operations with grids instead of loops over grids the performance comes from the fact that the operations are then run over whole grids with optimised sse code for example here is some numpy using code that wrote that does brute force numerical simulation of charged particles connected by springs this code calculates timestep for system with nodes and edges in ms that is over faster than the best pure python code could come up with from numpy import array sqrt float newaxis def evolve points velocities edges timestep charge mass edgelen dampen evolve body system of electrostatically repulsive nodes connected by springs by one timestep velocities dampen calculate matrix of distance vectors between all points and their lengths squared dists array for in points for in points dists dists sum axis make the diagonal to avoid division by zero for in xrange points shape inv inv inv sqrt inv repulsive force distance vectors divided by length cubed summed and multiplied by scale scale timestep charge charge mass velocities scale inv newaxis repeat points shape axis dists sum axis calculate spring contributions for each point for idx point outedges in enumerate izip points edges edgevecs point points take outedges axis edgevec lens sqrt edgevecs edgevecs sum axis scale timestep mass velocities idx edgevecs edgelen scale edgevec lens scale newaxis repeat points shape axis sum axis move points to new positions points velocities timestep
QA
read colors of image with python gae how can read the colors of an image with python using google app engine example like to build function to determine the most striking colors of an image to set harmonic background color for it
if you are willing to put flash or java applet on the page you might be able to do it on the client am not sure if anything like canvas or svg supports pixel level manipulation but if they do you might be able to get it to work in some browsers with javascript the flash or java applet can be invisible and optional you can use javascript to detect if the user has the plugin and only support this feature when they do
QA
getting the pattern back from compiled re assume have created compiled re re compile is there way to extract the pattern string back from the
you can get it back with pattern from the python documentation on regular expression objects
QA
how to get complete list of object methods and attributes dir re compile pattern does not return pattern as one of the lists elements namely it returns copy deepcopy findall finditer match scanner search split sub subn according to the manual it is supposed to contain the object attributes names the names of its class attributes and recursively of the attributes of its class base classes it says also that the list is not necessarily complete is there way to get the complete list always assumed that dir returns complete list but apparently it does not also is there way to list only attributes or only methods edit this is actually bug in python supposedly it is fixed in the branch and perhaps also in
for the complete list of attributes the short answer is no the problem is that the attributes are actually defined as the arguments accepted by the getattr built in function as the user can reimplement getattr suddenly allowing any kind of attribute there is no possible generic way to generate that list the dir function returns the keys in the dict attribute all the attributes accessible if the getattr method is not reimplemented for the second question it does not really make sense actually methods are callable attributes nothing more you could though filter callable attributes and using the inspect module determine the class methods methods or functions
QA
python webframework confusion could someone please explain to me how the current python webframworks fit together the three have heard of are cherrypy turbogears and pylons however am confused because turbogears seems to use cherrypy as the controller although is not cherrypy framework in in it is own right and turbgears is going to be built on top of pylons which thought did the same thing
there are more to it ofcourse here is comprehensive list and details web frameworks for python extract from above link popular full stack frameworks web application may use combination of base http application server storage mechanism such as database template engine request dispatcher an authentication module and an ajax toolkit these can be individual components or be provided together in high level framework these are the most popular high level frameworks many of them include components listed on the webcomponents page django released high level python web framework that encourages rapid development and clean pragmatic design pylons released lightweight web framework emphasizing flexibility and rapid development it combines the very best ideas from the worlds of ruby python and perl providing structured but extremely flexible python web framework it is also one of the first projects to leverage the emerging wsgi standard which allows extensive re use and flexibility but only if you need it out of the box pylons aims to make web development fast flexible and easy pylons is built on top of paste see below turbogears released the rapid web development megaframework you have been looking for combines cherrypy kid sqlobject and mochikit after reviewing the website check out quickstart manual web py currently version everything in one package with no dependencies development deployment debugging testing database administration and maintenance of applications can be done via the provided web interface web py has no configuration files requires no installation can run off usb drive web py uses python for the model the views and the controllers has built in ticketing system to manage errors an internationalization engine works with mysql postgresql sqlite oracle mssql and the google app engine via an orm abstraction layer web py includes libraries to handle html xml rss atom csv rtf json ajax xmlrpc wiki markup production ready capable of upload download of very large files and always backward compatible grok released is built on the existing zope libraries but aims to provide an easier learning curve and more agile development experience it does this by placing an emphasis on convention over configuration and dry do not repeat yourself zope released released zope released being the grandaddy of python web frameworks zope has grown into family of frameworks over the years zope was released in zope is both web framework and general purpose application server today it is primarily used by contentmanagementsystems zope is both standalone framework and collection of related libraries which are also included with newer releases of zope all of the zope frameworks include the zodb an object database for python
QA
python webframework confusion could someone please explain to me how the current python webframworks fit together the three have heard of are cherrypy turbogears and pylons however am confused because turbogears seems to use cherrypy as the controller although is not cherrypy framework in in it is own right and turbgears is going to be built on top of pylons which thought did the same thing
if you are looking for start to finish solution then it is worth mentioning that the leader of the pack in that space is django
QA
how to make ruby or python web sites to use multiple cores even though python and ruby have one kernel thread per interpreter thread they have global interpreter lock gil that is used to protect potentially shared data structures so this inhibits multi processor execution even though the portions in those languajes that are written in or can be free threaded that is not possible with pure interpreted code unless you use multiple processes what is the best way to achieve this using fastcgi creating cluster or farm of virtualized servers using their java equivalents jruby and jython
for python the pyprocessing project allows you to program with processes much like you would use threads it is included in the standard library of the recently released version as multiprocessing the module has many features for establishing and controlling access to shared data structures queues pipes etc and support for common idioms managers and worker pools
QA
python webframework confusion could someone please explain to me how the current python webframworks fit together the three have heard of are cherrypy turbogears and pylons however am confused because turbogears seems to use cherrypy as the controller although is not cherrypy framework in in it is own right and turbgears is going to be built on top of pylons which thought did the same thing
cherrypy is not full stack web framework like django for example in fact it is not web framework but http framework writing web application using cherrypy is much like writing regular object oriented application in python also cherrypy has it is own production ready wsgi web server which can be also used for applications written using other frameworks hence the confusion surrounding cherrypy as framework
QA
how to convert file to utf in python need to convert bunch of files to utf in python and have trouble with the converting the file part would like to do the equivalent of iconv utf file converted file this is she will code thanks
you can use the codecs module like this import codecs blocksize or some other desired size in bytes with codecs open sourcefilename your source encoding as sourcefile with codecs open targetfilename utf as targetfile while true contents sourcefile read blocksize if not contents break targetfile write contents edit added blocksize parameter to control file chunk size
QA
how to convert file to utf in python need to convert bunch of files to utf in python and have trouble with the converting the file part would like to do the equivalent of iconv utf file converted file this is she will code thanks
this worked for me in small test sourceencoding iso targetencoding utf source open source target open target target write unicode source read sourceencoding encode targetencoding
QA
converting xml to json using python have seen fair share of ungainly xml json code on the web and having interacted with stack users for bit am convinced that this crowd can help more than the first few pages of google results can so we are parsing weather feed and we need to populate weather widgets on multitude of web sites we are looking now into python based solutions this public weather com rss feed is good example of what we would be parsing our actual weather com feed contains additional information because of partnership them in nutshell how should we convert xml to json using python
well probably the simplest way is just parse the xml into dictionaries and then serialize that with simplejson
QA
converting xml to json using python have seen fair share of ungainly xml json code on the web and having interacted with stack users for bit am convinced that this crowd can help more than the first few pages of google results can so we are parsing weather feed and we need to populate weather widgets on multitude of web sites we are looking now into python based solutions this public weather com rss feed is good example of what we would be parsing our actual weather com feed contains additional information because of partnership them in nutshell how should we convert xml to json using python
there is no one to one mapping between xml and json so converting one to the other necessarily requires some understanding of what you want to do with the results that being said python standard library has several modules for parsing xml including dom sax and elementtree as of python support for converting python data structures to and from json is included in the json module so the infrastructure is there
QA
how to get complete list of object methods and attributes dir re compile pattern does not return pattern as one of the lists elements namely it returns copy deepcopy findall finditer match scanner search split sub subn according to the manual it is supposed to contain the object attributes names the names of its class attributes and recursively of the attributes of its class base classes it says also that the list is not necessarily complete is there way to get the complete list always assumed that dir returns complete list but apparently it does not also is there way to list only attributes or only methods edit this is actually bug in python supposedly it is fixed in the branch and perhaps also in
that is why the new dir method has been added in python see http docs python org whatsnew html other language changes scroll down little bit http bugs python org issue
QA
configuring python am new to python and struggling to find how to control the amount of memory python process can take am running python on cento os machine with more than gb of main memory size python is taking up only mb of this and want to allocate it more tried to search all over the internet on this for last half an hour and found absolutely nothing why is it so difficult to find information on python related stuff would be happy if someone could throw some light on how to configure python for various things like allowed memory size number of threads etc link to site where most controllable parameters of python are described would be appreciated well
forget all that python just allocates more memory as needed there is not myriad of comandline arguments for the vm as in java just let it run for all comandline switches you can just run python or read man python
QA
configuring python am new to python and struggling to find how to control the amount of memory python process can take am running python on cento os machine with more than gb of main memory size python is taking up only mb of this and want to allocate it more tried to search all over the internet on this for last half an hour and found absolutely nothing why is it so difficult to find information on python related stuff would be happy if someone could throw some light on how to configure python for various things like allowed memory size number of threads etc link to site where most controllable parameters of python are described would be appreciated well
are you sure that the machine does not have process limit if you are running the python script as cgi inside web server it is quite likely that there is process limit set you will need to look at the web server configuration
QA
python webframework confusion could someone please explain to me how the current python webframworks fit together the three have heard of are cherrypy turbogears and pylons however am confused because turbogears seems to use cherrypy as the controller although is not cherrypy framework in in it is own right and turbgears is going to be built on top of pylons which thought did the same thing
give try to web py it is point and click you do not even need to install python comes with it you develop using web interface and you can deploy almost everywhere including iphone oracle and google app engine before trying web py try install some of the other python frameworks you will appreciate it even more
QA
how do turn an rss feed back into rss according to the feedparser documentation can turn an rss feed into parsed object like this import feedparser feedparser parse http feedparser org docs examples atom xml but cannot find anything showing how to go the other way would like to be able do manipulate would and then output the result as xml print toxml but there does not seem to be anything in feedparser for going in that direction am going to have to loop through various elements or is there quicker way
appended is not hugely elegant but working solution it uses feedparser to parse the feed you can then modify the entries and it passes the data to pyrss gen it preserves most of the feed info the important bits anyway there are something is that will need extra conversion the parsed feed feed image element for example put this together as part of little feed processing framework am fiddling about with it may be of some use it is pretty short should be less than lines of code in total when done usr bin env python import datetime http www feedparser org import feedparser http www dalkescientific com python pyrss gen html import pyrss gen get the data parsed feed feedparser parse http reddit com rss modify the parsed feed data here items pyrss gen rssitem title title link link description summary guid link pubdate datetime datetime modified parsed modified parsed modified parsed modified parsed modified parsed modified parsed for in parsed feed entries make the rss object try to grab the title link language etc from the orig feed rss pyrss gen rss title parsed feed feed get title link parsed feed feed get link description parsed feed feed get description language parsed feed feed get language copyright parsed feed feed get copyright managingeditor parsed feed feed get managingeditor webmaster parsed feed feed get webmaster pubdate parsed feed feed get pubdate lastbuilddate parsed feed feed get lastbuilddate categories parsed feed feed get categories generator parsed feed feed get generator docs parsed feed feed get docs items items print rss to xml
QA
how do you get output parameters from stored procedure in python have googled around bit but maybe did not put the correct magik incantation into the search box does anyone know how to get output parameters from stored procedure in python am using pymssql to call stored procedure and am not sure of the correct syntax to get the output parameter back do not think can use any other db modules since am running this from linux box to connect to mssql database on ms server import pymssql con pymssql connect host xxxxx user xxxx password xxxxx database xxxxx cur con cursor query execute blah blah blah cur execute query con commit con close
am not python expert but after brief perusing of the db api believe you should use the callproc method of the cursor like this cur callproc my stored proc first param second param an out param then you will have the result in the returned value of the out param in the an out param variable
QA
how to convert file to utf in python need to convert bunch of files to utf in python and have trouble with the converting the file part would like to do the equivalent of iconv utf file converted file this is she will code thanks
thanks for the replies it works and since the source files are in mixed formats added list of source formats to be tried in sequence sourceformats and on unicodedecodeerror try the next format from future import with statement import os import sys import codecs from chardet universaldetector import universaldetector targetformat utf outputdir converted detector universaldetector def get encoding type current file detector reset for line in file current file detector feed line if detector done break detector close return detector result encoding def convertfilebestguess filename sourceformats ascii iso for format in sourceformats try with codecs open filename ru format as sourcefile writeconversion sourcefile print done return except unicodedecodeerror pass def convertfilewithdetection filename print converting filename format get encoding type filename try with codecs open filename ru format as sourcefile writeconversion sourcefile print done return except unicodedecodeerror pass print error failed to convert filename def writeconversion file with codecs open outputdir filename targetformat as targetfile for line in file targetfile write line off topic get the file list and call convertfile on each file edit by rudro badhon this incorporates the original try multiple formats until you do not get an exception as well as an alternate approach that uses chardet universaldetector
QA
is there function in python to print all the current properties and values of an object so what am looking for here is something like php print function this is so can debug my scripts by seeing what is the state of the object in question
you can use the dir function to do this import sys dir sys displayhook doc excepthook name stderr stdin stdo current frames getframe api version argv builtin module names byteorder call tracing callstats copyright displayhook dllhandle exc clear exc info exc type excepthook exec prefix executable exit getcheckinterval getdefault ncoding getfilesystemencoding getrecursionlimit getrefcount getwindowsversion he version maxint maxunicode meta path modules path path hooks path importer ache platform prefix ps ps setcheckinterval setprofile setrecursionlimit settrace stderr stdin stdout subversion version version info warnoption winver another useful feature is help help sys help on built in module sys name sys file built in module docs http www python org doc current lib module sys html description this module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter dynamic objects argv command line arguments argv is the script pathname if known
QA
is there function in python to print all the current properties and values of an object so what am looking for here is something like php print function this is so can debug my scripts by seeing what is the state of the object in question
def dump obj for attr in dir obj print obj attr getattr obj attr there are many rd party functions out there that add things like exception handling national special character printing recursing into nested objects etc according to their authors preferences but they all basically boil down to this
QA
is there function in python to print all the current properties and values of an object so what am looking for here is something like php print function this is so can debug my scripts by seeing what is the state of the object in question
dir has been mentioned but that will only give you the attributes names if you want their values as well try dict class def init self self value dict value
QA
how do log an exception at warning or info level with trace back using the python logging framework using something like this try something except baseexception excep logger logging getlogger componet logger warning something raised an exception excep logger info something raised an exception excep would rather not have it on the error level because in my special case it is not an error at least not in that python process
try using logger exception logger exception creates log message similar to logger error the difference is that logger exception dumps stack trace along with it call this method only from an exception handler
QA
is there function in python to print all the current properties and values of an object so what am looking for here is something like php print function this is so can debug my scripts by seeing what is the state of the object in question
you are really mixing together two different things use dir vars or the inspect module to get what you are interested in use builtins as an example you can use any object instead dir builtins builtins dict print that dictionary however fancy you like print arithmeticerror assertionerror attributeerror or from pprint import pprint pprint arithmeticerror assertionerror attributeerror baseexception deprecationwarning pprint indent arithmeticerror type exceptions arithmeticerror assertionerror type exceptions assertionerror attributeerror type exceptions attributeerror arithmeticerror assertionerror attributeerror baseexception deprecationwarning
QA
in django how do notify parent when child is saved in foreign key relationship have the following two models class activity models model name models charfield max length help text some help entity models foreignkey cancellationentity class cancellation models model activity models foreignkey activity date models datefield default datetime now date description models charfield max length would like the activity model to be aware when cancellation related to it is saved both inserted or updated what is the best way to go about this thanks in advance
what you want to look into is django signals check out this page too specifically the model signals more specifically the post save signal signals are django version of plugin hook system the post save signal gets sent every time model is saved whether it is updated or created and it will let you know if it was created this is how you would use signals to get notified when an activity has cancellation from django db models signals import post save class activity models model name models charfield max length help text some help entity models foreignkey cancellationentity classmethod def cancellation occurred sender instance created raw grab the current instance of activity self instance activity set all do something class cancellation models model activity models foreignkey activity date models datefield default datetime now date description models charfield max length post save connect activity cancellation occurred sender cancellation
QA
converting xml to json using python have seen fair share of ungainly xml json code on the web and having interacted with stack users for bit am convinced that this crowd can help more than the first few pages of google results can so we are parsing weather feed and we need to populate weather widgets on multitude of web sites we are looking now into python based solutions this public weather com rss feed is good example of what we would be parsing our actual weather com feed contains additional information because of partnership them in nutshell how should we convert xml to json using python
while the built in libs for xml parsing are quite good am partial to lxml but for parsing rss feeds would recommend universal feed parser which can also parse atom its main advantage is that it can digest even most malformed feeds python already includes json parser but newer version with improved speed is available as simplejson with these tools building your app should not be that difficult
QA
can you monkey patch methods on core types in python ruby can add methods to the number class and other core types to get effects like should equal but it seems like python cannot do this is this true and if so why does it have something to do with the fact that type cannot be modified update rather than talking about different definitions of monkey patching would like to just focus on the example above have already concluded that it cannot be done as few of you have answered but would like more detailed explanation of why it cannot be done and maybe what feature if available in python would allow this to answer some of you the reason might want to do this is simply aesthetics readability item price should equal reads more like english and clearly indicates which is the tested value and which is the expected value as supposed to should equal item price this concept is what rspec and some other ruby frameworks are based on
no you cannot do that in python consider it to be good thing
QA
can you monkey patch methods on core types in python ruby can add methods to the number class and other core types to get effects like should equal but it seems like python cannot do this is this true and if so why does it have something to do with the fact that type cannot be modified update rather than talking about different definitions of monkey patching would like to just focus on the example above have already concluded that it cannot be done as few of you have answered but would like more detailed explanation of why it cannot be done and maybe what feature if available in python would allow this to answer some of you the reason might want to do this is simply aesthetics readability item price should equal reads more like english and clearly indicates which is the tested value and which is the expected value as supposed to should equal item price this concept is what rspec and some other ruby frameworks are based on
if you really really really want to do monkey patch in python you can do sortof hack with the import foo as bar technique if you have class such as telnetconnection and you want to extend it subclass it in separate file and call it something like telnetconnectionextended then at the top of your code where you would normally say import telnetconnection change that to be import telnetconnectionextended as telnetconnection and then everywhere in your code that you reference telnetconnection will actually be referencing telnetconnectionextended sadly this assumes that you have access to that class and the as only operates within that particular file it is not global rename but have found it to be useful from time to time
QA
can you monkey patch methods on core types in python ruby can add methods to the number class and other core types to get effects like should equal but it seems like python cannot do this is this true and if so why does it have something to do with the fact that type cannot be modified update rather than talking about different definitions of monkey patching would like to just focus on the example above have already concluded that it cannot be done as few of you have answered but would like more detailed explanation of why it cannot be done and maybe what feature if available in python would allow this to answer some of you the reason might want to do this is simply aesthetics readability item price should equal reads more like english and clearly indicates which is the tested value and which is the expected value as supposed to should equal item price this concept is what rspec and some other ruby frameworks are based on
no but you have userdict userstring and userlist which were made with exactly this in mind if you google you will find examples for other types but this are builtin in general monkey patching is less used in python than in ruby
QA
can you monkey patch methods on core types in python ruby can add methods to the number class and other core types to get effects like should equal but it seems like python cannot do this is this true and if so why does it have something to do with the fact that type cannot be modified update rather than talking about different definitions of monkey patching would like to just focus on the example above have already concluded that it cannot be done as few of you have answered but would like more detailed explanation of why it cannot be done and maybe what feature if available in python would allow this to answer some of you the reason might want to do this is simply aesthetics readability item price should equal reads more like english and clearly indicates which is the tested value and which is the expected value as supposed to should equal item price this concept is what rspec and some other ruby frameworks are based on
what exactly do you mean by monkey patch here there are several slightly different definitions if you mean can you change class methods at runtime then the answer is emphatically yes class foo pass dummy class foo bar lambda self foo print bar if you mean can you change class methods at runtime and make all of the instances of that class change after the fact then the answer is yes as well just change the order slightly class foo pass dummy class foo foo bar lambda self print bar but you cannot do this for certain built in classes like int or float these classes methods are implemented in and there are certain abstractions sacrificed in order to make the implementation easier and more efficient am not really clear on why you would want to alter the behavior of the built in numeric classes anyway if you need to alter their behavior subclass them
QA
tfs webservice documentation we use lot of of python to do much of our deployment and would be handy to connect to our tfs server to get information on iteration paths tickets etc can see the webservice but unable to find any documentation just wondering if anyone knew of anything
the web services are not documented by microsoft as it is not an officially supported route to talk to tfs the officially supported route is to use their net api in the case of your sort of application the course of action usually recommend is to create your own web service shim that lives on the tfs server or another server and uses their api to talk to the server but allows you to present the data in nice way to your application their object model simplifies the interactions great deal depending on what you want to do and so it actually means less code over all but better tested and testable code and also you can work around things such as the ntlm auth used by the tfs web services hope that helps martin
QA
can you monkey patch methods on core types in python ruby can add methods to the number class and other core types to get effects like should equal but it seems like python cannot do this is this true and if so why does it have something to do with the fact that type cannot be modified update rather than talking about different definitions of monkey patching would like to just focus on the example above have already concluded that it cannot be done as few of you have answered but would like more detailed explanation of why it cannot be done and maybe what feature if available in python would allow this to answer some of you the reason might want to do this is simply aesthetics readability item price should equal reads more like english and clearly indicates which is the tested value and which is the expected value as supposed to should equal item price this concept is what rspec and some other ruby frameworks are based on
no you cannot in python all data classes methods functions etc defined in extension modules including builtins are immutable this is because modules are shared between multiple interpreters in the same process so monkeypatching them would also affect unrelated interpreters in the same process however classes defined in python code may be monkeypatched because they are local to that interpreter
QA
xml parsing elementtree vs sax and dom python has several ways to parse xml understand the very basics of parsing with sax it functions as stream parser with an event driven api understand the dom parser also it reads the xml into memory and coverts it to objects that can be accessed with python generally speaking it was easy to choose between the depending on what you needed to do memory constraints performance etc hopefully am correct so far since python we also have elementtree how does this compare to dom and sax which is it more similar to why is it better than the previous parsers
elementtree parse is like dom whereas iterparse is like sax in my opinion elementtree is better than dom and sax in that it provides api easier to work with
QA
how do log an exception at warning or info level with trace back using the python logging framework using something like this try something except baseexception excep logger logging getlogger componet logger warning something raised an exception excep logger info something raised an exception excep would rather not have it on the error level because in my special case it is not an error at least not in that python process
in some cases you might want to use the warnings library you can have very fine grained control over how your warnings are displayed
QA
standalone python applications in linux how can distribute standalone python application in linux think can take for granted the presence of recent python interpreter in any modern distribution the problem is dealing with those libraries that do not belong to the standard library wxpython scipy python cryptographic toolkit reportlab and so on is there working linux counterpart to say py exe which by the way have never tried is there free opensource one
you cannot easily do it in distribution neutral format the only reliable dependency tracking mechanisms are built into the package management systems on the distributions and will vary from distribution to distribution you will effectively have to do rpm for fedora debs for ubuntu and debian etc py exe works fine on windows it builds distribution with all of the necessary dll and wrapper for the python interpreter that starts your program it is fairly straightforward to install just drop it in directory so making msi file for it is trivial
QA
standalone python applications in linux how can distribute standalone python application in linux think can take for granted the presence of recent python interpreter in any modern distribution the problem is dealing with those libraries that do not belong to the standard library wxpython scipy python cryptographic toolkit reportlab and so on is there working linux counterpart to say py exe which by the way have never tried is there free opensource one
you might want to look at the dependency declarations in setuptools this might provide way to assure that the right packages are either available in the environment or can be installed by someone with appropriate privileges
QA
how do log an exception at warning or info level with trace back using the python logging framework using something like this try something except baseexception excep logger logging getlogger componet logger warning something raised an exception excep logger info something raised an exception excep would rather not have it on the error level because in my special case it is not an error at least not in that python process
from the logging documentation there are two keyword arguments in kwargs which are inspected exc info which if it does not evaluate as false causes exception information to be added to the logging message if an exception tuple in the format returned by sys exc info is provided it is used otherwise sys exc info is called to get the exception information so do logger warning something raised an exception excep exc info true
QA
what is the best project structure for python application imagine that you want to develop non trivial end user desktop not web application in python what is the best way to structure the project folder hierarchy desirable features are ease of maintenance ide friendliness suitability for source control branching merging and easy generation of install packages in particular where do you put the source where do you put application startup scripts where do you put the ide project cruft where do you put the unit acceptance tests where do you put non python data such as config files where do you put non python sources such as for pyd so binary extension modules
does not too much matter whatever makes you happy will work there are not lot of silly rules because python projects can be simple scripts or bin for that kind of command line interface stuff tests for your tests lib for your language libraries doc for most documentation apidoc for the epydoc generated api docs and the top level directory can contain readme config and whatnot the hard choice is whether or not to use src tree python does not have distinction between src lib and bin like java or has since top level src directory is seen by some as meaningless your top level directory can be the top level architecture of your application foo bar baz recommend putting all of this under the name of my product directory so if you are writing an application named quux the directory that contains all this stuff is named quux another project pythonpath then can include path to quux foo to reuse the quux foo module in my case since use komodo edit my ide cuft is single kpf file actually put that in the top level quux directory and omit adding it to svn
QA
in django how do notify parent when child is saved in foreign key relationship have the following two models class activity models model name models charfield max length help text some help entity models foreignkey cancellationentity class cancellation models model activity models foreignkey activity date models datefield default datetime now date description models charfield max length would like the activity model to be aware when cancellation related to it is saved both inserted or updated what is the best way to go about this thanks in advance
what is wrong with the following class cancellation models model blah blah def save self kw for in self activity set all somethingchanged self super cancellation self save kw it would allow you to to control the notification among models very precisely in way this is the canonical why is oo so good question think oo is good precisely because your collection of cancellation and activity objects can cooperate fully
QA
what is the best project structure for python application imagine that you want to develop non trivial end user desktop not web application in python what is the best way to structure the project folder hierarchy desirable features are ease of maintenance ide friendliness suitability for source control branching merging and easy generation of install packages in particular where do you put the source where do you put application startup scripts where do you put the ide project cruft where do you put the unit acceptance tests where do you put non python data such as config files where do you put non python sources such as for pyd so binary extension modules
non python data is best bundled inside your python modules using the package data support in setuptools one thing strongly recommend is using namespace packages to create shared namespaces which multiple projects can use much like the java convention of putting packages in com yourcompany yourproject and being able to have shared com yourcompany utils namespace re branching and merging if you use good enough source control system it will handle merges even through renames bazaar is particularly good at this contrary to some other answers here am on having src directory top level with doc and test directories alongside specific conventions for documentation directory trees will vary depending on what you are using sphinx for instance has its own conventions which its quickstart tool supports please please leverage setuptools and pkg resources this makes it much easier for other projects to rely on specific versions of your code and for multiple versions to be simultaneously installed with different non code files if you are using package data
QA
what is the best project structure for python application imagine that you want to develop non trivial end user desktop not web application in python what is the best way to structure the project folder hierarchy desirable features are ease of maintenance ide friendliness suitability for source control branching merging and easy generation of install packages in particular where do you put the source where do you put application startup scripts where do you put the ide project cruft where do you put the unit acceptance tests where do you put non python data such as config files where do you put non python sources such as for pyd so binary extension modules
in my experience it is just matter of iteration put your data and code wherever you think they go chances are you will be wrong anyway but once you get better idea of exactly how things are going to shape up you are in much better position to make these kinds of guesses as far as extension sources we have code directory under trunk that contains directory for python and directory for various other languages personally am more inclined to try putting any extension code into its own repository next time around with that said go back to my initial point do not make too big deal out of it put it somewhere that seems to work for you if you find something that does not work it can and should be changed
QA
read colors of image with python gae how can read the colors of an image with python using google app engine example like to build function to determine the most striking colors of an image to set harmonic background color for it
for png you can use pypng module lightweight pure python png decoder encoder import png point coordinates of pixel to read reader png reader filename image png streams are also accepted pixels metadata reader read pixel byte width if metadata has alpha else pixel position point point print pixels pixel position pixel byte width pixel position pixel byte width
QA
is there function in python to print all the current properties and values of an object so what am looking for here is something like php print function this is so can debug my scripts by seeing what is the state of the object in question
you want vars mixed with pprint from pprint import pprint pprint vars your object
QA
can you monkey patch methods on core types in python ruby can add methods to the number class and other core types to get effects like should equal but it seems like python cannot do this is this true and if so why does it have something to do with the fact that type cannot be modified update rather than talking about different definitions of monkey patching would like to just focus on the example above have already concluded that it cannot be done as few of you have answered but would like more detailed explanation of why it cannot be done and maybe what feature if available in python would allow this to answer some of you the reason might want to do this is simply aesthetics readability item price should equal reads more like english and clearly indicates which is the tested value and which is the expected value as supposed to should equal item price this concept is what rspec and some other ruby frameworks are based on
python core types are immutable by design as other users have pointed out int frobnicate lambda self whatever traceback most recent call last file stdin line in module typeerror cannot set attributes of built in extension type int you certainly could achieve the effect you describe by making subclass since user defined types in python are mutable by default class myint int def frobnicate self print frobnicating self five myint five frobnicate frobnicating five there is no need to make the myint subclass public either one could just as well define it inline directly in the function or method that constructs the instance there are certainly few situations where python programmers who are fluent in the idiom consider this sort of subclassing the right thing to do for instance os stat returns tuple subclass that adds named members precisely in order to address the sort of readability concern you refer to in your example import os st os stat st st st st size that said in the specific example you give do not believe that subclassing float in item price or elsewhere would be very likely to be considered the pythonic thing to do can easily imagine somebody deciding to add price should equal method to item if that were the primary use case if one were looking for something more general perhaps it might make more sense to use named arguments to make the intended meaning clearer as in should equal observed item price expected or something along those lines it is bit verbose but no doubt it could be improved upon possible advantage to such an approach over ruby style monkey patching is that should equal could easily perform its comparison on any type not just int or float but perhaps am getting too caught up in the details of the particular example that you happened to provide
QA
what are best practices for developing consistent libraries am working on developing pair of libraries to work with rest api because need to be able to use the api in very different settings am currently planning to have version in php for web applications and second version in python for desktop applications and long running processes are there any best practices to follow in the development of the libraries to help maintain my own sanity
well the obvious one would be to keep your naming consistent functions and classes should be named similarly if not identically in both implementations this usually happens naturally whenever you implement an api separately in two different languages the big ticket item though at least in my book is to follow language specific idioms for example let us assume that were implementing rest api in two languages am more familiar with ruby and scala the ruby version might have class mycompany foo which contains method bar baz conversely the scala version of the same api would have class com mycompany rest foo with method barbaz it is just naming conventions but find it goes long way to helping your api to feel at home in particular language even when the design was created elsewhere beyond that have only one piece of advise document document document that is easily the best way to keep your sanity when dealing with multi implementation api spec
QA
what are best practices for developing consistent libraries am working on developing pair of libraries to work with rest api because need to be able to use the api in very different settings am currently planning to have version in php for web applications and second version in python for desktop applications and long running processes are there any best practices to follow in the development of the libraries to help maintain my own sanity
so the problem with developing parallel libraries in different languages is that often times different languages will have different idioms for the same task know this from personal experience having ported library from python to php idioms are not just naming for example python has good deal of magic you can use with getters and setters to make object properties act magical python has monkeypatching python has named parameters with port you want to pick base language and then attempt to mimic all the idioms in the other language not easy to do for parallel development not doing anything too tricky and catering to the least common denominator is preferable then bolt on the syntax sugar
QA
what are best practices for developing consistent libraries am working on developing pair of libraries to work with rest api because need to be able to use the api in very different settings am currently planning to have version in php for web applications and second version in python for desktop applications and long running processes are there any best practices to follow in the development of the libraries to help maintain my own sanity
be your own client have found that the technique of writing tests first is an excellent way of ensuring an api is easy to use writing tests first means you will be thinking like consumer of your api rather than just an implementor
QA
what are best practices for developing consistent libraries am working on developing pair of libraries to work with rest api because need to be able to use the api in very different settings am currently planning to have version in php for web applications and second version in python for desktop applications and long running processes are there any best practices to follow in the development of the libraries to help maintain my own sanity
try to write common unit test suite for both maybe by wrapping class in one language for calling it from the other if you cannot do it at least make sure the two versions of the tests are equivalent
QA
is there function in python to print all the current properties and values of an object so what am looking for here is something like php print function this is so can debug my scripts by seeing what is the state of the object in question
to print the current state of the object you might obj in an interpreter or print repr obj in script or print obj for your classes define str or repr methods from the python documentation repr self called by the repr built in function and by string conversions reverse quotes to compute the official string representation of an object if at all possible this should look like valid python expression that could be used to recreate an object with the same value given an appropriate environment if this is not possible string of the form some useful description should be returned the return value must be string object if class defines repr but not str then repr is also used when an informal string representation of instances of that class is required this is typically used for debugging so it is important that the representation is information rich and unambiguous str self called by the str built in function and by the print statement to compute the informal string representation of an object this differs from repr in that it does not have to be valid python expression more convenient or concise representation may be used instead the return value must be string object
QA
microphone access in python can access users microphone in python sorry forgot not everyone is mind reader windows at minimum xp but vista support would be very good
best way to go about it would be to use the ctypes library and use winmm from that mixeropen will open microphone device and you can read the data easily from there should be very straightforward
QA
how can in python iterate over multiple lists at once cleanly if am making simple grid based game for example might have few lists one might be for terrain another might be for objects etc unfortunately when need to iterate over the lists and have the contents of square in one list affect part of another list have to do something like this for in range len alist for in range len alist if alist iswhatever blist dosomething is there nicer way to do something like this
if iswhatever is rarely true you could build an index once index set for arow in enumerate for in enumerate arow if iswhatever and each time you want something to be done for in index dosomething if changes over time then you will need to keep the index up to date that is why used set so items can be added and removed fast
QA
is there function in python to print all the current properties and values of an object so what am looking for here is something like php print function this is so can debug my scripts by seeing what is the state of the object in question
metaprogramming example dump object with magic cat dump py usr bin python import sys if len sys argv module metaklass sys argv import module globals locals metaklass metaclass getattr metaklass class data def init self self num self lst self str spam dumps lambda self repr self str lambda self self dumps data data print data without arguments python dump py main data instance at with gnosis utils python dump py gnosis magic metaxmlpickler xml version doctype pyobject system pyobjects dtd pyobject module main class data id attr name lst type list id item type string value item type string value item type string value attr attr name num type numeric value attr name str type string value spam pyobject it is bit outdated but still working
QA
what are good rules of thumb for python imports am little confused by the multitude of ways in which you can import modules in python import import as from import have been reading up about scoping and namespaces but would like some practical advice on what is the best strategy under which circumstances and why should imports happen at module level or method function level in the init py or in the module code itself my question is not really answered by python packages import by class not file although it is obviously related
would normally use import on module level if you only need single object from module use from import only use import as in case you are otherwise confronted with name clash only use imports on function level to import stuff need when the module is used as the main module like def main import sys if len sys argv pass hth
QA
what are good rules of thumb for python imports am little confused by the multitude of ways in which you can import modules in python import import as from import have been reading up about scoping and namespaces but would like some practical advice on what is the best strategy under which circumstances and why should imports happen at module level or method function level in the init py or in the module code itself my question is not really answered by python packages import by class not file although it is obviously related
in production code in our company we try to follow the following rules we place imports at the beginning of the file right after the main file docstring registry related functionality import wx now if we import class that is one of few in the imported module we import the name directly so that in the code we only have to use the last part from registrycontroller import registrycontroller from ui windows lists import listctrl dynamiclistctrl there are modules however that contain dozens of classes list of all possible exceptions then we import the module itself and reference to it in the code from main core import exceptions raise exceptions filenotfound we use the import as as rarely as possible because it makes searching for usage of particular module or class difficult sometimes however you have to use it if you wish to import two classes that have the same name but exist in different modules from queue import queue from main core messagequeue import queue as messagequeue as general rule we do not do imports inside methods they simply make code slower and less readable some may find this good way to easily resolve cyclic imports problem but better solution is code reorganization
QA
what are good rules of thumb for python imports am little confused by the multitude of ways in which you can import modules in python import import as from import have been reading up about scoping and namespaces but would like some practical advice on what is the best strategy under which circumstances and why should imports happen at module level or method function level in the init py or in the module code itself my question is not really answered by python packages import by class not file although it is obviously related
the import as is useful if you have different implementations of the same module class with some nested try import except importerror imports you can hide the implementation from your code see lxml etree import example try from lxml import etree print running with lxml etree except importerror try python import xml etree celementtree as etree print running with celementtree on python except importerror try python import xml etree elementtree as etree print running with elementtree on python except importerror try normal celementtree install import celementtree as etree print running with celementtree except importerror try normal elementtree install import elementtree elementtree as etree print running with elementtree except importerror print failed to import elementtree from any known place
QA
standalone python applications in linux how can distribute standalone python application in linux think can take for granted the presence of recent python interpreter in any modern distribution the problem is dealing with those libraries that do not belong to the standard library wxpython scipy python cryptographic toolkit reportlab and so on is there working linux counterpart to say py exe which by the way have never tried is there free opensource one
create deb for everything debian derived and an rpm for fedora suse add the right dependencies to the packaging and you can be reasonably sure that it will work
QA
what are good rules of thumb for python imports am little confused by the multitude of ways in which you can import modules in python import import as from import have been reading up about scoping and namespaces but would like some practical advice on what is the best strategy under which circumstances and why should imports happen at module level or method function level in the init py or in the module code itself my question is not really answered by python packages import by class not file although it is obviously related
generally try to use the regular import modulename unless the module name is long or used often for example would do from beautifulsoup import beautifulstonesoup as bss so can do soup bss html instead of beautifulsoup beautifulstonesoup html or from xmpp import xmppclientbase instead of importing the entire of xmpp when only use the xmppclientbase using import as is handy if you want to import either very long method names or to prevent clobbering an existing import variable class method something you should try to avoid completely but it is not always possible say want to run main function from another script but already have main function from my other module import main as other module main would not replace my main function with my other module main oh one thing do not do from import it makes your code very hard to understand as you cannot easily see where method came from from import from import my func where is my func defined in all cases you could just do import modulename and then do modulename subthing subthing method test the from import as stuff is purely for convenience use it whenever it will make your code easier to read or write
QA
problem opening berkeley db in python have problems opening berkeley db in python using bdtables as bdtables is used by the library am using to access the database need it to work the problem seems to be that the db environment am trying to open got copy of the database to open is version while libdb is version get the following error using bsddb dbtables bsdtabledb dbname folder db version mismatch database environment version mismatch program version does not match environment version however bsddb btopen dbname works have also tried installing db util db util and db util trying to use db verify results in db verify program version does not match environment version db verify db env open db version mismatch database environment version mismatchs db verify results in the computer just hanging and nothing happening finally if run db recover on the database that works however afterwards get the following error no such file or directory in python
damn verifying everything in this question eventually solved the problem the no such file or directory are caused by some db xxx files missing using bsddb dbtables bsdtabledb dbname folder create after db recover these files got created and everything is now working still it was bit of an obscure problem and initially hard to figure out but thanks to the question examining berkeley db files from the cli got the tools needed will just post it here if someone ends up with the same problem in the future and end up at stackoverflow com
QA
what are good rules of thumb for python imports am little confused by the multitude of ways in which you can import modules in python import import as from import have been reading up about scoping and namespaces but would like some practical advice on what is the best strategy under which circumstances and why should imports happen at module level or method function level in the init py or in the module code itself my question is not really answered by python packages import by class not file although it is obviously related
others have covered most of the ground here but just wanted to add one case where will use import as temporarily when am trying out new version of class or module so if we were migrating to new implementation of module but did not want to cut the code base over all at one time we might write xyz new module and do this in the source files that we had migrated import xyz new as xyz then once we cut over the entire code base we would just replace the xyz module with xyz new and change all of the imports back to import xyz
QA
what are good rules of thumb for python imports am little confused by the multitude of ways in which you can import modules in python import import as from import have been reading up about scoping and namespaces but would like some practical advice on what is the best strategy under which circumstances and why should imports happen at module level or method function level in the init py or in the module code itself my question is not really answered by python packages import by class not file although it is obviously related
do not do this from import unless you are absolutely sure that you will use each and every thing in that module and even then you should probably reconsider using different approach other than that it is just matter of style from import is good and saves you lots of typing tend to use that when am using something in it fairly frequently but if you are importing lot from that module you could end up with an import statement that looks like this from import you get the idea that is when imports like import become useful either that or if am not really using anything in very frequently
QA
xml parsing elementtree vs sax and dom python has several ways to parse xml understand the very basics of parsing with sax it functions as stream parser with an event driven api understand the dom parser also it reads the xml into memory and coverts it to objects that can be accessed with python generally speaking it was easy to choose between the depending on what you needed to do memory constraints performance etc hopefully am correct so far since python we also have elementtree how does this compare to dom and sax which is it more similar to why is it better than the previous parsers
elementtree has more pythonic api it also is in standard library now so using it reduces dependencies actually prefer lxml as it has api like elementtree but has also nice additional features and performs well
QA
xml parsing elementtree vs sax and dom python has several ways to parse xml understand the very basics of parsing with sax it functions as stream parser with an event driven api understand the dom parser also it reads the xml into memory and coverts it to objects that can be accessed with python generally speaking it was easy to choose between the depending on what you needed to do memory constraints performance etc hopefully am correct so far since python we also have elementtree how does this compare to dom and sax which is it more similar to why is it better than the previous parsers
elementtree is much easier to use because it represents an xml tree basically as structure of lists and attributes are represented as dictionaries elementtree needs much less memory for xml trees than dom and thus is faster and the parsing overhead via iterparse is comparable to sax additionally iterparse returns partial structures and you can keep memory usage constant during parsing by discarding the structures as soon as you process them elementtree as in python has only small feature set compared to full blown xml libraries but it is enough for many applications if you need validating parser or complete xpath support lxml is the way to go for long time it used to be quite unstable but have not had any problems with it since elementtree deviates from dom where nodes have access to their parent and siblings handling actual documents rather than data stores is also bit cumbersome because text nodes are not treated as actual nodes in the xml snippet this is test the string test will be the so called tail of element in general recommend elementtree as the default for all xml processing with python and dom or sax as the solutions for specific problems
QA
recommended data format for describing the rules of chess am going to be writing chess server and one or more clients for chess and want to describe the rules of chess allowable moves based on game state rules for when game is complete in programming language independant way this is bit tricky since some of the chess rules king castling en passent draws based on or more repeated moves are based not only on the board layout but also on the history of moves would prefer the format to be textual human readable based on standard yaml xml easily parsable in variety of languages but am willing to sacrifice any of these for suitable solution my main question is how can build algorithms of such complexity that operate on such complex state from data format followup queston is can you provide an example of similar problem solved in similar manner that can act as starting point edit in response to request for clarity consider that will have server written in python one client written in and another client written in java would like to avoid specifying the rules for allowable piece movement circumstances for check etc in each place would prefer to specify these rules once in language independant manner
let us think we are describing objects locations and pieces with states and behaviors we need to note current state and an ever changing set of allowed state changes from current state this is programming you do not want some meta language that you can then parse in regular programming language just use programming language start with ordinary class definitions in an ordinary language get it all to work then those class definitions are the definition of chess with only miniscule exceptions all programming languages are textual human readable reasonably standardized easily parsed by their respective compilers or interpreters just pick language and you are done since it will take while to work out the nuances you will probably be happier with dynamic language like python or ruby than with static language like java or if you want portability pick portable language if you want the language embedded in larger application then pick the language for your larger application since the original requirements were incomplete secondary minor issue is how to have code that runs in conjunction with multiple clients do not have clients in multiple languages pick one java for example and stick with it if you must have clients in multiple languages then you need language you can embed in all three language run time environments you have two choices embed an interpreter for example python tcl and javascript are lightweight interpreters that you can call from or programs this approach works for browsers it can work for you java via jni can make use of this also there are bpel rules engines that you can try this with spawn an interpreter as separate subprocess open named pipe or socket or something between your app and your spawned interpreter your java and clients can talk with python subprocess your python server can simply use this code
QA
recommended data format for describing the rules of chess am going to be writing chess server and one or more clients for chess and want to describe the rules of chess allowable moves based on game state rules for when game is complete in programming language independant way this is bit tricky since some of the chess rules king castling en passent draws based on or more repeated moves are based not only on the board layout but also on the history of moves would prefer the format to be textual human readable based on standard yaml xml easily parsable in variety of languages but am willing to sacrifice any of these for suitable solution my main question is how can build algorithms of such complexity that operate on such complex state from data format followup queston is can you provide an example of similar problem solved in similar manner that can act as starting point edit in response to request for clarity consider that will have server written in python one client written in and another client written in java would like to avoid specifying the rules for allowable piece movement circumstances for check etc in each place would prefer to specify these rules once in language independant manner
edit overly wordy answer deleted the short answer is write the rules in python use iron python to interface that to the client and jython for the java client
QA
recommended data format for describing the rules of chess am going to be writing chess server and one or more clients for chess and want to describe the rules of chess allowable moves based on game state rules for when game is complete in programming language independant way this is bit tricky since some of the chess rules king castling en passent draws based on or more repeated moves are based not only on the board layout but also on the history of moves would prefer the format to be textual human readable based on standard yaml xml easily parsable in variety of languages but am willing to sacrifice any of these for suitable solution my main question is how can build algorithms of such complexity that operate on such complex state from data format followup queston is can you provide an example of similar problem solved in similar manner that can act as starting point edit in response to request for clarity consider that will have server written in python one client written in and another client written in java would like to avoid specifying the rules for allowable piece movement circumstances for check etc in each place would prefer to specify these rules once in language independant manner
this is answering the followup question can point out that one of the most popular chess servers around documents its protocol here warning ftp link and does not support passive ftp but only to write interfaces to it not for any other purpose you could start writing client for this server as learning experience one thing that is relevant is that good chess servers offer many more features than just move relay that said there is more basic protocol used to interface to chess engines documented here oh and by the way board representation at wikipedia anything beyond board representation belongs to the program itself as many have already pointed out