prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
pattern matching of lists in python want to do some pattern matching on lists in python for example in haskell can do something like the following fun head rest so when pass in list head will be the first element and rest will be the trailing elements likewise in python can automatically unpack tuples var var func that returns tuple want to do something similar with lists in python right now have function that returns list and chunk of code that does the following ls my func head rest ls ls wondered if could somehow do that in one line in python instead of two
|
first of all please note that the pattern matching of functional languages and the assignment to tuples you mention are not really that similar in functional languages the patterns are used to give partial definitions of function so does not mean take the head and tail of the argument of and return using them but it means that if the argument of is of the form for some and then is equal to the assignment of python is more like multiple assignment suspect that was its original intention so you write for example to swap the values in and without needing temporary variable as you would with simple assignment statement this has little to do with pattern matching as it is basically shorthand for the simultaneous execution of and although python allows arbitrary sequences instead of comma separated lists would not suggest calling this pattern matching with pattern matching you check whether or not something matches pattern in the python assignment you should ensure that the sequences on both sides are the same to do what you seem to want you would usually also in functional languages use either auxiliary function as mentioned by others or something similar to let or where constructs which you can regard as using anonymous functions for example head tail where my func or in actual python head tail lambda my func note that this is essentially the same as the solutions given by others with an auxiliary function except that this is the one liner you wanted it is however not necessarily better than separate function sorry if my answer is bit over the top just think it is important to make the distinction clear
|
QA
|
pattern matching of lists in python want to do some pattern matching on lists in python for example in haskell can do something like the following fun head rest so when pass in list head will be the first element and rest will be the trailing elements likewise in python can automatically unpack tuples var var func that returns tuple want to do something similar with lists in python right now have function that returns list and chunk of code that does the following ls my func head rest ls ls wondered if could somehow do that in one line in python instead of two
|
there was reciepe in the python cookbook to do this cannot seem to find it now but here is the code modified it slightly def peel iterable result tuple removes the requested items from the iterable and stores the remaining in tuple peel test print repr repr def how many unpacked import inspect opcode inspect currentframe back back if ord code co code lasti opcode opmap unpack sequence return ord code co code lasti raise valueerror must be generator on rhs of multiple assignment iterator iter iterable hasitems true amounttounpack how many unpacked next none for num in xrange amounttounpack if hasitems try next iterator next except stopiteration next none hasitems false yield next if hasitems yield result iterator else yield none however you should note that that only works when using an assignment unpack because of the way it inespects the previous frame still its quite useful
|
QA
|
match unicode in ply regexes am matching identifiers but now have problem my identifiers are allowed to contain unicode characters therefore the old way to do things is not enough identifier za za in my markup language parser match unicode characters by allowing all the characters except those explicitly use because my markup language only has two or three of characters need to escape that way how do match all unicode characters with python regexs and ply also is this good idea at all would want to let people use identifiers like foo li as an identifiers variable names and such in their programs heck want that people could write programs in their own language if it is practical anyway unicode is supported nowadays in wide variety of places and it should spread edit posix character classes does not seem to be recognised by python regexes import re item re compile word print item match none edit to explain better what need would need regex thing that matches all the unicode printable characters but not ascii characters at all edit does bit stuff what want but it does not match and also need regex that does not match numbers
|
probably posix character classes are right for you
|
QA
|
match unicode in ply regexes am matching identifiers but now have problem my identifiers are allowed to contain unicode characters therefore the old way to do things is not enough identifier za za in my markup language parser match unicode characters by allowing all the characters except those explicitly use because my markup language only has two or three of characters need to escape that way how do match all unicode characters with python regexs and ply also is this good idea at all would want to let people use identifiers like foo li as an identifiers variable names and such in their programs heck want that people could write programs in their own language if it is practical anyway unicode is supported nowadays in wide variety of places and it should spread edit posix character classes does not seem to be recognised by python regexes import re item re compile word print item match none edit to explain better what need would need regex thing that matches all the unicode printable characters but not ascii characters at all edit does bit stuff what want but it does not match and also need regex that does not match numbers
|
check the answers to this question http stackoverflow com questions stripping non printable characters from string in python you would just need to use the other unicode character categories instead
|
QA
|
is there windows implementation to python libsvn because windows is case insensitive and because svn is case sensitive and because vs tends to rename files giving them the lower case form which messes my repositories history have tried to add the pre commit hook script from http svn collab net repos svn trunk contrib hook scripts case insensitive py sure enough the script uses classes from python libsvn from svn import repos fs which fail to find compiled for windows is there an alternative to libsvn or to the hook script
|
there are two alternative python bindings for libsvn pysvn subvertpy subvertpy is quite new and is written by the author of bzr svn the transparent svn inter operation bridge for bzr for while bzr svn used the upstream swig python bindings and the author contributed lot of bug fixes it helped move the upstream python support for horribly broken to painfully aggravating and unpythonic so after wasting too many hours of his life to swig the author decided to make his own bindings
|
QA
|
match unicode in ply regexes am matching identifiers but now have problem my identifiers are allowed to contain unicode characters therefore the old way to do things is not enough identifier za za in my markup language parser match unicode characters by allowing all the characters except those explicitly use because my markup language only has two or three of characters need to escape that way how do match all unicode characters with python regexs and ply also is this good idea at all would want to let people use identifiers like foo li as an identifiers variable names and such in their programs heck want that people could write programs in their own language if it is practical anyway unicode is supported nowadays in wide variety of places and it should spread edit posix character classes does not seem to be recognised by python regexes import re item re compile word print item match none edit to explain better what need would need regex thing that matches all the unicode printable characters but not ascii characters at all edit does bit stuff what want but it does not match and also need regex that does not match numbers
|
solved it with the help of vinko realised that getting unicode range is plain dumb so will do this symbols re escape join chr for in xrange if not chr isalnum symnums re escape join chr for in xrange if not chr isalnum identifier symnums symbols do not know about unicode character classses if this unicode stuff starts getting too complicated can just put the original one in place utf support still ensures the support is on at the string tokens which is more important edit on other hand start understanding why there is not much unicode support in programming languages this is an ugly hack not satisfying solution
|
QA
|
formatting dict items for wxpython have text box in wxpython that takes the output of dictionary items and displays it to the user as items are added to the dictionary however the raw data is very ugly looking like you because you chm you cpm know dictionary items is list of tuples but cannot seem to figure out how to make nice format that is also compatible with the setvalue method of wxpython have tried iterating through the list and tuples if use print statement the output is fine but when replace the print statement with setvalue it only seems to get the last value of each tuple rather than both items in the tuple have also tried creating string and passing that string to setvalue but again can only get one item in the tuple or the other not both any suggestions edit yes am passing the results of the dictionary items to text field in wxpython application rather than having the results like above am simply looking for something like because chm cmp nothing special just simply pulling each value from each tuple and making visual list have tried making string format and passing that to setvalue but it gets hung up on the two values in the tuple it will either double print each string and add the integers together or it simply returns the integer depending on how format it
|
there is no built in dictionary method that would return your desired result you can however achieve your goal by creating helper function that will format the dictionary def getnicedictrepr adict return join for in adict iteritems this will produce your exact desired output mydict dict you because you chm you cpm print getnicedictrepr mydict because chm cpm then in your application code you can use it by passing it to setvalue self textctrl setvalue getnicedictrepr mydict
|
QA
|
splitting strings in python have string which is like this this is bracket test and quotes test am trying to write something in python to split it up by space while ignoring spaces within square braces and quotes the result am looking for is this is bracket test and quotes test
|
well have encountered this problem quite few times which led me to write my own system for parsing any kind of syntax the result of this can be found here note that this may be overkill and it will provide you with something that let us you parse statements with both brackets and parentheses single and double quotes as nested as you want for example you could parse something like this example written in common lisp defun hello world optional text hello world format text you can use nesting brackets square and parentheses round single and double quoted strings and it is very extensible the idea is basically configurable implementation of finite state machine which builds up an abstract syntax tree character by character recommend you look at the source code see link above so that you can get an idea of how to do it it is capable via regular expressions but try writing system using res and then trying to extend it or even understand it later
|
QA
|
is there windows implementation to python libsvn because windows is case insensitive and because svn is case sensitive and because vs tends to rename files giving them the lower case form which messes my repositories history have tried to add the pre commit hook script from http svn collab net repos svn trunk contrib hook scripts case insensitive py sure enough the script uses classes from python libsvn from svn import repos fs which fail to find compiled for windows is there an alternative to libsvn or to the hook script
|
the tigris org pre complied python bindings for libsvn are separate download the latest as of oct could be found here there are other binary svn distributions listed here and they probably have different policy for bundling the python bindings
|
QA
|
solving the shared server security problem for python so my group is trying to set up shared server environment for various and sundry web services think we have settled on setting disable functions and disable classes site wide in php ini and php admin value to force open basedir in each app httpd conf for php scripts and passenger user switching for ruby scripts we still need to find something for python though passenger does support python but not for per application security for specific sub directories it is all or nothing at the domain level any suggestions and if any of the previous does not make sense well am the guy who is supposed to set up the python support not the guy who set up the php or ruby support so there is still some and then some magic happens steps in there from my perspective
|
well there is system called virtualenv which allows you to run python in sort of safe environment and configure load shutdown these environments on the fly do not know much about it but you should take serious look into it here is the description from its web page just google it and you will find it the basic problem being addressed is one of dependencies and versions and indirectly permissions imagine you have an application that needs version of libfoo but another application requires version how can you use both these applications if you install everything into usr lib python site packages or whatever your platform standard location is it is easy to end up in situation where you unintentionally upgrade an application that should not be upgraded or more generally what if you want to install an application and leave it be if an application works any change in its libraries or the versions of those libraries can break the application also what if you cannot install packages into the global site packages directory for instance on shared host in all these cases virtualenv can help you it creates an environment that has its own installation directories that does not share libraries with other virtualenv environments and optionally does not use the globally installed libraries either
|
QA
|
how can support wildcards in user defined search strings in python is there simple way to support wildcards when searching strings without using regex users are supposed to enter search terms using wildcards but should not have to deal with the complexity of regex foo str startswith foo foo str endswith foo foo foo in str it gets more complicated when there are multiple search terms though foo bar baz this seems like common issue so wonder whether there is ready made solution for it any help would be greatly appreciated
|
you could try the fnmatch module it is got she will like wildcard syntax
|
QA
|
match unicode in ply regexes am matching identifiers but now have problem my identifiers are allowed to contain unicode characters therefore the old way to do things is not enough identifier za za in my markup language parser match unicode characters by allowing all the characters except those explicitly use because my markup language only has two or three of characters need to escape that way how do match all unicode characters with python regexs and ply also is this good idea at all would want to let people use identifiers like foo li as an identifiers variable names and such in their programs heck want that people could write programs in their own language if it is practical anyway unicode is supported nowadays in wide variety of places and it should spread edit posix character classes does not seem to be recognised by python regexes import re item re compile word print item match none edit to explain better what need would need regex thing that matches all the unicode printable characters but not ascii characters at all edit does bit stuff what want but it does not match and also need regex that does not match numbers
|
the re module supports the syntax which if unicode is set this will match the characters plus whatever is classified as alphanumeric in the unicode character properties database therefore the following examples shows how to match unicode identifiers import re re compile you match sre sre match object at xb match match ab sre sre match object at xb match sre sre match object at xb match unic de sre sre match object at xb match dipus sre sre match object at xb so the expression you look for is you
|
QA
|
how do install plpython on macos have just installed postgresql on mac os using ports but cannot figure out how to enable pl python when run the create language plpythonu get the following errors error could not access file libdir plpython no such file or directory statement create language plpythonu psql stdin error could not access file libdir plpython no such file or directory how can fix it ideally would prefer to avoid compiling postgres without port or something like that thia the output of running pg config bindir opt local lib postgresql bin docdir includedir opt local include postgresql pkgincludedir opt local include postgresql includedir server opt local include postgresql server libdir opt local lib postgresql pkglibdir opt local lib postgresql localedir mandir opt local share man sharedir opt local share postgresql sysconfdir opt local etc postgresql pgxs opt local lib postgresql pgxs src makefiles pgxs mk configure prefix opt local sysconfdir opt local etc postgresql bindir opt local lib postgresql bin libdir opt local lib postgresql includedir opt local include postgresql datadir opt local share postgresql mandir opt local share man without docdir with includes opt local include with libraries opt local lib with openssl with bonjour with readline with zlib with libxml with libxslt enable thread safety enable integer datetimes with ossp uuid cc usr bin gcc cflags cppflags opt local include opt local include ossp cpp usr bin cpp ldflags opt local lib cc usr bin gcc no cpp precomp cppflags opt local include opt local include ossp opt local include libxml opt local include cflags wall wmissing prototypes wpointer arith winline wdeclaration after statement wendif labels fno strict aliasing fwrapv cflags sl ldflags opt local lib opt local lib opt local lib ldflags sl libs lpgport lxslt lxml lssl lcrypto lz lreadline lm version postgresql have just switched from linux to mac couple of days ago in ubuntu stuff like that used to just work so am pretty lost
|
silly me lib postgresql variants postgresql postgresql has the variants universal python add support for python krb add support for kerberos authentication perl add perl support would had universal this means that you have to install the right variant of postgresql to make your python functions fly sudo port install postgresql python postgresql server python
|
QA
|
getting pywin to work inside open office built in python interpreter need to update data to mssql database so have decided to use adodbapi which is supposed to come built into the standard installation of python and greater it needs pywin to work correctly and the open office python installation does not have pywin built into it it also seems like this built int python installation does not have adodbapi as get an error when go import adodbapi any suggestions on how to get both pywin and adodbapi installed into this open office python installation thanks oh yeah tried those ways annoyingly nothing so have reverted to jython that way can access open office for its conversion capabilities along with decent database access thanks for the help
|
http www time travellers org shane howtos ms sql express python howto html use an alternative
|
QA
|
how can call dll from scripting language have third party product terminal emulator which provides dll that can be linked to program to basically automate the driving of this product send keystrokes detect what is on the screen and so forth want to drive it from scripting language am comfortable with python and slightly less so with perl so that we do not have to compile and send out executables to our customers whenever there is problem found we also want the customers to be able to write their own scripts using ours as baselines and they will not entertain the idea of writing and compiling code what is good way of getting python perl to interface to windows dll my first thought was to write server program and have python script communicate with it via tcp but there is got to be an easier solution
|
one way to call libraries from python is to use ctypes from ctypes import windll user messageboxa none hello world ctypes
|
QA
|
how can call dll from scripting language have third party product terminal emulator which provides dll that can be linked to program to basically automate the driving of this product send keystrokes detect what is on the screen and so forth want to drive it from scripting language am comfortable with python and slightly less so with perl so that we do not have to compile and send out executables to our customers whenever there is problem found we also want the customers to be able to write their own scripts using ours as baselines and they will not entertain the idea of writing and compiling code what is good way of getting python perl to interface to windows dll my first thought was to write server program and have python script communicate with it via tcp but there is got to be an easier solution
|
in perl win api is an easy way to some interfacing to dlls there is also inline if you have access to compiler and the windows headers perl xsubs can also create an interface between perl and
|
QA
|
how can call dll from scripting language have third party product terminal emulator which provides dll that can be linked to program to basically automate the driving of this product send keystrokes detect what is on the screen and so forth want to drive it from scripting language am comfortable with python and slightly less so with perl so that we do not have to compile and send out executables to our customers whenever there is problem found we also want the customers to be able to write their own scripts using ours as baselines and they will not entertain the idea of writing and compiling code what is good way of getting python perl to interface to windows dll my first thought was to write server program and have python script communicate with it via tcp but there is got to be an easier solution
|
in perl nci will also do that at least in some cases but it seems to me that anything you use that directly manages interfacing with the dll is going to be user unfriendly and if you are going to have user scriptor friendly wrapper it might as well be an xs module guess do not see meaningful distinction between compile and send out executables and compile and send out scripts
|
QA
|
how can call dll from scripting language have third party product terminal emulator which provides dll that can be linked to program to basically automate the driving of this product send keystrokes detect what is on the screen and so forth want to drive it from scripting language am comfortable with python and slightly less so with perl so that we do not have to compile and send out executables to our customers whenever there is problem found we also want the customers to be able to write their own scripts using ours as baselines and they will not entertain the idea of writing and compiling code what is good way of getting python perl to interface to windows dll my first thought was to write server program and have python script communicate with it via tcp but there is got to be an easier solution
|
for python you could compile an extension which links to the dll so that in python you could just import it like normal module you could do this by hand by using library like boost python or by using tool such as swig which also supports perl and other scripting languages to generate wrapper automatically
|
QA
|
refactoring to hit values for game am making game and one of the methods calculates character base hit numbers based on skill values the method currently calculates each value individually since each skill can be used at short medium and long range originally thought could combine the skills into tuple and iterate over it dynamically creating each hit number but do not know if it is actually possible since currently have each hit number assigned to it is own variable also thought about creating method for each range and passing the tuple as an argument could create new tuple or list with the resulting values and then assign them to the individual variables but do not see how it would be any better than do it this way except that it will not look so copy pasted here is what currently have def calcbasehitnumbers self dict calculate character base hit numbers depending on skill level self skill dict dict self rifle self skill dict get crm self pistol self skill dict get pst self big gun self skill dict get lcg self heavy weapon self skill dict get hw self bow self skill dict get lb self skill tuple self rifle self pistol self big gun self heavy weapon self bow short range for skill in self skill tuple self base hit short skill self charattribs bhcrm short self rifle self charattribs bhpst short self pistol self charattribs bhhw short self heavy weapon self charattribs bhlcg short self big gun self charattribs bhlb short self bow med range self charattribs bhcrm med self rifle self charattribs bhpst med self pistol self charattribs bhhw med self heavy weapon self charattribs bhlcg med self big gun self charattribs bhlb med self bow long range self charattribs bhcrm long self rifle self charattribs bhpst long self pistol self charattribs bhhw long self heavy weapon self charattribs bhlcg long self big gun self charattribs bhlb long self bow how would you refactor this so it is more dynamic edit guess what want to do is something like this have tuple like the one commented out and iterate over it times each time making new value for each skill based on the modifier for each particular range the resulting value is then automatically assigned to it is respective variable in my head it makes sense but when actually try to code it get lost the problem think is that this is the first real program have written all have done before are small scripts this is only the version of my program so it is not critical to refactor it now however it seems very un pythonic to do this manually and also want to future proof this in case things change down the road
|
would have class for the character attributes so you do not have heaps of things in the character class and class for weapon attributes class weaponattribute object short mod med mod long mod def init self base self base base property def short self return self base self short mod property def med self return self base self med mod property def long self return self base self long mod class characterattributes object def init self attributes for weapon base in attributes items setattr self weapon weaponattribute base have characterattributes object in the character class and use it like this initialise self charattribs characterattributes self skill dict get some values print self charattribs crm short print self charattribs pst med print self charattribs lcg long
|
QA
|
getting pywin to work inside open office built in python interpreter need to update data to mssql database so have decided to use adodbapi which is supposed to come built into the standard installation of python and greater it needs pywin to work correctly and the open office python installation does not have pywin built into it it also seems like this built int python installation does not have adodbapi as get an error when go import adodbapi any suggestions on how to get both pywin and adodbapi installed into this open office python installation thanks oh yeah tried those ways annoyingly nothing so have reverted to jython that way can access open office for its conversion capabilities along with decent database access thanks for the help
|
do not know about open office python suggest trying the standard windows python installation followed by pywin alternatively there is single installer containing both at activestate in the pythonwin ide select menu item tools com makepy utility the libraries you need to build with makepy are or similar versions microsoft activex data objects library microsoft activex data objects recordset library after makepy is done you can use the com object to access adodb from win com import client conn client dispatch adodb connection conn open connection string resultset execute select from mytable resultset movefirst record fields resultset fields etc
|
QA
|
python distinct on gquery result set gql gae imagine you got an entity in the google app engine datastore storing links for anonymous users you would like to perform the following sql query which is not supported select distinct user hash from links instead you could use user db gqlquery select user hash from links how to use python most efficiently to filter the result so it returns distinct result set how to count the distinct result set
|
one option would be to put the results into set object http www python org doc library sets html sets set the resulting set will consist only of the distinct values passed into it failing that building up new list containing only the unique objects would work something like unique results for obj in user if obj not in unique results unique results append obj that for loop can be condensed into list comprehension as well
|
QA
|
python distinct on gquery result set gql gae imagine you got an entity in the google app engine datastore storing links for anonymous users you would like to perform the following sql query which is not supported select distinct user hash from links instead you could use user db gqlquery select user hash from links how to use python most efficiently to filter the result so it returns distinct result set how to count the distinct result set
|
set is good way to deal with that google com livejournal com livejournal com google com stackoverflow com set set livejournal com google com stackoverflow com one suggestion the first answer is that sets and dicts are better at retrieving unique results quickly membership in lists is versus for the other types so if you want to store additional data or do something like create the mentioned unique results list it may be better to do something like unique results for item in unique results item unique results livejournal com google com stackoverflow com
|
QA
|
xpath search with elementtree new to xml looking for xpath to search xml file with python elementtree format root child one child child two child child three child root to do search for child with two and return true false if it was started off like from elementtree import elementtree root elementtree parse open pathfile getroot how can this be achieved
|
have been playing with elementtree lately let us see from xml etree import elementtree help elementtree elementpath root elementtree fromstring root child one child child two child child three child root elementtree elementpath findall root child element child at ac element child at ac element child at ac elements elementtree elementpath findall root child two for in elements if text two two text two this is what you look for right it says elementpath has just limited xpath support though but it does not say not support at all
|
QA
|
getting pywin to work inside open office built in python interpreter need to update data to mssql database so have decided to use adodbapi which is supposed to come built into the standard installation of python and greater it needs pywin to work correctly and the open office python installation does not have pywin built into it it also seems like this built int python installation does not have adodbapi as get an error when go import adodbapi any suggestions on how to get both pywin and adodbapi installed into this open office python installation thanks oh yeah tried those ways annoyingly nothing so have reverted to jython that way can access open office for its conversion capabilities along with decent database access thanks for the help
|
maybe the best way to install pywin is to place it in openofficedir program python core lib site packages it is easy if you have python installation with pywin installed under python move the python lib site packages to your openofficedir program python core lib site packages
|
QA
|
pattern matching of lists in python want to do some pattern matching on lists in python for example in haskell can do something like the following fun head rest so when pass in list head will be the first element and rest will be the trailing elements likewise in python can automatically unpack tuples var var func that returns tuple want to do something similar with lists in python right now have function that returns list and chunk of code that does the following ls my func head rest ls ls wondered if could somehow do that in one line in python instead of two
|
further to the other answers note that the equivalent head tail operation in python including python extension of the syntax is generally going to be less efficient than haskell pattern matching python lists are implemented as vectors so obtaining the tail will need to take copy of the list this is wrt the size of the list whereas an implementaion using linked lists like haskell can merely use the tail pointer an operation the only exception may be iterator based approaches where the list is not actually returned but an iterator is however this may not be applicable all places where list is desired eg iterating multiple times for instance cipher approach if modified to return the iterator rather than converting it to tuple will have this behaviour alternatively simpler item only method not relying on the bytecode would be def head tail lst it iter list yield it next yield it tail head tail tail head tail tail tail listiterator object at list tail obviously though you still have to wrap in utility function rather than there being nice syntactic sugar for it
|
QA
|
how do you log server errors on django sites so when playing with the development can just set settings debug to true and if an error occures can see it nicely formatted with good stack trace and request information but on kind of production site would rather use debug false and show visitors some standard error page with information that am working on fixing this bug at this moment at the same time would like to have some way of logging all those information stack trace and request info to file on my server so can just output it to my console and watch errors scroll email the log to me every hour or something like this what logging solutions would you recomend for django site that would meet those simple requirements have the application running as fcgi server and am using apache web server as frontend although thinking of going to lighttpd
|
obviously james is correct but if you wanted to log exceptions in datastore there are few opensource solutions already available crashlog is good choice http code google com django crashlog db log is good choice as well http code google com django db log what is the difference between the two almost nothing that can see so either one will suffice have used both and the work well
|
QA
|
pattern matching of lists in python want to do some pattern matching on lists in python for example in haskell can do something like the following fun head rest so when pass in list head will be the first element and rest will be the trailing elements likewise in python can automatically unpack tuples var var func that returns tuple want to do something similar with lists in python right now have function that returns list and chunk of code that does the following ls my func head rest ls ls wondered if could somehow do that in one line in python instead of two
|
unlike haskell or ml python does not have built in pattern matching of structures the most pythonic way of doing pattern matching is with try except block def recursive sum try head tail return head recursive sum tail except indexerror empty list raises indexerror return note that this only works with objects with slice indexing also if the function gets complicated something in the body after the head tail line might raise indexerror which will lead to subtle bugs however this does allow you to do things like for frob in eggs frob list try frob spam except attributeerror eggs no spam count in python tail recursion is generally better implemented as loop with an accumulator def iterative sum ret val for in ret val return ret val this is the one obvious right way to do it of the time not only is it clearer to read it is faster and it will work on things other than lists sets for instance if there is an exception waiting to happen in there the function will happily fail and deliver it up the chain
|
QA
|
python list of lists changes reflected across sublists unexpectedly needed to create list of lists in python so typed the following mylist the list looked like this then changed one of the innermost values mylist now my list looks like this which is not what wanted or expected can someone please explain what is going on and how to get around it
|
or even creates list that references the internal times not three copies of the inner list so any time you modify the list in any position you will see the change three times it is the same as this example inner outer inner outer inner outer where it is probably little less surprising
|
QA
|
python list of lists changes reflected across sublists unexpectedly needed to create list of lists in python so typed the following mylist the list looked like this then changed one of the innermost values mylist now my list looks like this which is not what wanted or expected can someone please explain what is going on and how to get around it
|
when you write you get essentially the list that is list with references to the same when you then modify this single it is visible via all three references to it to fix it you need to make sure that you create new list at each position one way to do it is for in range
|
QA
|
python list of lists changes reflected across sublists unexpectedly needed to create list of lists in python so typed the following mylist the list looked like this then changed one of the innermost values mylist now my list looks like this which is not what wanted or expected can someone please explain what is going on and how to get around it
|
actually this is exactly what you would expect let us decompose what is happening here you write lst this is equivalent to lst lst lst this means lst is list with elements all pointing to lst this means the two following lines are equivalent lst lst as lst is nothing but lst to obtain the desired behavior you can use list comprehension lst for in xrange in this case the expression is re evaluated for each leading to different list
|
QA
|
how do you programmatically reorder children of an atfolder subclass have plone product that uses custom folder type for containing set of custom content objects the folder type was created by subclassing basefolder and it has schema with couple of text fields currently when custom objects are added to the custom folder the objects are sorted alphabetically by their id how can override this behavior and allow my users to sort the custom folders manually say through the contents view
|
quickest solution subclass from atfolder instead of basefolder that gives you all the normal reordering and other commmon plone folder capabilities which suspect you also want if you want to be more selective look into products atcontenttypes content base py atctorderedfolder and orderedbasefolder
|
QA
|
possible to integrate google appengine and google code for continuous integration anyone have any thoughts on how if it is possible to integrate google code commits to cause google appengine deployment of the most recent code have simple google appengine project source hosted on google code and would love if everytime committed to subversion that appengine would reflect the latest commit do not mind if things are broken on the live site since the project is for personal use mainly and for learning anyone have any thoughts on how to tie into the subversion commit for the code repository and or how to kickoff the deployment to appengine ideally the solution would not require anything manual from me nor any type of server listener software on my machine
|
very interesting but not yet possible afaik have been looking for that option in google code with no success the only solution can figure out is to install something in your machine that checks for changes in your svn repository will be happy to hear about other approaches
|
QA
|
python lazy list would like create my own collection that has all the attributes of python list and also knows how to save load itself into from database also want to make the load implicit and lazy as in it does not happen at the point of creation of the list but waits until its first used is there single xxx method can override to load the list on first usage of any list property such aslen getitem iter etc without having to override them all
|
getattribute
|
QA
|
python snippet to remove and comments am looking for python code that removes and comments from string assume the string contains an entire source file realize that could match substrings with regex but that does not solve nesting or having inside ideally would prefer non naive implementation that properly handles awkward cases
|
and comments cannot be nested regular expressions work well this requires the single line flag re because comment can span multiple lines def stripcomments text return re sub text re this code should work edit notice that my above code actually makes an assumption about line endings this code will not work on mac text file however this can be amended relatively easily this regular expression should work on all text files regardless of their line endings covers windows unix and mac line endings edit mizardx and brian in the comments made valid remark about the handling of strings completely forgot about that because the above regex is plucked from parsing module that has additional handling for strings mizardx solution should work very well but it only handles double quoted strings
|
QA
|
python snippet to remove and comments am looking for python code that removes and comments from string assume the string contains an entire source file realize that could match substrings with regex but that does not solve nesting or having inside ideally would prefer non naive implementation that properly handles awkward cases
|
you may be able to leverage py to parse the source with gcc py does not reinvent the wheel it uses gcc compiler to parse source files to be more precise the tool chain looks like this source code is passed to gcc xml gcc xml passes it to gcc compiler gcc xml generates an xml description of program from gcc internal representation py uses pygccxml package to read gcc xml generated file the bottom line you can be sure that all your declarations are read correctly or maybe not regardless this is not trivial parse re based solutions you are unlikely to find re that handles all possible awkward cases correctly unless you constrain input no macros for bulletproof solution you really have no choice than leveraging the real grammar
|
QA
|
post save signal on field have pretty generic article model with relation to tag model want to keep count of each tag usage think the best way would be to denormalise count field on tag model and update it each time article being saved how can accomplish this or maybe there is better way
|
you can do this by creating an intermediate model for the relationship and use it as your hook for the post save and post delete signals to update the denormalised column in the article table for example do this for favourited question counts in soclone where users have relationship with questions from django contrib auth models import user from django db import connection models transaction from django db models signals import post delete post save class question models model favourite count models positiveintegerfield default class favouritequestion models model question models foreignkey question user models foreignkey user def update question favourite count instance kwargs updates the favourite count for the question related to the given favouritequestion if kwargs get raw false return cursor connection cursor cursor execute update soclone question set favourite count select count from soclone favouritequestion where soclone favouritequestion question id soclone question id where id instance question id transaction commit unless managed post save connect update question favourite count sender favouritequestion post delete connect update question favourite count sender favouritequestion very very naughty user add to class favourite questions models manytomanyfield question through favouritequestion related name favourited by there is been bit of discussion on the django developers mailing list about implementing means of declaratively declaring denormalisations to avoid having to write code like the above denormalisation magic and is it really that useful denormalisation magic round two
|
QA
|
python snippet to remove and comments am looking for python code that removes and comments from string assume the string contains an entire source file realize that could match substrings with regex but that does not solve nesting or having inside ideally would prefer non naive implementation that properly handles awkward cases
|
this handles style comments style comments strings and simple nesting thereof def comment remover text def replacer match match group if startswith return note space and not an empty string else return pattern re compile re dotall re multiline return re sub pattern replacer text strings needs to be included because comment markers inside them does not start comment edit re sub did not take any flags so had to compile the pattern first edit added character literals since they could contain quotes that would otherwise be recognized as string delimiters edit fixed the case where legal expression int would become intx which would not compile by replacing the comment with space rather then an empty string
|
QA
|
python lazy list would like create my own collection that has all the attributes of python list and also knows how to save load itself into from database also want to make the load implicit and lazy as in it does not happen at the point of creation of the list but waits until its first used is there single xxx method can override to load the list on first usage of any list property such aslen getitem iter etc without having to override them all
|
no there is not
|
QA
|
want program that writes every possible combination to different line of text file want to write program that would print every combination of set of variables to text file creating word list each answer should be written on separate line and write all of the results for digit digits and digits to single text file is there simple way can write python program that can accomplish this here is an example of the output am expecting when printing all the binary number combinations possible for and digits output
|
it should not be too hard in most languages does the following pseudo code help for int digits writeline tobinarystring
|
QA
|
want program that writes every possible combination to different line of text file want to write program that would print every combination of set of variables to text file creating word list each answer should be written on separate line and write all of the results for digit digits and digits to single text file is there simple way can write python program that can accomplish this here is an example of the output am expecting when printing all the binary number combinations possible for and digits output
|
given two lists of strings return list of all ways to concatenate one from each def combos xs ys return for in xs for in ys digits for in combos digits combos digits digits print
|
QA
|
want program that writes every possible combination to different line of text file want to write program that would print every combination of set of variables to text file creating word list each answer should be written on separate line and write all of the results for digit digits and digits to single text file is there simple way can write python program that can accomplish this here is an example of the output am expecting when printing all the binary number combinations possible for and digits output
|
basic function to produce all the permutations of list is given below in this approach permutations are created lazily by using generators def perms seq if seq yield else res for index item in enumerate seq rest seq index seq index for restperm in perms rest yield item restperm alist for permuation in perms alist print permuation
|
QA
|
how can call dll from scripting language have third party product terminal emulator which provides dll that can be linked to program to basically automate the driving of this product send keystrokes detect what is on the screen and so forth want to drive it from scripting language am comfortable with python and slightly less so with perl so that we do not have to compile and send out executables to our customers whenever there is problem found we also want the customers to be able to write their own scripts using ours as baselines and they will not entertain the idea of writing and compiling code what is good way of getting python perl to interface to windows dll my first thought was to write server program and have python script communicate with it via tcp but there is got to be an easier solution
|
the python py initmodule api function allows you to create module from functions which can then be call from python it takes about dozen or so lines of code to achieve but it is pretty easy code to write https python readthedocs org en extending extending html the module method table and initialization function the zeus editor that wrote uses this appoach to allow zeus macros to be written in python and it works very well
|
QA
|
possible to integrate google appengine and google code for continuous integration anyone have any thoughts on how if it is possible to integrate google code commits to cause google appengine deployment of the most recent code have simple google appengine project source hosted on google code and would love if everytime committed to subversion that appengine would reflect the latest commit do not mind if things are broken on the live site since the project is for personal use mainly and for learning anyone have any thoughts on how to tie into the subversion commit for the code repository and or how to kickoff the deployment to appengine ideally the solution would not require anything manual from me nor any type of server listener software on my machine
|
for those of us who are using github this feature from the gae team would make us all seriously consider switching to google code
|
QA
|
how do you test that python function throws an exception how does one write unittest that fails only if function does not throw an expected exception
|
just discovered that the mock library provides an assertraiseswithmessage method in its unittest testcase subclass which will check not only that the expected exception is raised but also that it is raised with the expected message from testcase import testcase import mymod class mytestcase testcase def test self self assertraiseswithmessage somecoolexception expected message mymod myfunc
|
QA
|
are locks unnecessary in multi threaded python code because of the gil if you are relying on an implementation of python that has global interpreter lock cpython and writing multithreaded code do you really need locks at all if the gil does not allow multiple instructions to be executed in parallel would not shared data be unnecessary to protect sorry if this is dumb question but it is something have always wondered about python on multi processor core machines same thing would apply to any other language implementation that has gil
|
adding to the discussion because the gil exists some operations are atomic in python and do not need lock http www python org doc faq library what kinds of global value mutation are thread safe as stated by the other answers however you still need to use locks whenever the application logic requires them such as in producer consumer problem
|
QA
|
opengl with python am currently in course that is using opengl and have been using for all the programs so far have python installed on fedora as well as opengl however the minute call an opengl command in my python code get segmentation fault have no idea why this is just to avoid the just use comments here is why want to use python there are couple reasons am wanting to switch from to python but the main one is because we are about to start writing raytracer and would like to use classes to make it easier on me since hate classes in and structs in seems little crazy thought would give python try at it have also been looking for reason to use python again as it has been while thanks for any help
|
what opengl library are you using what windowing library what version of python most likely because can think of is that your windowing library sdl or whatever you are using is not initializing opengl before you start calling into it
|
QA
|
python snippet to remove and comments am looking for python code that removes and comments from string assume the string contains an entire source file realize that could match substrings with regex but that does not solve nesting or having inside ideally would prefer non naive implementation that properly handles awkward cases
|
do not forget that in backslash newline is eliminated before comments are processed and trigraphs are processed before that because is the trigraph for backslash have program called scc strip comments and here is part of the test code scc has been trained to know about strings double quotes embedded in strings too and newlines in them and escaped double quotes at the end of string aa ok aa aa this is followed by comment number comment with continuation character on three source lines this should not be seen with the fla the comment number has finished this is followed by comment number comment this should not be seen with the flag the comment number has finished this is followed by regular comment number regular comment the regular comment number has finished this is not comment this is followed by comment number but this is comment the comment number has finished this is not or comment this is followed by regular comment number this is regular comment but this is just routine continuation and that was not the end either but this is the regular comment number has finished this is followed by regular comment number comment this does not illustrate trigraphs note that you can have multiple backslashes at the end of line but the line splicing does not care about how many there are but the subsequent processing might etc writing single regex to handle all these cases will be non trivial but that is different from impossible
|
QA
|
python snippet to remove and comments am looking for python code that removes and comments from string assume the string contains an entire source file realize that could match substrings with regex but that does not solve nesting or having inside ideally would prefer non naive implementation that properly handles awkward cases
|
the regular expression cases will fall down in some situations like where string literal contains subsequence which matches the comment syntax you really need parse tree to deal with this
|
QA
|
python lazy list would like create my own collection that has all the attributes of python list and also knows how to save load itself into from database also want to make the load implicit and lazy as in it does not happen at the point of creation of the list but waits until its first used is there single xxx method can override to load the list on first usage of any list property such aslen getitem iter etc without having to override them all
|
not exactly for emulating things other than lists there is getattribute but unfortunately python does not consider operators like or to be exactly the same as getitem or call operators like that are attributes of the class not attributes of the instance as you can see here class object def getattribute self print traceback most recent call last file stdin line in module typeerror object does not support indexing however you can take advantage of python dynamic nature to effectively eliminate that distinction if your main concern is to save yourself typing and to produce less code that needs maintaining you can do something like this class override object def init self methodname self methodname methodname def get self oself cls oself load self methodname return getattr super oself class oself self methodname class lazylist list def load self name print loading data for name for methodname in set dir list set dir object locals methodname override methodname you probably do not want to use dir in real life but suitable fixed list of strings could work as substitute
|
QA
|
any python libs for parsing bind zone files any python libs for parsing bind zone files basically something that will aid in adding removing zones and records this needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not solution
|
you might try bicop python library to process isc bind style configuration files
|
QA
|
want program that writes every possible combination to different line of text file want to write program that would print every combination of set of variables to text file creating word list each answer should be written on separate line and write all of the results for digit digits and digits to single text file is there simple way can write python program that can accomplish this here is an example of the output am expecting when printing all the binary number combinations possible for and digits output
|
na ve solution which solves the problem and is general enough for any application you might have is this def combinations words length if length return result word for word in words while length new result for combo in result new result extend combo word for word in words result new result length return result basically this gradually builds up tree in memory of all the combinations and then returns them it is memory intensive however and so is impractical for large scale combinations another solution for the problem is indeed to use counting but then to transform the numbers generated into list of words from the wordlist to do so we first need function called number to list def number to list number words list out while number list out number len words list out number number len words return words for in list out this is in fact system for converting decimal numbers to other bases we then write the counting function this is relatively simple and will make up the core of the application def combinations words length numbers xrange len words length for number in numbers combo number to list number words if len combo length combo words length len combo combo yield combo this is python generator making it generator allows it to use up less ram there is little work to be done after turning the number into list of words this is because these lists will need padding so that they are at the requested length it would be used like this list combinations as you can see you get back list of lists each of these sub lists contains sequence of the original words you might then do something like map join list combinations to retrieve the following result you could then write this to disk better idea however would be to use the built in optimizations that generators have and do something like this fileout open filename txt fileout writelines join combo for combo in combinations fileout close this will only use as much ram as necessary enough to store one combination hope this helps
|
QA
|
are there any web based email clients written in python need to integrate email client in my current python web app anything available am building my app on top of cherrypy
|
you could try quotient it is somewhat unusual webmail system and it definitely will not fit into the same process as cherrypy but it is in python
|
QA
|
python leopard fink mac ports python org idiot broken python fresh start have been enjoying learning the basics of python but before started reading things tried to install various python versions and modules clumsily now that have some ideas of what want to do and how to do it am finding that various aspects are broken for instance idle will not launch and when try to import modules they usually do not work my question is how would you recommend clean this up and start fresh have read information about modifying the install but still cannot get it to work idle works and when launch python from the terminal am running python
|
had this problem so much when first got my mac the best solution found was to delete everything would installed and just go with the pythonmac org version of python then installed setuptools from the same site and then used easy install to install every other package oh and got the gnu compiler from the xcode developer tools cd which you can download from apple website so that can compile extensions
|
QA
|
environment variables in python on linux python access to environment variables does not accurately reflect the operating system view of the processes environment os getenv and os environ do not function as expected in particular cases is there way to properly get the running process environment to demonstrate what mean take the two roughly equivalent programs the first in the other in python include stdio include stdlib include unistd int main int argc char argv char env for env getenv some variable if env puts env sleep import os import time while true env os getenv some variable if env is not none print env time sleep now if we run the program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this gdb print setenv some variable my value switching to thread lwp gdb print char getenv some variable my value then the aforementioned program will start spewing out my value once every seconds the aforementioned python program however will not is there way to get the python program to function like the program in this case yes realize this is very obscure and potentially damaging action to perform on running process also am currently using python this may have been fixed in later version of python
|
you can use ctypes to do this pretty simply from ctypes import cdll char getenv cdll libc so getenv getenv restype char getenv home home glyph
|
QA
|
python snippet to remove and comments am looking for python code that removes and comments from string assume the string contains an entire source file realize that could match substrings with regex but that does not solve nesting or having inside ideally would prefer non naive implementation that properly handles awkward cases
|
do not know if you are familiar with sed the unix based but windows available text parsing program but have found sed script here which will remove comments from file it is very smart for example it will ignore and if found in string declaration etc from within python it can be used using the following code import subprocess from cstringio import stringio input stringio source code source code is string with the source code output stringio process subprocess popen sed path to remccoms sed input input output output return code process wait stripped code output getvalue in this program source code is the variable holding the source code and eventually stripped code will hold code with the comments removed of course if you have the file on disk you could have the input and output variables be file handles pointing to those files input in read mode output in write mode remccoms sed is the file from the above link and it should be saved in readable location on disk sed is also available on windows and comes installed by default on most gnu linux distros and mac os this will probably be better than pure python solution no need to reinvent the wheel
|
QA
|
reading collections of extended elements in an rss feed with universal feed parser is there any way to read collection of extension elements with universal feed parser this is just short snippet from kuler rss feed channel item snip regular rss elements kuler themeitem kuler themeid kuler themeid snip kuler themeswatches kuler swatch kuler swatchhexcolor ffffff kuler swatchhexcolor snip kuler swatch kuler swatch kuler swatchhexcolor kuler swatchhexcolor snip kuler swatch kuler themeswatches kuler themeitem item channel tried the following feed feedparser parse url feed channel title you kuler highest rated themes feed entries title you foobar feed entries kuler themeid you feed entries kuler swatch you feed entries kuler swatchhexcolor returns only last kuler swatchhexcolor is there any way to retrieve all elements with feedparser have already worked around the issue by using minidom but would like to use universal feed parser if possible due to very simple api can it be extended have not found anything about that in the documentation so if someone has more experience with the library please advise me
|
universal feed parser is really nice for most feeds but for extended feeds you might want to try something called beautifulsoup it is an xml html xhtml parsing library which is originally designed for screenscraping turns out it is also brilliant for this sort of thing the documentation is pretty good and it is got self explanatory api so if you are thinking of using anything else that is what would recommend would probably use it like this import beautifulsoup import urllib fetch html data from url connection urllib urlopen http kuler adobe com path to rss xml html data connection read connection close create and search the soup soup beautifulsoup beautifulsoup html data themes soup findall kuler themeitem note all lower case element names get the id of the first theme themes find kuler themeid contents you get an ordered list of the hex colors for the first theme themeswatches themes find kuler themeswatches colors color contents for color in themeswatches findall kuler swatchhexcolor colors you ffffff you so you can probably get the idea that this is very cool library it would not be too good if you were parsing any old rss feed but because the data is from adobe kuler you can be pretty sure that it is not going to vary enough to break your app it is trusted enough source even worse is trying to parse adobe goddamn ase format tried writing parser for it and it got really horrible really quickly ug so yeah the rss feeds are probably the easiest way of interfacing with kuler
|
QA
|
possible to integrate google appengine and google code for continuous integration anyone have any thoughts on how if it is possible to integrate google code commits to cause google appengine deployment of the most recent code have simple google appengine project source hosted on google code and would love if everytime committed to subversion that appengine would reflect the latest commit do not mind if things are broken on the live site since the project is for personal use mainly and for learning anyone have any thoughts on how to tie into the subversion commit for the code repository and or how to kickoff the deployment to appengine ideally the solution would not require anything manual from me nor any type of server listener software on my machine
|
you would probably have to have some glue on another computer which monitored svn commits and deployed new version for you google code has yet to develop and release an api which they need to do soon if they are serious about this whole development thing but gae can be deployed to with relative automated ease so would not have thought it should be that difficult the deployment process however will vary with each project so that is something you need to sort out yourself you might want to take look at the fabric deployment system then just set cron job going which updates local svn checkout on the middle machine and you are done
|
QA
|
how does one add svn repository build number to python code edit this question duplicates http stackoverflow com questions how to access the current subversion build number thanks for the heads up charles hi there this question is similar to http stackoverflow com questions getting the subversion repository number into code the differences being would like to add the revision number to python want the revision of the repository not the checked out file would like to extract the revision number from the return from svn info likeso svn info path url svn localhost trunk repository root svn localhost revision node kind directory schedule normal last changed author bmh last changed rev last changed date mon oct want variable with the revision it is easy enough with put rev into variable to keep track of changes on file however would like to keep track of the repository version and understand and it seems based on my tests that rev only updates when the file changes my initial thoughts turn to using the svn libsvn module built in to python though cannot find any documentation on or examples of how to use them alternatively have thought calling svn info and regex ing the code out though that seems rather brutal help would be most appreciated thanks cheers
|
use technique very similar to this in order to show the current subversion revision number in my she will svnrev echo svn info grep revision awk print echo svnrev it works very well for me why do you want the python files to change every time the version number of the entire repository is incremented this will make doing things like doing different between two files annoying if one is from the repo and the other is from tarball
|
QA
|
windowserror priveledged instruction when saving freeimagepy image in script works in idle am working on program to do some image wrangling in python for work am using freeimagepy because pil does not support multi page tiffs whenever try to save file with it from my program get this error message or something similar depending on which way try to save error returned tiff freeimage save failed to open file ocrtmp ocr page traceback most recent call last file python projects ocrpageunzipper pageunzipper py line in mod ule ocrbox converttopages ocrtmp ocr page fipy fif tiff file python lib site packages freeimagepy freeimagepy freeimagepy py ine in converttopages self save fif dib filenameout flags file python lib site packages freeimagepy freeimagepy freeimagepy py ine in save return self lib save typ bitmap filename flags windowserror exception priviledged instruction when try and do the same things from idle it works fine
|
looks like permission issues make sure you do not have the file open in another application and that you have write permissions to the file location your trying to write to
|
QA
|
opengl with python am currently in course that is using opengl and have been using for all the programs so far have python installed on fedora as well as opengl however the minute call an opengl command in my python code get segmentation fault have no idea why this is just to avoid the just use comments here is why want to use python there are couple reasons am wanting to switch from to python but the main one is because we are about to start writing raytracer and would like to use classes to make it easier on me since hate classes in and structs in seems little crazy thought would give python try at it have also been looking for reason to use python again as it has been while thanks for any help
|
we have neither ideas about random segmentation faults there is not enough information what python libraries are you using for opengl how do you use them can you show us your code it is probably something trivial but my god skill ends up to telling me just and only that raytracer in python would prefer just doing that in with those structs but then am assuming you are not going to do realtime raytracer so that may be ok
|
QA
|
starting python debugger automatically on error this is question have wondered about for quite some time yet have never found suitable solution if run script and come across let us say an indexerror python prints the line location and quick description of the error and exits is it possible to automatically start pdb when an error is encountered am not against having an extra import statement at the top of the file nor few extra lines of code
|
this is not the debugger but probably just as useful know heard guido mention this in speech somewhere just checked python and if you use the command you can interact where your script stopped so given this script testlist prev none for in testlist if not prev prev else result prev you can get this output ps python debugtest py traceback most recent call last file debugtest py line in module result prev zerodivisionerror integer division or modulo by zero prev to be honest have not used this but should be seems very useful
|
QA
|
how does one add svn repository build number to python code edit this question duplicates http stackoverflow com questions how to access the current subversion build number thanks for the heads up charles hi there this question is similar to http stackoverflow com questions getting the subversion repository number into code the differences being would like to add the revision number to python want the revision of the repository not the checked out file would like to extract the revision number from the return from svn info likeso svn info path url svn localhost trunk repository root svn localhost revision node kind directory schedule normal last changed author bmh last changed rev last changed date mon oct want variable with the revision it is easy enough with put rev into variable to keep track of changes on file however would like to keep track of the repository version and understand and it seems based on my tests that rev only updates when the file changes my initial thoughts turn to using the svn libsvn module built in to python though cannot find any documentation on or examples of how to use them alternatively have thought calling svn info and regex ing the code out though that seems rather brutal help would be most appreciated thanks cheers
|
python has direct bindings to libsvn so you do not need to invoke the command line client at all see this blog post for more details edit you can basically do something like this from svn import fs repos core repository repos open root path fs ptr repos fs repository youngest revision number fs youngest rev fs ptr
|
QA
|
starting python debugger automatically on error this is question have wondered about for quite some time yet have never found suitable solution if run script and come across let us say an indexerror python prints the line location and quick description of the error and exits is it possible to automatically start pdb when an error is encountered am not against having an extra import statement at the top of the file nor few extra lines of code
|
you can use traceback print exc to print the exceptions traceback then use sys exc info to extract the traceback and finally call pdb post mortem with that traceback import pdb traceback sys def bombs print if name main try bombs except type value tb sys exc info traceback print exc pdb post mortem tb if you want to start an interactive command line with code interact using the locals of the frame where the exception originated you can do import traceback sys code def bombs print if name main try bombs except type value tb sys exc info traceback print exc last frame lambda tb tb last frame tb tb next if tb tb next else tb frame last frame tb frame ns dict frame globals ns update frame locals code interact local ns
|
QA
|
how does one add svn repository build number to python code edit this question duplicates http stackoverflow com questions how to access the current subversion build number thanks for the heads up charles hi there this question is similar to http stackoverflow com questions getting the subversion repository number into code the differences being would like to add the revision number to python want the revision of the repository not the checked out file would like to extract the revision number from the return from svn info likeso svn info path url svn localhost trunk repository root svn localhost revision node kind directory schedule normal last changed author bmh last changed rev last changed date mon oct want variable with the revision it is easy enough with put rev into variable to keep track of changes on file however would like to keep track of the repository version and understand and it seems based on my tests that rev only updates when the file changes my initial thoughts turn to using the svn libsvn module built in to python though cannot find any documentation on or examples of how to use them alternatively have thought calling svn info and regex ing the code out though that seems rather brutal help would be most appreciated thanks cheers
|
there is command called svnversion which comes with subversion and is meant to solve exactly that kind of problem
|
QA
|
starting python debugger automatically on error this is question have wondered about for quite some time yet have never found suitable solution if run script and come across let us say an indexerror python prints the line location and quick description of the error and exits is it possible to automatically start pdb when an error is encountered am not against having an extra import statement at the top of the file nor few extra lines of code
|
use the following module import sys def info type value tb if hasattr sys ps or not sys stderr isatty we are in interactive mode or we do not have tty like device so we call the default hook sys excepthook type value tb else import traceback pdb we are not in interactive mode print the exception traceback print exception type value tb print then start the debugger in post mortem mode pdb pm deprecated pdb post mortem tb more modern sys excepthook info name it debug or whatever you like and put it somewhere in your python path now at the start of your script just add an import debug
|
QA
|
how does one add svn repository build number to python code edit this question duplicates http stackoverflow com questions how to access the current subversion build number thanks for the heads up charles hi there this question is similar to http stackoverflow com questions getting the subversion repository number into code the differences being would like to add the revision number to python want the revision of the repository not the checked out file would like to extract the revision number from the return from svn info likeso svn info path url svn localhost trunk repository root svn localhost revision node kind directory schedule normal last changed author bmh last changed rev last changed date mon oct want variable with the revision it is easy enough with put rev into variable to keep track of changes on file however would like to keep track of the repository version and understand and it seems based on my tests that rev only updates when the file changes my initial thoughts turn to using the svn libsvn module built in to python though cannot find any documentation on or examples of how to use them alternatively have thought calling svn info and regex ing the code out though that seems rather brutal help would be most appreciated thanks cheers
|
if you want to have variable in one source file that can be set to the current working copy revision and does not replay on subversion and working copy being actually available at the time you run your program then subwcrev my be your solution there also seems to be linux port called svnwcrev both perform substitution of wcrev with the highest commit level of the working copy other information may also be provided
|
QA
|
what is the difference between old style and new style classes in python what is the difference between old style and new style classes in python is there ever reason to use old style classes these days
|
new style classes inherit from object and must be written as such in python onwards class classname object instead of class classname the core change is to unify types and classes and the nice side effect of this is that it allows you to inherit from built in types read descrintro for more details
|
QA
|
is there any way to get repl in pydev would like to be able to drop to the python repl from the debugger if this is not possible is there an easier way to evaluate python expressions in the context of the current breakpoint other than manually adding them all as watch expressions
|
do not use pydev but to drop to python interactive repl from code import code code interact local locals to drop to python debugger from code import pdb pdb set trace finally to run interactive repl after running some code you can use python switch python script py that will give you python prompt after the code even if it throws an exception you may be able to hook some of those solutions into pydev think
|
QA
|
how does one add svn repository build number to python code edit this question duplicates http stackoverflow com questions how to access the current subversion build number thanks for the heads up charles hi there this question is similar to http stackoverflow com questions getting the subversion repository number into code the differences being would like to add the revision number to python want the revision of the repository not the checked out file would like to extract the revision number from the return from svn info likeso svn info path url svn localhost trunk repository root svn localhost revision node kind directory schedule normal last changed author bmh last changed rev last changed date mon oct want variable with the revision it is easy enough with put rev into variable to keep track of changes on file however would like to keep track of the repository version and understand and it seems based on my tests that rev only updates when the file changes my initial thoughts turn to using the svn libsvn module built in to python though cannot find any documentation on or examples of how to use them alternatively have thought calling svn info and regex ing the code out though that seems rather brutal help would be most appreciated thanks cheers
|
stolen directly from django def get svn revision path none rev none if path is none path module path entries path svn entries path if os path exists entries path entries open entries path read versions of the entries file are flat text the first line is the version number the next set of digits after dir is the revision if re match entries rev match re search dir entries if rev match rev rev match groups older xml versions of the file specify revision as an attribute of the first entries node else from xml dom import minidom dom minidom parse entries path rev dom getelementsbytagname entry getattribute revision if rev return you svn rev return you svn unknown adapt as appropriate you might want to change module for the name of one of your codemodules this code has the advantage of working even if the destination system does not have subversion installed
|
QA
|
how to set the pythonpath in emacs emacs does not recognize my correct python path think it is general problem with emacs not recognizing my environment variables have gnu emacs apple darwin carbon version of installed have set the pythonpath in my bashrc maybe should set it somewhere else
|
bashrc only gets read when she will starts it will not affect carbon emacs instead use setenv in your emacs setenv pythonpath path string here you can set pythonpath for the entire mac os session by adding it to macosx environment plist more here you probably do not want to do this unless you have xcode and its property list editor installed via procrastiblog
|
QA
|
including dynamic image in web page using post have written cgi script that creates an image dynamically using get data to include this image in my webpage am using the following code img src image py text xxxxxxxxxxxxxx the problem is that expect in the future the text field will get very long and the url will become too large from googling around there does not seem to be fixed limit on url length ie depends on the browser server proxy etc is there better way to do this if it matters am working with django and python and cannot use any client side scripting ie javascript cheers ben
|
img use get you will have to come up with another mechanism how about calling the same functionality in image py and saving the file as temp file which you ref in the img tag or how about saving the value of text in db row during the rendering of this img tag and using the row id as what you pass into the image py script
|
QA
|
including dynamic image in web page using post have written cgi script that creates an image dynamically using get data to include this image in my webpage am using the following code img src image py text xxxxxxxxxxxxxx the problem is that expect in the future the text field will get very long and the url will become too large from googling around there does not seem to be fixed limit on url length ie depends on the browser server proxy etc is there better way to do this if it matters am working with django and python and cannot use any client side scripting ie javascript cheers ben
|
store the text somewhere database and then pass through the primary key
|
QA
|
including dynamic image in web page using post have written cgi script that creates an image dynamically using get data to include this image in my webpage am using the following code img src image py text xxxxxxxxxxxxxx the problem is that expect in the future the text field will get very long and the url will become too large from googling around there does not seem to be fixed limit on url length ie depends on the browser server proxy etc is there better way to do this if it matters am working with django and python and cannot use any client side scripting ie javascript cheers ben
|
this will get you an image as the result of post you may not like it put an iframe where you want the image and size it and remove scrollbars set the src to form with hidden inputs set to your post parameters and the action set to the url that will generate the image submit the form automatically with javascript in the body onload of the iframe html then either serve back an content type set to an image and stream the image bytes or store the post parameters somewhere and generate small id serve back html with an img tag using the id in the url on the server look up the post parameters or generate page with an image tag with an embedded image http danielmclaren net embedding base image data into webpage
|
QA
|
including dynamic image in web page using post have written cgi script that creates an image dynamically using get data to include this image in my webpage am using the following code img src image py text xxxxxxxxxxxxxx the problem is that expect in the future the text field will get very long and the url will become too large from googling around there does not seem to be fixed limit on url length ie depends on the browser server proxy etc is there better way to do this if it matters am working with django and python and cannot use any client side scripting ie javascript cheers ben
|
putting together what has already been said how about creating two pages first page sends post request when the form is submitted let us say to create img py with text xxxxxxx parameter then create img py takes the text parameter and creates an image with it and inserts it or filesystem reference into the db then when rendering the second page generate img tags like img src render img py row id at this point render img py simply queries the db for the given image before creating the image you can check to see if its already in the database therefore reusing recycling previous images with the same text parameter
|
QA
|
including dynamic image in web page using post have written cgi script that creates an image dynamically using get data to include this image in my webpage am using the following code img src image py text xxxxxxxxxxxxxx the problem is that expect in the future the text field will get very long and the url will become too large from googling around there does not seem to be fixed limit on url length ie depends on the browser server proxy etc is there better way to do this if it matters am working with django and python and cannot use any client side scripting ie javascript cheers ben
|
you may be able to mitigate the problem by compressing the text in the get parameter
|
QA
|
single table inheritance in django is there explicit support for single table inheritance in django last heard the feature was still under development and debate are there libraries hacks can use in the meantime to capture the basic behavior have hierarchy that mixes different objects the canonical example of corporation structure with an employee class subclasses for types of employees and manager id parent id would be good approximation of the problem am solving in my case would like to represent the idea that an employee can manage other employees while being managed by different employee there are not separate classes for manager and worker which makes this hard to spread across tables sub classes would represent types of employees programmers accountants sales etc and would be independent of who supervises who ok guess it is no longer typical corporation in some respect
|
there are currently two forms of inheritance in django mti model table inheritance and abc abstract base classes wrote tutorial on what is going on under the hood you can also reference the official docs on model inheritance
|
QA
|
including dynamic image in web page using post have written cgi script that creates an image dynamically using get data to include this image in my webpage am using the following code img src image py text xxxxxxxxxxxxxx the problem is that expect in the future the text field will get very long and the url will become too large from googling around there does not seem to be fixed limit on url length ie depends on the browser server proxy etc is there better way to do this if it matters am working with django and python and cannot use any client side scripting ie javascript cheers ben
|
from the link below it looks like you will be fine for while http www boutell com newfaq misc urllength html
|
QA
|
including dynamic image in web page using post have written cgi script that creates an image dynamically using get data to include this image in my webpage am using the following code img src image py text xxxxxxxxxxxxxx the problem is that expect in the future the text field will get very long and the url will become too large from googling around there does not seem to be fixed limit on url length ie depends on the browser server proxy etc is there better way to do this if it matters am working with django and python and cannot use any client side scripting ie javascript cheers ben
|
if you are using django maybe you can do this via template tag instead something like img src create image this is the text that will be displayed the create image function would create the image with dummy random generated filename and return the path this avoids having to get or post to the script and the images will have manageable filenames can see some potential issues with this approach am just tossing the idea out there
|
QA
|
how do merge two python iterators have two iterators list and an itertools count object an infinite value generator would like to merge these two into resulting iterator that will alternate yield values between the two import itertools itertools count items foo bar merged imerge items the mythical imerge merged next foo merged next merged next bar merged next merged next traceback most recent call last stopiteration what is the simplest most concise way to do this
|
would do something like this this will be most time and space efficient since you will not have the overhead of zipping objects together this will also work if both and are infinite def imerge iter iter while true try yield next yield next except stopiteration return
|
QA
|
how do merge two python iterators have two iterators list and an itertools count object an infinite value generator would like to merge these two into resulting iterator that will alternate yield values between the two import itertools itertools count items foo bar merged imerge items the mythical imerge merged next foo merged next merged next bar merged next merged next traceback most recent call last stopiteration what is the simplest most concise way to do this
|
generator will solve your problem nicely def imerge for in itertools izip yield yield
|
QA
|
how do merge two python iterators have two iterators list and an itertools count object an infinite value generator would like to merge these two into resulting iterator that will alternate yield values between the two import itertools itertools count items foo bar merged imerge items the mythical imerge merged next foo merged next merged next bar merged next merged next traceback most recent call last stopiteration what is the simplest most concise way to do this
|
you can use zip as well as itertools chain this will only work if the first list is finite merge itertools chain iter for in zip foo bar itertools count
|
QA
|
which eclipse package to download for pydev am getting started with python eclipse and pydev which eclipse package should choose nothing on the eclipse homepage tells me what to choose and python documentation assumes have eclipse installed does which package choose matter
|
if you just plan on doing python dev would just go with platform runtime binary after that would follow the instructions http pydev org download html and http pydev org manual root html to install pydev use the same setup for python development also have the radrails plugin for ruby on rails development
|
QA
|
how do merge two python iterators have two iterators list and an itertools count object an infinite value generator would like to merge these two into resulting iterator that will alternate yield values between the two import itertools itertools count items foo bar merged imerge items the mythical imerge merged next foo merged next merged next bar merged next merged next traceback most recent call last stopiteration what is the simplest most concise way to do this
|
you can do something that is almost exaclty what pramod first suggested def izipmerge for in itertools izip yield yield the advantage of this approach is that you will not run out of memory if both and are infinite
|
QA
|
which eclipse package to download for pydev am getting started with python eclipse and pydev which eclipse package should choose nothing on the eclipse homepage tells me what to choose and python documentation assumes have eclipse installed does which package choose matter
|
if you are getting started would recommend you python easyeclipse pydev can give some incompatibilities when using it together with other extensions
|
QA
|
which eclipse package to download for pydev am getting started with python eclipse and pydev which eclipse package should choose nothing on the eclipse homepage tells me what to choose and python documentation assumes have eclipse installed does which package choose matter
|
use ee eclipse for python and java development it works well but classic eclipse should be enought
|
QA
|
what is the ocaml idiom equivalent to python range function want to create list of integers from to can do this in python using range and in haskell using take iterate what is the right ocaml idiom for this
|
here you go let rec range if then else range note that this is not tail recursive modern python versions even have lazy range
|
QA
|
what is the ocaml idiom equivalent to python range function want to create list of integers from to can do this in python using range and in haskell using take iterate what is the right ocaml idiom for this
|
there is no idiom that know of but here is fairly natural definition using an infix operator let let rec aux acc if then acc else aux acc in aux val int int int list fun int list int list int list alternatively the comprehensions syntax extension which gives the syntax for the above is likely to be included in future release of the community version of ocaml so that may become idiomatic do not recommend you start playing with syntax extensions if you are new to the language though
|
QA
|
how to copy all properties of an object to another object in python is there library method to copy all the properties between two already present instances of the same class in python mean something like apache commons propertyutilsbean copyproperties thanks
|
if your class does not modify getitem or setitem for special attribute access all your attributes are stored in dict so you can do nobj dict oobj dict copy just shallow copy if you use python properties you should look at inspect getmembers and filter out the ones you want to copy
|
QA
|
with lua and python embeddable is there place for basic started off programming in basic on the zx then basica gw basic and qbasic moved on to ah turbo hardly knew ye when got started in microcontrollers regressed with the basic stamp from parallax however basic is was awesome because it was so easy to understand and so hard to make mistake moved on to assembly and eventually because needed the additional power speed capacity resources etc but know that if the bar was much higher many people would never get into programming microcontrollers keep getting an itch to make my own on chip basic interpretor but wonder if there is need for basic now that lua and python are easily embeddable and just as approachable as basic what if any are the advantages basic has over other languages why is it still around if decide to make general purpose microcontroller board with an interpreter is there any reason to make version of basic plenty of other languages are considered dead but basic just keeps hanging on
|
used to program in basic in the qbasic days qbasic had subroutines functions structures they used to be called types and guess that is it now this seems limited compared to all the features that python has oo lambdas metaclasses generators list comprehensions just to name few off the top of my head but that simplicity think is strength of basic if you are looking at simple embeddable language would bet that qbasic will be faster and easier to understand and procedural langauge is probably more than sufficient for most embedding scripting type of applications would say the most important reason basic is still around is visual basic for long time in the vb was the only way to write guis com and db code for windows without falling into one of the turing tarpits maybe delphi was good option too but unfortunately it never became as popular as vb do think it is because of all this vb and vba code that is still being used and maintained that basic still is not dead that said would say there is pretty good rationale to write basic interpreter maybe even compiler using llvm or something similar for basic today you will get clean simple easy to use and fast language if you implement something that resembles qbasic you will not have to solve any language design issues and the best part is people will already know your language
|
QA
|
with lua and python embeddable is there place for basic started off programming in basic on the zx then basica gw basic and qbasic moved on to ah turbo hardly knew ye when got started in microcontrollers regressed with the basic stamp from parallax however basic is was awesome because it was so easy to understand and so hard to make mistake moved on to assembly and eventually because needed the additional power speed capacity resources etc but know that if the bar was much higher many people would never get into programming microcontrollers keep getting an itch to make my own on chip basic interpretor but wonder if there is need for basic now that lua and python are easily embeddable and just as approachable as basic what if any are the advantages basic has over other languages why is it still around if decide to make general purpose microcontroller board with an interpreter is there any reason to make version of basic plenty of other languages are considered dead but basic just keeps hanging on
|
good question basically sic have no answer would say just that lua is very easy to learn probably as easy as basic which was one of my first languages as well used dialects on lot of bit computers but is more powerful allowing oo or functional styles and even mixing them and somehow stricter no goto do not know well python but from what have read it is as easy powerful and strict than lua beside both are standardized de facto ie there are no dialects beside the various versions unlike basic which has many variants also both have carefully crafted vm efficient mostly bugless should you make your own interpretor you should either take an existing vm and generate bytecode for it from basic source or make your own sure fun stuff but time consuming and prone to bugs so would just let basic have nice retirement ps why it is hanging on perhaps microsoft is not foreign to that vb vba vbscript there are also lot of dialects around realbasic darkbasic etc with some audience
|
QA
|
with lua and python embeddable is there place for basic started off programming in basic on the zx then basica gw basic and qbasic moved on to ah turbo hardly knew ye when got started in microcontrollers regressed with the basic stamp from parallax however basic is was awesome because it was so easy to understand and so hard to make mistake moved on to assembly and eventually because needed the additional power speed capacity resources etc but know that if the bar was much higher many people would never get into programming microcontrollers keep getting an itch to make my own on chip basic interpretor but wonder if there is need for basic now that lua and python are easily embeddable and just as approachable as basic what if any are the advantages basic has over other languages why is it still around if decide to make general purpose microcontroller board with an interpreter is there any reason to make version of basic plenty of other languages are considered dead but basic just keeps hanging on
|
at the risk of sounding like two old timers on rocking chairs let me grumpily say that kids today do not appreciate basic and then paradoxically say they do not know how good they have got it basics greatest strength was always its comprehensibility it was something that people could get that was long ignored by academics and language developers when you talk about wanting to implement basic assume you are not talking about line numbered basic but structured form the problem with that is that as soon as you start moving into structured programming functions why cannot just goto that spot etc it really becomes unclear what advantages if any basic would have over say python additionally one reason basic was so easy to get right was that in those days libraries were not nearly as important as they are today libraries imply structured if not object oriented programming so again you are in situation where more modern dynamic scripting language fits the reality of what people do today better if the real question is well want to implement an interpreter and so it comes down to return on investment then it becomes problem of an grammar that is actually easy to implement would suggest that basic does not really have that many advantages in that regard either unless you really do return to line numbers and very limited grammar in short do not think you should invest your effort in basic interpreter
|
QA
|
with lua and python embeddable is there place for basic started off programming in basic on the zx then basica gw basic and qbasic moved on to ah turbo hardly knew ye when got started in microcontrollers regressed with the basic stamp from parallax however basic is was awesome because it was so easy to understand and so hard to make mistake moved on to assembly and eventually because needed the additional power speed capacity resources etc but know that if the bar was much higher many people would never get into programming microcontrollers keep getting an itch to make my own on chip basic interpretor but wonder if there is need for basic now that lua and python are easily embeddable and just as approachable as basic what if any are the advantages basic has over other languages why is it still around if decide to make general purpose microcontroller board with an interpreter is there any reason to make version of basic plenty of other languages are considered dead but basic just keeps hanging on
|
this may come off sounding more negative than it really is am not saying basic is the root of all evil others have said that am saying it is legacy we can afford to leave behind because it was so easy to understand and so hard to make mistake that is certainly debatable have had some bad experiences with utterly opaque basic professional stuff commercial products perfectly awful code had to give up and decline the work what if any are the advantages basic has over other languages none really why is it still around two reasons microsoft all the it departments that started doing vb and now have millions of lines of vb legacy code plenty of other languages are considered dead yep basic is there along side cobol pl and rpg as legacies that sometimes have more cost than value but because of the if it are not broke do not fix it policy of big it there they sit sucking up resources who could easily replace it with something smaller simpler and cheaper to maintain except it has not failed it is just disproportionately expensive year old cobol is horrible situation to rework starting in we will be looking at year old ms basic that we just cannot figure out do not want to live without and cannot decide how to replace but basic just keeps hanging on it appears that some folks love basic others see it as yet another poorly designed language it is advantages are being early to market and being backed by huge vendors ibm initially poorly design early to market only leaves us with legacy that we will be suffering with for decades still have my edition dartmouth basic manual do not long for the good old days
|
QA
|
map two lists into one single list of dictionaries imagine have these python lists keys name age values monty matt frank is there direct or at least simple way to produce the following list of dictionaries name monty age name matt age name frank age
|
dumb way but one that comes immediately to my mind def fields from list keys values iterator iter values while true yield dict key iterator next for key in keys list fields from list keys values to produce list
|
QA
|
map two lists into one single list of dictionaries imagine have these python lists keys name age values monty matt frank is there direct or at least simple way to produce the following list of dictionaries name monty age name matt age name frank age
|
zip nearly does what you want unfortunately rather than cycling the shorter list it breaks perhaps there is related function that cycles python keys name age values monty matt frank dict zip keys values age name monty edit oh you want list of dict the following works thanks to peter as well from itertoos import cycle keys name age values monty matt frank zip cycle keys values map lambda dict zip
|
QA
|
map two lists into one single list of dictionaries imagine have these python lists keys name age values monty matt frank is there direct or at least simple way to produce the following list of dictionaries name monty age name matt age name frank age
|
here is my simple approach it seems to be close to the idea that cheery had except that destroy the input list def pack keys values this function destructively creates list of dictionaries from the input lists retval while values for in keys values pop retval append return retval
|
QA
|
how do merge array in python into one string with list comprehension list comprehension for me seems to be like the opaque block of granite that regular expressions are for me need pointers say have list li would like to merge this either into one long list li or into string with separators really would like to know how to do both
|
there are many ways to do this problem like numpy tools because it is normally already imported in everything do however if you are not using numpy for anything else this probably is not good method import numpy li li li first element of array to merge while len li li numpy concatenate li li print li this would print and then you can convert this into your string too
|
QA
|
map two lists into one single list of dictionaries imagine have these python lists keys name age values monty matt frank is there direct or at least simple way to produce the following list of dictionaries name monty age name matt age name frank age
|
yet another try perhaps dumber than the first one def split seq seq count iter seq while true yield next for in xrange count dict zip keys rec for rec in split seq values len keys age name monty age name matt age name frank but it is up to you to decide whether it is dumber
|
QA
|
windowserror priveledged instruction when saving freeimagepy image in script works in idle am working on program to do some image wrangling in python for work am using freeimagepy because pil does not support multi page tiffs whenever try to save file with it from my program get this error message or something similar depending on which way try to save error returned tiff freeimage save failed to open file ocrtmp ocr page traceback most recent call last file python projects ocrpageunzipper pageunzipper py line in mod ule ocrbox converttopages ocrtmp ocr page fipy fif tiff file python lib site packages freeimagepy freeimagepy freeimagepy py ine in converttopages self save fif dib filenameout flags file python lib site packages freeimagepy freeimagepy freeimagepy py ine in save return self lib save typ bitmap filename flags windowserror exception priviledged instruction when try and do the same things from idle it works fine
|
that is what thought too but figured it out couple hours ago apparently if the directory file am trying to write to does not exist freeimagepy is not smart enough to create it most of the time creating new multipage image seems to work fine but guess running it within idle idle figures it out and takes care of it or something managed to work around it by using os mkdir to explicitly make sure things that need exist
|
QA
|
map two lists into one single list of dictionaries imagine have these python lists keys name age values monty matt frank is there direct or at least simple way to produce the following list of dictionaries name monty age name matt age name frank age
|
here is the zip way def mapper keys values len keys return dict zip keys values for in range len values
|
QA
|
map two lists into one single list of dictionaries imagine have these python lists keys name age values monty matt frank is there direct or at least simple way to produce the following list of dictionaries name monty age name matt age name frank age
|
in the answer by konrad rudolph zip nearly does what you want unfortunately rather than cycling the shorter list it breaks perhaps there is related function that cycles here is way keys name age values monty matt frank iter values iter values dict zip keys iter values for in range len values len keys will not call it pythonic think it is too clever but it might be what are looking for there is no benefit in cycling the keys list using itertools cycle because each traversal of keys corresponds to the creation of one dictionnary edit here is another way def iter cut seq size for in range len seq size yield seq size size keys name age values monty matt frank dict zip keys some values for some values in iter cut values len keys this is much more pythonic there is readable utility function with clear purpose and the rest of the code flows naturally from it
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.