prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
|
one function have come to appreciate is string translate its very fast at what it does and useful anywhere you want to alter or remove characters in string have just used it in seemingly inapplicable problem and found it beat all the other solutions handily the downside is that its api is bit clunky but this is improving in py py
|
QA
|
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
|
remember use the timeit module to test which of small snipps of code is faster python timeit for in range pass loops best of msec per loop python timeit for in xrange pass loops best of msec per loop personally always use range unless were dealing with really huge lists as you can see time wise for list of million entries the extra overhead is only seconds and as corey points out in python xrange will go away and range will give you nice iterator behaviour anyway
|
QA
|
how to load python module into fresh interactive she will in komodo when using pywin can easily load python file into fresh interactive she will and find this quite handy for prototyping and other exploratory tasks would like to use komodo as my python editor but have not found replacement for pywin ability to restart the she will and reload the current module how can do this in komodo it is also very important to me that when reload get fresh she will would prefer it if my previous interactions are in the she will history but it is more important to me that the memory be isolated from the previous versions and attempts
|
use komodo edit which might be little less sophisticated than full komodo create new command with python as the text of the command have this run in new console usually have the starting directory as the top of the project directory the option runs the file and drops into interactive python
|
QA
|
google app engine how can programmatically access the properties of my model class have model class class person db model first name db stringproperty required true last name db stringproperty required true have an instance of this class in and string contains the value first name would like to do something like print and new value both of which result in typeerror does anybody know how can achieve what would like
|
with much thanks to jim the exact solution was looking for is properties get value for datastore to all the other respondents thank you for your help also would have expected the model class to implement the python standard way of doing this but for whatever reason it does not
|
QA
|
django vs grails vs am wondering if there is such thing as django like ease of web app development combined with good deployment debugging and other tools django is very productive framework for building content heavy sites the best have tried and breath of fresh air compared to some of the java monstrosities out there however it is written in python which means there is little real support in the way of deployment packaging debugging profilers and other tools that make building and maintaining applications much easier ruby has similar issues and although do like ruby much better than like python get the impression that rails is roughly in the same boat at django when it comes to managing supporting the app has anyone here tried both django and grails or other web frameworks for non trivial projects how did they compare
|
the good deployment issue for python does not have the deep significance that it has for java python deployment for django is basically move the files you can run straight out of the subversion trunk directory if you want to you can without breaking much of sweat using the python distutils and build yourself distribution kit that puts your django apps into python site packages am not big fan of it but it is really easy to do since my stuff runs in linux have simple install py scripts that move stuff out of the subversion directories into opt this and opt that directories use an explicit path settings in my apache configuration to name those directories where the applications live patching can be done by editing the files in place bad policy prefer to edit in the svn location and rerun my little install to be sure actually have all the files under control
|
QA
|
does an application wide exception handler make sense long story short have substantial python application that among other things does outcalls to losetup mount etc on linux essentially consuming system resources that must be released when complete if my application crashes want to ensure these system resources are properly released does it make sense to do something like the following def main todo main application entry point pass def cleanup todo release system resources here pass if name main try main except cleanup raise is this something that is typically done is there better way perhaps the destructor in singleton class
|
if you use classes you should free the resources they allocate in their destructors instead of course use the try on entire application just if you want to free resources that are not already liberated by your classes destructors and instead of using catch all except you should use the following block try main finally cleanup that will ensure cleanup in more pythonic way
|
QA
|
how do use django templates without the rest of django want to use the django template engine in my python code but am not building django based web site how do use it without having settings py file and others and having to set the django settings module environment variable if run the following code import django template from django template import template context template my name is my name get importerror settings cannot be imported because environment variable django settings module is undefined
|
any particular reason you want to use django templates both jinja and genshi are in my opinion superior if you really want to then see the django documentation on settings py especially the section using settings without setting django settings module use something like this from django conf import settings settings configure foo bar your settings go here
|
QA
|
how do use django templates without the rest of django want to use the django template engine in my python code but am not building django based web site how do use it without having settings py file and others and having to set the django settings module environment variable if run the following code import django template from django template import template context template my name is my name get importerror settings cannot be imported because environment variable django settings module is undefined
|
google appengine uses the django templating engine have you taken look at how they do it you could possibly just use that
|
QA
|
how do use django templates without the rest of django want to use the django template engine in my python code but am not building django based web site how do use it without having settings py file and others and having to set the django settings module environment variable if run the following code import django template from django template import template context template my name is my name get importerror settings cannot be imported because environment variable django settings module is undefined
|
found this http snippets dzone com posts show
|
QA
|
how do use django templates without the rest of django want to use the django template engine in my python code but am not building django based web site how do use it without having settings py file and others and having to set the django settings module environment variable if run the following code import django template from django template import template context template my name is my name get importerror settings cannot be imported because environment variable django settings module is undefined
|
the solution is simple it is actually well documented but not too easy to find had to dig around it did not come up when tried few different google searches the following code works from django template import template context from django conf import settings settings configure template my name is my name context my name daryl spitzer render you my name is daryl spitzer see the django documentation linked above for description of some of the settings you may want to define as keyword arguments to configure
|
QA
|
what does blazeds livecycle data services do that something like pyamf or rubyamf not do am doing tech review and looking at amf integration with various backends rails python grails etc lots of options are out there question is what do the adobe products do blazeds etc that something like rubyamf pyamf do not
|
other than nio rtmp channels lcds include also the data management features using this feature you basically implement in an actionscript class crud like interface defined by lcds and you get automatic progressive list loading large lists datagrids loads while scrolling automatic crud management you get object locally in flash modify it send it back and db will get updated automatically feature for conflict resolution if multiple user try to updated the same record at the same time if remember well also some improved integration with the livecycle es workflow engine am going to it can be very fast to develop this way but only if you have only basic requirements and simple architecture forget soa that otherwise works so well with flex am fine with blazeds
|
QA
|
how do use django templates without the rest of django want to use the django template engine in my python code but am not building django based web site how do use it without having settings py file and others and having to set the django settings module environment variable if run the following code import django template from django template import template context template my name is my name get importerror settings cannot be imported because environment variable django settings module is undefined
|
jinja syntax is pretty much the same as django with very few differences and you get much more powerfull template engine which also compiles your template to bytecode fast use it for templating including in django itself and it is very good you can also easily write extensions if some feature you want is missing here is some demonstration of the code generation import jinja print jinja environment compile for row in data row name upper endfor raw true from future import division from jinja runtime import loopcontext context templatereference macro markup templateruntimeerror missing concat escape markup join unicode join name none def root context environment environment data context resolve data environment filters upper if yield none for row in data if yield none yield unicode environment getattr row name blocks debug info
|
QA
|
how do use django templates without the rest of django want to use the django template engine in my python code but am not building django based web site how do use it without having settings py file and others and having to set the django settings module environment variable if run the following code import django template from django template import template context template my name is my name get importerror settings cannot be imported because environment variable django settings module is undefined
|
echo the above statements jinja is pretty good superset of django templates for general use think they are working on making the django templates little less coupled to the settings py but jinja should do well for you
|
QA
|
where can learn more about pypy translation function have been having hard time trying to understand pypy translation it looks like something absolutely revolutionary from simply reading the description however am hard pressed to find good documentation on actually translating real world piece of code to something such as llvm does such thing exist the official pypy documentation on it just skims over the functionality rather than providing anything can try out myself
|
if you want some hand on examples pypy getting started document has section titled trying out the translator
|
QA
|
what is the best solution for database connection pooling in python have developed some custom dao like classes to meet some very specialized requirements for my project that is server side process that does not run inside any kind of framework the solution works great except that every time new request is made open new connection via mysqldb connect what is the best drop in solution to switch this over to using connection pooling in python am imagining something like the commons dbcp solution for java the process is long running and has many threads that need to make requests but not all at the same time specifically they do quite lot of work before brief bursts of writing out chunk of their results edited to add after some more searching found anitpool py which looks decent but as am relatively new to python guess just want to make sure am not missing more obvious more idiomatic better solution
|
wrap your connection class set limit on how many connections you make return an unused connection intercept close to free the connection update put something like this in dbpool py import sqlalchemy pool as pool import mysqldb as mysql mysql pool manage mysql
|
QA
|
what is the best solution for database connection pooling in python have developed some custom dao like classes to meet some very specialized requirements for my project that is server side process that does not run inside any kind of framework the solution works great except that every time new request is made open new connection via mysqldb connect what is the best drop in solution to switch this over to using connection pooling in python am imagining something like the commons dbcp solution for java the process is long running and has many threads that need to make requests but not all at the same time specifically they do quite lot of work before brief bursts of writing out chunk of their results edited to add after some more searching found anitpool py which looks decent but as am relatively new to python guess just want to make sure am not missing more obvious more idiomatic better solution
|
am going to the more obvious more idiomatic better solution is to use an existing orm rather than invent dao like classes it appears to me that orm are more popular than raw sql connections why because python is oo and the mapping from sql row to to object is absolutely essential there are not many cases where you deal with sql rows that do not map to python objects think that sqlalchemy or sqlobject and the associated connection pooling the more idiomatic pythonic solution pooling as separate feature is not very common because pure sql without object mapping is not very popular for the kind of complex long running processes that benefit from connection pooling yes pure sql is used but it is always used in simpler or more controlled applications where pooling is not helpful think you might have two alternatives revise your classes to use sqlalchemy or sqlobject while this appears painful at first all that work wasted you should be able to leverage all the design and thought and it is merely an exercise in adopting widely used orm and pooling solution roll your own simple connection pool using the algorithm you outlined simple set or list of connections that you cycle through
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
why not just use sympy it should do what you are trying to achieve
|
QA
|
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
|
alexandru suggestion of using class constants for enums works quite well also like to add dictionary for each set of constants to lookup human readable string representation this serves two purposes it provides simple way to pretty print your enum and the dictionary logically groups the constants so that you can test for membership class animal type dog type cat type str type dog dog type cat cat def init self type assert type in self type str keys self type type def repr self return type self class name self type str self type upper
|
QA
|
what is the best solution for database connection pooling in python have developed some custom dao like classes to meet some very specialized requirements for my project that is server side process that does not run inside any kind of framework the solution works great except that every time new request is made open new connection via mysqldb connect what is the best drop in solution to switch this over to using connection pooling in python am imagining something like the commons dbcp solution for java the process is long running and has many threads that need to make requests but not all at the same time specifically they do quite lot of work before brief bursts of writing out chunk of their results edited to add after some more searching found anitpool py which looks decent but as am relatively new to python guess just want to make sure am not missing more obvious more idiomatic better solution
|
in mysql would say do not bother with the connection pooling they are often source of trouble and with mysql they are not going to bring you the performance advantage you are hoping for this road may be lot of effort to follow politically because there is so much best practices hand waving and textbook verbiage in this space about the advantages of connection pooling connection pools are simply bridge between the post web era of stateless applications http protocol and the pre web era of stateful long lived batch processing applications since connections were very expensive in pre web databases since no one used to care too much about how long connection took to establish post web applications devised this connection pool scheme so that every hit did not incur this huge processing overhead on the rdbms since mysql is more of web era rdbms connections are extremely lightweight and fast have written many high volume web applications that do not use connection pool at all for mysql this is complication you may benefit from doing without so long as there is not political obstacle to overcome
|
QA
|
what does blazeds livecycle data services do that something like pyamf or rubyamf not do am doing tech review and looking at amf integration with various backends rails python grails etc lots of options are out there question is what do the adobe products do blazeds etc that something like rubyamf pyamf do not
|
the data management features for lcds described here are certainly valid however believe they do not let you actually develop solution faster developer still has to write all the data access code query execution extracting data from datareaders into value objects all of this has been solved dozen of times with code generators for instance the data management approach in weborb for java much like in weborb for net and php is based on code generation which creates code for both client side and server side you get all the actionscript apis out of the code generator to do full crud additionally weborb provides video streaming and real time messaging features and goes way beyond what both blazeds and lcds offer combined especially considering that the product is free just google it
|
QA
|
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
|
the pickle module is pretty awesome
|
QA
|
what is metaclass in python what are metaclasses what do you use them for
|
metaclasses are the secret sauce that make class work the default metaclass for new style object is called type class type object type object the object type type name bases dict new type metaclasses take args name bases and dict here is where the secret starts look for where name bases and the dict come from in this example class definition class thisisthename bases are here all the code here def doesis create dict let us define metaclass that will demonstrate how class calls it def test metaclass name bases dict print the class name is name print the class bases are bases print the dict has len dict elems the keys are dict keys return yellow class testname object none int metaclass test metaclass foo def baz self arr pass print testname repr testname output the class name is testname the class bases are type object none type int the dict has elems the keys are baz module foo metaclass testname yellow and now an example that actually means something this will automatically make the variables in the list attributes set on the class and set to none def init attributes name bases dict if attributes in dict for attr in dict attributes dict attr none return type name bases dict class initialised object metaclass init attributes attributes foo bar baz print foo initialised foo output foo none note that the magic behaviour that initalised gains by having the metaclass init attributes is not passed onto subclass of initalised here is an even more concrete example showing how you can subclass type to make metaclass that performs an action when the class is created this is quite tricky class metasingleton type instance none def call cls args kw if cls instance is none cls instance super metasingleton cls call args kw return cls instance class foo object metaclass metasingleton foo foo assert is
|
QA
|
what is metaclass in python what are metaclasses what do you use them for
|
think the onlamp introduction to metaclass programming is well written and gives really good introduction to the topic despite being several years old already http www onlamp com pub python metaclasses html in short class is blueprint for the creation of an instance metaclass is blueprint for the creation of class it can be easily seen that in python classes need to be first class objects too to enable this behavior have never written one myself but think one of the nicest uses of metaclasses can be seen in the django framework the model classes use metaclass approach to enable declarative style of writing new models or form classes while the metaclass is creating the class all members get the possibility to customize the class itself creating new model the metaclass enabling this the thing that is left to say is if you do not know what metaclasses are the probability that you will not need them is
|
QA
|
what is metaclass in python what are metaclasses what do you use them for
|
one use for metaclasses is adding new properties and methods to an instance automatically for example if you look at django models their definition looks bit confusing it looks as if you are only defining class properties class person models model first name models charfield max length last name models charfield max length however at runtime the person objects are filled with all sorts of useful methods see the source for some amazing metaclassery
|
QA
|
what is metaclass in python what are metaclasses what do you use them for
|
metaclass is the class of class like class defines how an instance of the class behaves metaclass defines how class behaves class is an instance of metaclass while in python you can use arbitrary callables for metaclasses like jerub shows the more useful approach is actually to make it an actual class itself type is the usual metaclass in python in case you are wondering yes type is itself class and it is its own type you will not be able to recreate something like type purely in python but python cheats little to create your own metaclass in python you really just want to subclass type metaclass is most commonly used as class factory like you create an instance of the class by calling the class python creates new class when it executes the class statement by calling the metaclass combined with the normal init and new methods metaclasses therefore allow you to do extra things when creating class like registering the new class with some registry or even replace the class with something else entirely when the class statement is executed python first executes the body of the class statement as normal block of code the resulting namespace dict holds the attributes of the class to be the metaclass is determined by looking at the baseclasses of the class to be metaclasses are inherited at the metaclass attribute of the class to be if any or the metaclass global variable the metaclass is then called with the name bases and attributes of the class to instantiate it however metaclasses actually define the type of class not just factory for it so you can do much more with them you can for instance define normal methods on the metaclass these metaclass methods are like classmethods in that they can be called on the class without an instance but they are also not like classmethods in that they cannot be called on an instance of the class type subclasses is an example of method on the type metaclass you can also define the normal magic methods like add iter and getattr to implement or change how the class behaves here is an aggregated example of the bits and pieces def make hook decorator to turn foo method into foo is hook return class mytype type def new cls name bases attrs if name startswith none return none go over attributes and see if they should be renamed newattrs for attrname attrvalue in attrs iteritems if getattr attrvalue is hook newattrs attrname attrvalue else newattrs attrname attrvalue return super mytype cls new cls name bases newattrs def init self name bases attrs super mytype self init name bases attrs classregistry register self self interfaces print would register class now self def add self other class autoclass self other pass return autoclass alternatively to autogenerate the classname as well as the class return type self name other name self other def unregister self classregistry unregister self print would unregister class now self class myobject metaclass mytype class nonesample myobject pass will print nonetype none print type nonesample repr nonesample class example myobject def init self value self value value make hook def add self other return self class self value other value will unregister the class example unregister inst example will fail with an attributeerror inst unregister print inst inst class sibling myobject pass examplesibling example sibling examplesibling is now subclass of both example and sibling with no content of its own although it will believe it is called autoclass print examplesibling print examplesibling mro
|
QA
|
what is the standard way to add seconds to datetime time in python given datetime time value in python is there standard way to add an integer number of seconds to it so that for example these obvious ideas do not work datetime time typeerror unsupported operand type for datetime time and int datetime time datetime timedelta typeerror unsupported operand type for datetime time and datetime timedelta datetime time datetime time typeerror unsupported operand type for datetime time and datetime time in the end have written functions like this def add secs to time timeval secs to add secs timeval hour timeval minute timeval second secs secs to add return datetime time secs secs secs cannot help thinking that am missing an easier way to do this though related python time timedelta equivalent
|
try adding datetime datetime to datetime timedelta if you only want the time portion you can call the time method on the resultant datetime datetime object to get it
|
QA
|
how do split string into list if have this string what is the most efficient approach for creating this list
|
this is parsing problem so neither regex not split are the good solution use parser generator instead would look closely at pyparsing there have also been some decent articles about pyparsing in the python magazine
|
QA
|
what is the standard way to add seconds to datetime time in python given datetime time value in python is there standard way to add an integer number of seconds to it so that for example these obvious ideas do not work datetime time typeerror unsupported operand type for datetime time and int datetime time datetime timedelta typeerror unsupported operand type for datetime time and datetime timedelta datetime time datetime time typeerror unsupported operand type for datetime time and datetime time in the end have written functions like this def add secs to time timeval secs to add secs timeval hour timeval minute timeval second secs secs to add return datetime time secs secs secs cannot help thinking that am missing an easier way to do this though related python time timedelta equivalent
|
you can use full datetime variables with timedelta and by providing dummy date then using time to just get the time value for example import datetime datetime datetime datetime timedelta days seconds then other fields print time print time results in the two values three seconds apart you could also opt for the more readable datetime timedelta seconds if you are so inclined if you are after function that can do this you can look into using addsecs below import datetime def addsecs tm secs fulldate datetime datetime tm hour tm minute tm second fulldate fulldate datetime timedelta seconds secs return fulldate time datetime datetime now time addsecs print print this outputs
|
QA
|
how can analyze python code to identify problematic areas have large source repository split across multiple projects would like to produce report about the health of the source code identifying problem areas that need to be addressed specifically would like to call out routines with high cyclomatic complexity identify repetition and perhaps run some lint like static analysis to spot suspicious and thus likely erroneous constructs how might go about constructing such report
|
for static analysis there is pylint and pychecker personally use pylint as it seems to be more comprehensive than pychecker for cyclomatic complexity you can try this perl program or this article which introduces python program to do the same
|
QA
|
what is the standard way to add seconds to datetime time in python given datetime time value in python is there standard way to add an integer number of seconds to it so that for example these obvious ideas do not work datetime time typeerror unsupported operand type for datetime time and int datetime time datetime timedelta typeerror unsupported operand type for datetime time and datetime timedelta datetime time datetime time typeerror unsupported operand type for datetime time and datetime time in the end have written functions like this def add secs to time timeval secs to add secs timeval hour timeval minute timeval second secs secs to add return datetime time secs secs secs cannot help thinking that am missing an easier way to do this though related python time timedelta equivalent
|
one little thing might add clarity to override the default value for seconds datetime timedelta seconds datetime datetime
|
QA
|
django sessions am looking at sessions in django and by default they are stored in the database what are the benefits of filesystem and cache sessions and when should use them
|
one thing that has to be considered when choosing session backend is how often session data is modified even sites with moderate traffic will suffer if session data is modified on each request making many database trips to store and retrieve data in my previous work we used memcache as session backend exclusively and it worked really well our administrative team put really great effort in making two special memcached instances stable as rock but after bit of twiddling with initial setup we did not have any interrupts of session backends operations
|
QA
|
how can analyze python code to identify problematic areas have large source repository split across multiple projects would like to produce report about the health of the source code identifying problem areas that need to be addressed specifically would like to call out routines with high cyclomatic complexity identify repetition and perhaps run some lint like static analysis to spot suspicious and thus likely erroneous constructs how might go about constructing such report
|
thanks to pydev you can integrate pylint in the eclipse ide really easily and get code report each time you save modified file
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
in the first test python try to convert the object to bool value if it is not already one roughly we are asking the object are you meaningful or not this is done using the following algorithm if the object has nonzero special method as do numeric built ins int and float it calls this method it must either return bool value which is then directly used or an int value that is considered false if equal to zero otherwise if the object has len special method as do container built ins list dict set tuple it calls this method considering container false if it is empty length is zero otherwise the object is considered true unless it is none in which case it is considered false in the second test the object is compared for equality to none here we are asking the object are you equal to this other value this is done using the following algorithm if the object has eq method it is called and the return value is then converted to boolvalue and used to determine the outcome of the if otherwise if the object has cmp method it is called this function must return an int indicating the order of the two object if self other if self other if self other otherwise the object are compared for identity ie they are reference to the same object as can be tested by the is operator there is another test possible using the is operator we would be asking the object are you this particular object generally would recommend to use the first test with non numerical values to use the test for equality when you want to compare objects of the same nature two strings two numbers and to check for identity only when using sentinel values none meaning not initialized for member field for exemple or when using the getattr or the getitem methods to summarize we have class object def repr self return def nonzero self return false class object def repr self return def len self return class object def repr self return def cmp self other return class object def repr self return would def eq self other return true for obj in none print bool obj obj none obj is none repr obj bool obj obj none obj is none bool obj false obj none false obj is none false bool obj false obj none false obj is none false bool obj false obj none false obj is none false bool obj false obj none false obj is none false bool obj false obj none false obj is none false bool obj false obj none false obj is none false bool obj false obj none false obj is none false bool obj false obj none false obj is none false bool obj true obj none true obj is none false bool obj true obj none true obj is none false none bool obj false obj none true obj is none true
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
because none is not the only thing that is considered false if not false print false is false if not print is false if not print an empty list is false if not print an empty tuple is false if not print an empty dict is false if not print an empty string is false false and are all different from none so your two code snippets are not equivalent moreover consider the following false true false false if object is not an equality check none etc are all different from each other but they all evaluate to false this is the magic behind short circuiting expressions like foo bar and spam or eggs which is shorthand for if bar foo spam else foo eggs although you really should write foo spam if bar else egg
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
these two comparisons serve different purposes the former checks for boolean value of something the second checks for identity with none value
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
for one the first example is shorter and looks nicer as per the other posts what you choose also depends on what you really want to do with the comparison
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
style guide recommends to use is or is not if you are testing for none ness comparisons to singletons like none should always be done with is or is not never the equality operators on the other hand if you are testing for more than none ness you should use the boolean operator
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
the answer is it depends use the first example if consider and false list not exhaustive to be equivalent to none in this context
|
QA
|
what is the standard way to add seconds to datetime time in python given datetime time value in python is there standard way to add an integer number of seconds to it so that for example these obvious ideas do not work datetime time typeerror unsupported operand type for datetime time and int datetime time datetime timedelta typeerror unsupported operand type for datetime time and datetime timedelta datetime time datetime time typeerror unsupported operand type for datetime time and datetime time in the end have written functions like this def add secs to time timeval secs to add secs timeval hour timeval minute timeval second secs secs to add return datetime time secs secs secs cannot help thinking that am missing an easier way to do this though related python time timedelta equivalent
|
thanks to pax diablo bvmou and arachnid for the suggestion of using full datetimes throughout if have to accept datetime time objects from an external source then this seems to be an alternative add secs to time function def add secs to time timeval secs to add dummy date datetime date full datetime datetime datetime combine dummy date timeval added datetime full datetime datetime timedelta seconds secs to add return added datetime time this verbose code can be compressed to this one liner datetime datetime combine datetime date timeval datetime timedelta seconds secs to add time but think would want to wrap that up in function for code clarity anyway
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
personally chose consistent approach across languages do if var or equivalent only if var is declared as boolean or defined as such in we do not have specific type even prefix these variables with so it would be bvar actually to be sure will not accidentally use another type here do not really like implicit casting to boolean even less when there are numerous complex rules of course people will disagree some go farther see if bvar true in the java code at my work too redundant for my taste others love too much compact syntax going while line getnextline too ambiguous for me
|
QA
|
python on windows how to wait for multiple child processes how to wait for multiple child processes in python on windows without active wait polling something like this almost works for me proc subprocess popen python mytest py proc subprocess popen python mytest py proc wait print finished proc wait print finished the problem is that when proc finishes before proc the parent process will still wait for proc on unix one would use waitpid in loop to get the child processes return codes as they finish how to achieve something like this in python on windows
|
it might seem overkill but here it goes import queue thread subprocess results queue queue def process waiter popen description que try popen wait finally que put description popen returncode process count proc subprocess popen python mytest py thread start new thread process waiter proc finished results process count proc subprocess popen python mytest py thread start new thread process waiter proc finished results process count etc while process count description rc results get print job description ended with rc rc process count
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
these are actually both poor practices once upon time it was considered ok to casually treat none and false as similar however since python this is not the best policy first when you do an if or if not kind of test python has to implicitly convert to boolean the rules for the bool function describe raft of things which are false everything else is true if the value of was not properly boolean to begin with this implicit conversion is not really the clearest way to say things before python there was no bool function so it was even less clear second you should not really test with none you should use is none and is not none see pep style guide for python code comparisons to singletons like none should always be done with is or is not never the equality operators also beware of writing if when you really mean if is not none when testing whether variable or argument that defaults to none was set to some other value the other value might have type such as container that could be false in boolean context how many singletons are there five none true false notimplemented and ellipsis since you are really unlikely to use notimplemented or ellipsis and you would never say if is true because simply if is lot clearer you will only ever test none
|
QA
|
why is if not someobj better than if someobj none in python have seen several examples of code like this if not someobj do something but am wondering why not doing if someobj none do something is there any difference does one have an advantage over the other
|
if you ask if not spam print sorry no spam the nonzero method of spam gets called from the python manual nonzero self called to implement truth value testing and the built in operation bool should return false or true or their integer equivalents or when this method is not defined len is called if it is defined see below if class defines neither len nor nonzero all its instances are considered true if you ask if spam none print sorry no spam here either the eq method of spam gets called with the argument none for more information of the customization possibilities have look at the python documenation at https docs python org reference datamodel html basic customization
|
QA
|
if it is decided that our system needs an overhaul what is the best way to go about it we are mainting web application that is built on classic asp using vbscript as the primary language we are in agreement that our backend framework if you will is out dated and does not provide us with the proper tools to move forward in quick manner we have pretty much embraced the current webmvc pattern that is all over the place and cannot do it in reasonable manner with the current technology the big missing features are proper dispatching and templating with inheritance amongst others currently there are two paths being discussed port the existing application to classic asp using jscript which will allow us to hopefully go from there to net msjscript without too much trouble and eventually end up on the net platform preferably the mvc stuff will be done by then asp net is not much better than were we are on now in our opinions this has been argued as the safer path with less risk than the next option albeit it might take slightly longer completely rewrite the application using some other technology right now the leader of the pack is python wsgi with custom framework orm and good templating solution there is wiggle room here for even django and other pre built solutions this method would hopefully be the quickest solution as we would probably run beta beside the actual product but it does have the potential for big waste of time if we cannot do not get it right this does not mean that our logic is gone as what we have built over the years is fairly stable as noted just difficult to deal with it is built on sql server with heavy use of stored procedures and published on iis just for little more background now the question has anyone taken either of the two paths above if so was it successful how could it have been better etc we are not looking to deviate much from doing one of those two things but some suggestions or other solutions would potentially be helpful
|
half year ago took over large web application fortunately already in python which had some major architectural deficiencies templates and code mixed code duplication you name it my plan is to eventually have the system respond to wsgi but am not there yet found the best way to do it is in small steps over the last month code reuse has gone up and progress has accelerated general principles which have worked for me throw away code which is not used or commented out throw away all comments which are not useful define layer hierarchy models business logic view controller logic display logic etc of your application this has not to be very clear cut architecture but rather should help you think about the various parts of your application and help you better categorize your code if something grossly violates this hierarchy change the offending code move the code around recode it at another place etc at the same time adjust the rest of your application to use this code instead of the old one throw the old one away if not used anymore keep you apis simple progress can be painstakingly slow but should be worth it
|
QA
|
building python extension modules for windows have extension module and it would be nice to distribute built binaries setuptools makes it easy to build extensions modules on os and gnu linux since those oss come with gcc but do not know how to do it in windows would need to buy copy of visual studio or does visual studio express work can just use cygwin or mingw
|
you can use both mingw and vc express free no need to buy it see http eli thegreenplace net compiling python extensions with distutils and mingw http eli thegreenplace net creating python extension modules in
|
QA
|
building python extension modules for windows have extension module and it would be nice to distribute built binaries setuptools makes it easy to build extensions modules on os and gnu linux since those oss come with gcc but do not know how to do it in windows would need to buy copy of visual studio or does visual studio express work can just use cygwin or mingw
|
setuptools and distutils do not come with gcc but they use the same compiler python was built with the difference is mostly that on the typical unix system that compiler is gcc and you have it installed in order to compile extension modules on windows you need compiler for windows msvs will do even the express version believe but it does have to be the same msvc version as python was built with or you can use cygwin or mingw see the appropriate section of installing python modules
|
QA
|
how do read text from the windows clipboard from python how do read text from the windows clipboard from python
|
try win clipboard from the win all package that is probably installed if you are on activestate python see sample here http code activestate com recipes
|
QA
|
how do read text from the windows clipboard from python how do read text from the windows clipboard from python
|
you can use the module called win clipboard which is part of pywin here is an example that first sets the clipboard data then gets it import win clipboard set clipboard data win clipboard openclipboard win clipboard emptyclipboard win clipboard setclipboardtext testing win clipboard closeclipboard get clipboard data win clipboard openclipboard data win clipboard getclipboarddata win clipboard closeclipboard print data an important reminder from the documentation when the window has finished examining or changing the clipboard close the clipboard by calling closeclipboard this enables other windows to access the clipboard do not place an object on the clipboard after calling closeclipboard
|
QA
|
is there zip like method in net in python there is really neat function called zip which can be used to iterate through two lists at the same time list list for in zip list list print the above code shoul produce the following wonder if there is method like it available in net am thinking about writing it myself but there is no point if it is already available
|
nope there is no such function in net you have roll out your own note that does not support tuples so python like syntax sugar is missing too you can use something like this class pair public first get set public second get set static ienumerable pair zip ienumerable first ienumerable second if first count second count throw new argumentexception blah blah using ienumerator first getenumerator using ienumerator second getenumerator while movenext movenext yield return new pair first current second current var ints new int var strings new string foreach var pair in zip ints strings console writeline pair first pair second
|
QA
|
is there zip like method in net in python there is really neat function called zip which can be used to iterate through two lists at the same time list list for in zip list list print the above code shoul produce the following wonder if there is method like it available in net am thinking about writing it myself but there is no point if it is already available
|
update it is built in in as system linq enumerable zip method here is version ienumerable tresult zip tresult ienumerable ienumerable func tresult combine using var getenumerator using var getenumerator while movenext movenext yield return combine current current dropped the version as it was showing its age
|
QA
|
is there zip like method in net in python there is really neat function called zip which can be used to iterate through two lists at the same time list list for in zip list list print the above code shoul produce the following wonder if there is method like it available in net am thinking about writing it myself but there is no point if it is already available
|
as far as know there is not wrote one for myself as well as few other useful extensions and put them in project called nextension on codeplex apparently the parallel extensions for net have zip function here is simplified version from nextension but please check it out for more useful extension methods public static ienumerable tresult zip tresult this ienumerable source ienumerable source func tresult combine using ienumerator data source getenumerator using ienumerator data source getenumerator while data movenext data movenext yield return combine data current data current usage int list new int string list new string foreach var result in list zip list tostring console writeline result
|
QA
|
is there zip like method in net in python there is really neat function called zip which can be used to iterate through two lists at the same time list list for in zip list list print the above code shoul produce the following wonder if there is method like it available in net am thinking about writing it myself but there is no point if it is already available
|
there is also one in let zipped seq zip firstenumeration secondenumation
|
QA
|
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
|
complex numbers the complexobject defines class so technically it is not module great for coordinates with easy translation rotations etc eg turn left turn right coord print coord turn left
|
QA
|
ironclad equivalent for jython for ironpython there is project ironclad that aims to transparently run extensions in it is there similiar project for jython
|
you can probably use java loadlibrary to do that provided it works in your platform java it is in the java library java system loadlibrary note that sometimes you will have to write wrapper in and or in java depending on the library you want to use and target system since details are platform dependant refer to the documentation for more details
|
QA
|
is there way to run python on android we are working on an version and this platform has nice python api however there is nothing official about python on android but since jython exists is there way to let the snake and the robot work together
|
not at the moment and you would be lucky to get jython to work soon if you are planning to start your development now you would be better off with just sticking to java for now on
|
QA
|
what is the standard way to add seconds to datetime time in python given datetime time value in python is there standard way to add an integer number of seconds to it so that for example these obvious ideas do not work datetime time typeerror unsupported operand type for datetime time and int datetime time datetime timedelta typeerror unsupported operand type for datetime time and datetime timedelta datetime time datetime time typeerror unsupported operand type for datetime time and datetime time in the end have written functions like this def add secs to time timeval secs to add secs timeval hour timeval minute timeval second secs secs to add return datetime time secs secs secs cannot help thinking that am missing an easier way to do this though related python time timedelta equivalent
|
as others here have stated you can just use full datetime objects throughout sometime get some time the time to which you want to add seconds later datetime combine date today sometime timedelta seconds time however think it is worth explaining why full datetime objects are required consider what would happen if added hours to pm what is the correct behavior an exception because you cannot have time larger than pm should it wrap back around different programmers will expect different things so whichever result they picked would surprise lot of people worse yet programmers would write code that worked just fine when they tested it initially and then have it break later by doing something unexpected this is very bad which is why you are not allowed to add timedelta objects to time objects
|
QA
|
how do you access an authenticated google app engine service from non web python client have google app engine app http mylovelyapp appspot com it has page mylovelypage for the moment the page just does self response out write ok if run the following python at my computer import urllib urllib urlopen http mylovelyapp appspot com mylovelypage read print close it prints ok the problem is if add login required to this page in the app yaml then this prints out the html of the google accounts login page have tried normal authentication approaches passman urllib httppasswordmgrwithdefaultrealm auth handler urllib httpbasicauthhandler auth handler add password none uri http mylovelyapp appspot com mylovelypage user billy bob gmail com passwd billybobspasswd opener urllib build opener auth handler urllib install opener opener but it makes no difference still get the login page html back have tried google clientlogin auth api but cannot get it to work httplib http auth uri https www google com accounts clientlogin headers content type application www form urlencoded myrequest email passwd service ah source dalelane billy bob gmail com billybobspassword response content request auth uri post body myrequest headers headers if response status authtok re search auth content group headers headers authorization googlelogin auth authtok strip headers content length response content request http mylovelyapp appspot com mylovelypage post body headers headers while response status response content request response location post body headers headers print content do seem to be able to get some token correctly but attempts to use it in the header when call mylovelypage still just return me the login page html can anyone help please could use the gdata client library to do this sort of thing from what have read think it should be able to access app engine apps but have not been any more successful at getting the authentication working for app engine stuff there either any pointers to samples articles or even just keywords should be searching for to get me started would be very much appreciated thanks
|
am not too familiar with appengine or googles web apis but for brute force approach you could write script with something like mechanize http wwwsearch sourceforge net mechanize to simply walk through the login process before you begin doing the real work of the client
|
QA
|
accessing mp meta data with python what is the best way to retrieve mp metadata in python have seen couple frameworks out there but am unsure as to which would be the best to use any ideas
|
used eyed the other day with lot of success found that it could add artwork to the id tag which the other modules looked at could not you will have to download the tar and execute python setup py install from the source folder relevant examples from the website are below reading the contents of an mp file containing either or tag info import eyed tag eyed tag tag link some file mp print tag getartist print tag getalbum print tag gettitle read an mp file track length bitrate etc and access it is tag if eyed ismp file audiofile eyed mp audiofile tag audiofile gettag specific tag versions can be selected tag link some file mp eyed id tag link some file mp eyed id tag link some file mp eyed id any version the default or you can iterate over the raw frames tag eyed tag tag link some file mp for frame in tag frames print frame once tag is linked to file it can be modified and saved tag setartist you cro mags tag setalbum you age of quarrel tag update if the tag linked in was and you would like to save it as tag update eyed id read in tag and remove it from the file tag link some file mp tag remove tag update add new tag tag eyed tag tag link some file mp no tag in this file link returned false tag header setversion eyed id tag setartist fugazi tag update
|
QA
|
sorting dict on iter am trying to sort dict based on its key and return an iterator to the values from within an overridden iter method in class is there nicer and more efficient way of doing this than creating new list inserting into the list as sort through the keys
|
by far the easiest approach and almost certainly the fastest is something along the lines of def sorted dict keys keys keys sort for key in keys yield key you cannot sort without fetching all keys fetching all keys into list and then sorting that list is the most efficient way to do that list sorting is very fast and fetching the keys list like that is as fast as it can be you can then either create new list of values or yield the values as the example does keep in mind that you cannot modify the dict if you are iterating over it the next iteration would fail so if you want to modify the dict before you are done with the result of sorted dict make it return list
|
QA
|
sorting dict on iter am trying to sort dict based on its key and return an iterator to the values from within an overridden iter method in class is there nicer and more efficient way of doing this than creating new list inserting into the list as sort through the keys
|
how about something like this def itersorted for key in sorted yield key
|
QA
|
how do you access an authenticated google app engine service from non web python client have google app engine app http mylovelyapp appspot com it has page mylovelypage for the moment the page just does self response out write ok if run the following python at my computer import urllib urllib urlopen http mylovelyapp appspot com mylovelypage read print close it prints ok the problem is if add login required to this page in the app yaml then this prints out the html of the google accounts login page have tried normal authentication approaches passman urllib httppasswordmgrwithdefaultrealm auth handler urllib httpbasicauthhandler auth handler add password none uri http mylovelyapp appspot com mylovelypage user billy bob gmail com passwd billybobspasswd opener urllib build opener auth handler urllib install opener opener but it makes no difference still get the login page html back have tried google clientlogin auth api but cannot get it to work httplib http auth uri https www google com accounts clientlogin headers content type application www form urlencoded myrequest email passwd service ah source dalelane billy bob gmail com billybobspassword response content request auth uri post body myrequest headers headers if response status authtok re search auth content group headers headers authorization googlelogin auth authtok strip headers content length response content request http mylovelyapp appspot com mylovelypage post body headers headers while response status response content request response location post body headers headers print content do seem to be able to get some token correctly but attempts to use it in the header when call mylovelypage still just return me the login page html can anyone help please could use the gdata client library to do this sort of thing from what have read think it should be able to access app engine apps but have not been any more successful at getting the authentication working for app engine stuff there either any pointers to samples articles or even just keywords should be searching for to get me started would be very much appreciated thanks
|
appcfg py the tool that uploads data to app engine has to do exactly this to authenticate itself with the app engine server the relevant functionality is abstracted into appengine rpc py in nutshell the solution is use the google clientlogin api to obtain an authentication token appengine rpc py does this in getauthtoken send the auth token to special url on your app engine app that page then returns cookie and redirect ignore the redirect and store the cookie appcfg py does this in getauthcookie use the returned cookie in all future requests you may also want to look at authenticate to see how appcfg handles the various return codes from clientlogin and getopener to see how appcfg creates urllib openerdirector that does not follow http redirects or you could in fact just use the abstractrpcserver and httprpcserver classes wholesale since they do pretty much everything you need
|
QA
|
what is good way to find relative paths in google app engine so have done the trivial warmup apps with gae now would like to build something with more complex directory structure something along the lines of siteroot models controllers controller controller templates template template etc the controllers will be python modules handling requests they would then need to locate django style templates in associated folders most of the demo apps have seen resolve template paths like this path os path join os path dirname file mypage html the file property resolves to the currently executing script so in my above example if python script were running in controllers controller then the mypage html would resolve to that same directory controllers controller mypage html and would rather cleanly separate my python code and templates the solution have hacked together feels hacky base paths os path split os path dirname file template dir os path join base paths templates so am just snipping off the last element of the path for the currently running script and appending the template directory to the new path the other non gae specific solutions have seen for resolving python paths seem pretty heavyweight such as splitting paths into lists and manipulating accordingly django seems to have an answer for this but would rather stick to the gae api vs creating full django app and modifying it for gae am assuming anything hard coded would be non starter since the apps live on google infinite server farm so what is better way
|
you cannot use relative paths as toni suggests because you have no guarantee that the path from your working directory to your app directory will remain the same the correct solution is to either use os path split as you are or to use something like path os path join os path dirname file templates mypage html my usual approach is to generate path to the template directory using the above method and store it as member of my controller object and provide gettemplatepath method that takes the provided filename and joins it with the basename
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
see the motivation section in pep non obvious use of generators is creating interruptible functions which let us you do things like update ui or run several jobs simultaneously interleaved actually while not using threads
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
generators give you lazy evaluation you use them by iterating over them either explicitly with for or implicitly by passing it to any function or construct that iterates you can think of generators as returning multiple items as if they return list but instead of returning them all at once they return them one by one and the generator function is paused until the next item is requested generators are good for calculating large sets of results in particular calculations involving loops themselves where you do not know if you are going to need all results or where you do not want to allocate the memory for all results at the same time or for situations where the generator uses another generator or consumes some other resource and it is more convenient if that happened as late as possible another use for generators that is really the same is to replace callbacks with iteration in some situations you want function to do lot of work and occasionally report back to the caller traditionally you would use callback function for this you pass this callback to the work function and it would periodically call this callback the generator approach is that the work function now generator knows nothing about the callback and merely yields whenever it wants to report something the caller instead of writing separate callback and passing that to the work function does all the reporting work in little for loop around the generator for example say you wrote filesystem search program you could perform the search in its entirety collect the results and then display them one at time all of the results would have to be collected before you showed the first and all of the results would be in memory at the same time or you could display the results while you find them which would be more memory efficient and much friendlier towards the user the latter could be done by passing the result printing function to the filesystem search function or it could be done by just making the search function generator and iterating over the result if you want to see an example of the latter two approaches see os path walk the old filesystem walking function with callback and os walk the new filesystem walking generator of course if you really wanted to collect all results in list the generator approach is trivial to convert to the big list approach big list list the generator
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
basically avoiding call back functions when iterating over input maintaining state see here and here for an overview of what can be done using generators
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
one of the reasons to use generator is to make the solution clearer for some kind of solutions the other is to treat results one at time avoiding building huge lists of results that you would process separated anyway if you have fibonacci up to function like this function version def fibon result for in xrange result append return result you can more easily write the function as this generator version def fibon for in xrange yield the function is clearer and if you use the function like this for in fibon print in this example if using the generator version the whole item list will not be created at all just one value at time that would not be the case when using the list version where list would be created first
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
my favorite uses are filter and reduce operations let us say we are reading file and only want the lines which begin with def filter sharps asequence for in asequence if startswith yield we can then use the generator function in proper loop source file for line in filter sharps source readlines print line source close the reduce example is similar let us say we have file where we need to locate blocks of location location lines not html tags but lines that happen to look tag like def reducelocation asequence keep false block none for line in asequence if line startswith location block append line yield block block none keep false elif line startswith location block line keep true elif keep block append line else pass if block is not none yield block partial block icky again we can use this generator in proper for loop source file for in reducelocation source readlines print source close the idea is that generator function allows us to filter or reduce sequence producing another sequence one value at time
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
buffering when it is efficient to fetch data in large chunks but process it in small chunks then generator might help def bufferedfetch while true buffer getbigchunkofdata insert some code to break on end of data for in buffer yield the above let us you easily separate buffering from processing the consumer function can now just get the values one by one without worrying about buffering
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
piles of stuff any time you want to generate sequence of items but do not want to have to materialize them all into list at once for example you could have simple generator that returns prime numbers def primes primes found set primes found add yield for in itertools count candidate if not all candidate prime for prime in primes found primes found add candidate yield candidate you could then use that to generate the products of subsequent primes def prime products primeiter primes prev primeiter next for prime in primeiter yield prime prev prev prime these are fairly trivial examples but you can see how it can be useful for processing large potentially infinite datasets without generating them in advance which is only one of the more obvious uses
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
the simple explanation consider for statement for item in iterable do stuff lot of the time all the items in iterable does not need to be there from the start but can be generated on the fly as they are required this can be lot more efficient in both space you never need to store all the items simultaneously and time the iteration may finish before all the items are needed other times you do not even know all the items ahead of time for example for command in user input do stuff with command you have no way of knowing all the user commands beforehand but you can use nice loop like this if you have generator handing you commands def user input while true wait for command cmd get command yield cmd with generators you can also have iteration over infinite sequences which is of course not possible when iterating over containers
|
QA
|
what can you use python generator functions for am starting to learn python and have come across generator functions those that have yield statement in them want to know what types of problems that these functions are really good at solving
|
use generators when our web server is acting as proxy the client requests proxied url from the server the server begins to load the target url the server yields to return the results to the client as soon as it gets them
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
expanding on the dict as switch idea if you want to use default value for your switch def try return except keyerror return default
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
if you would like defaults you could use the dictionary get key default method def return get is default if not found
|
QA
|
sorting dict on iter am trying to sort dict based on its key and return an iterator to the values from within an overridden iter method in class is there nicer and more efficient way of doing this than creating new list inserting into the list as sort through the keys
|
def sorteddict dictobj return value for key value in sorted dictobj iteritems this will create single intermediate list the sorted method returns real list but at least it is only one
|
QA
|
how do you retrieve items from dictionary in the order that they are inserted is it possible to retrieve items from python dictionary in the order that they were inserted
|
it is not possible unless you store the keys in separate list for referencing later
|
QA
|
anyone used dabo for medium big project we are at the beginning of new erp ish client server application developed as python rich client we are currently evaluating dabo as our main framework and it looks quite nice and easy to use but was wondering has anyone used it for medium to big sized projects thanks for your time
|
have no dabo experience at all but this question is on the top of the list fo such long time that decided to give it shot framework selection assumptions medium to big project we are talking about team of more than people working on something for about year for the first phase this is usually an expensive and very important effort for the client this project will have significant amount of users around hundred so performance is essential it is an erp project so the application will work with large amounts of information you have no prior dabo experience in your team considerations could not open dabo project site right now there seems to be some server problem that alone would make me think twice about using it for big project it is not well known framework typing dabo in google returns almost no useful results it does not have wikipedia page all in all it is quite obscure it means that when you will have problems with it and you will have problems with it you will have almost no place to go your question was unanswered for days on so this alone would make me re consider if you base your project on an obscure technology you have no previous experience with it is huge risk you do not have people who know that framework in your team it means that you have to learn it to get any results at all and to master it will require quite significant amount of time you will have to factor that time into your project plan do you really need it what does this framework give you that you cannot do yourself quite lot of time my team tried to use some third party component or tool only to find that building custom one would be faster than dealing with third party problems and limitations there are brilliant tools available to people nowadays and we would be lost without them but you have to carefully consider if this tool is one of them dabo project version is do you know if they spend time optimising their code for performance at this stage did you run any tests to see it will sustain the load you have in your nfrs hope that helps good luck with your project
|
QA
|
how do you access an authenticated google app engine service from non web python client have google app engine app http mylovelyapp appspot com it has page mylovelypage for the moment the page just does self response out write ok if run the following python at my computer import urllib urllib urlopen http mylovelyapp appspot com mylovelypage read print close it prints ok the problem is if add login required to this page in the app yaml then this prints out the html of the google accounts login page have tried normal authentication approaches passman urllib httppasswordmgrwithdefaultrealm auth handler urllib httpbasicauthhandler auth handler add password none uri http mylovelyapp appspot com mylovelypage user billy bob gmail com passwd billybobspasswd opener urllib build opener auth handler urllib install opener opener but it makes no difference still get the login page html back have tried google clientlogin auth api but cannot get it to work httplib http auth uri https www google com accounts clientlogin headers content type application www form urlencoded myrequest email passwd service ah source dalelane billy bob gmail com billybobspassword response content request auth uri post body myrequest headers headers if response status authtok re search auth content group headers headers authorization googlelogin auth authtok strip headers content length response content request http mylovelyapp appspot com mylovelypage post body headers headers while response status response content request response location post body headers headers print content do seem to be able to get some token correctly but attempts to use it in the header when call mylovelypage still just return me the login page html can anyone help please could use the gdata client library to do this sort of thing from what have read think it should be able to access app engine apps but have not been any more successful at getting the authentication working for app engine stuff there either any pointers to samples articles or even just keywords should be searching for to get me started would be very much appreciated thanks
|
thanks to arachnid for the answer it worked as suggested here is simplified copy of the code in case it is helpful to the next person to try import os import urllib import urllib import cookielib users email address billy bob gmail com users password billybobspassword target authenticated google app engine uri http mylovelyapp appspot com mylovelypage my app name yay we use cookie to authenticate with google app engine by registering cookie handler here this will automatically store the cookie returned when we use urllib to open http currentcost appspot com ah login cookiejar cookielib lwpcookiejar opener urllib build opener urllib httpcookieprocessor cookiejar urllib install opener opener get an authtoken from google accounts auth uri https www google com accounts clientlogin authreq data urllib urlencode email users email address passwd users password service ah source my app name accounttype hosted or google auth req urllib request auth uri data authreq data auth resp urllib urlopen auth req auth resp body auth resp read auth response includes several fields we are interested in the bit after auth auth resp dict dict split for in auth resp body split if authtoken auth resp dict auth get cookie the call to request cookie will also automatically redirect us to the page that we want to go to the cookie jar will automatically provide the cookie when we reach the redirected location this is where actually want to go to serv uri target authenticated google app engine uri serv args serv args continue serv uri serv args auth authtoken full serv uri http mylovelyapp appspot com ah login urllib urlencode serv args serv req urllib request full serv uri serv resp urllib urlopen serv req serv resp body serv resp read serv resp body should contain the contents of the target authenticated google app engine uri page as we will have been redirected to that page automatically to prove this am just going to print it out print serv resp body
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
also tend to put my unit tests in the file itself as jeremy cantrell above notes although tend to not put the test function in the main body but rather put everything in an if name main do tests block this ends up adding documentation to the file as example code for how to use the python file you are testing should add tend to write very tight modules classes if your modules require very large numbers of tests you can put them in another but even then would still add if name main import tests thismodule tests thismodule runtests this let us anybody reading your source code know where to look for the test code
|
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
|
to make it flattened list use either http code activestate com recipes http code activestate com recipes then join to make it string
|
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 is couple choices first you can just create new list and add the contents of each list to it li for sublist in li li extend sublist alternately you can use the itertools module chain function which produces an iterable containing all the items in multiple iterables import itertools li list itertools chain li if you take this approach you can produce the string without creating an intermediate list join itertools chain li
|
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
|
for the second one there is built in string method to do that print join str for in li for the first one you can use join within comprehension list print join join str for in li but it is easier to use itertools flatten import itertools print itertools flatten li print join str for in itertools flatten li itertools is module that help you to deal with common tasks with iterators such as list tuples or string it is handy because it does not store copy of the structure you are working on but process the items one by one edit funny am learning plenty of way to do it who said that there was only one good way to do it
|
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
|
my favorite and the shortest one is this li sum li and join li edit use sum instead of reduce thanks thomas wouters
|
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
|
like so item for innerlist in outerlist for item in innerlist turning that directly into string with separators join str item for innerlist in outerlist for item in innerlist yes the order of for innerlist in outerlist and for item in innerlist is correct even though the body of the loop is at the start of the listcomp the order of nested loops and if clauses is still the same as when you would write the loop out for innerlist in outerlist for item in innerlist
|
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
|
try that li li for in li for in you can read it like this give me the list of every ys the ys come from the xs the xs come from li to map that in string join map str li
|
QA
|
how to generate all permutations of list in python how do you generate all the permutations of list in python independently of the type of elements in that list for example permutations permutations permutations permutations edit eliben pointed to solution that is similar to mine although simpler so am choosing it as the accepted answer although python has builtin solution in the itertools module import itertools itertools permutations
|
this solution implements generator to avoid holding all the permutations on memory def permutations orig list if not isinstance orig list list orig list list orig list yield orig list if len orig list return for in sorted orig list new list orig list pos new list index del new list pos new list insert for resto in permutations new list if new list resto orig list yield new list resto
|
QA
|
how to generate all permutations of list in python how do you generate all the permutations of list in python independently of the type of elements in that list for example permutations permutations permutations permutations edit eliben pointed to solution that is similar to mine although simpler so am choosing it as the accepted answer although python has builtin solution in the itertools module import itertools itertools permutations
|
starting with python and if you are on python you have standard library tool for this itertools permutations if you are using an older python for some reason or are just curious to know how it works here is one nice approach taken from http code activestate com recipes def all perms elements if len elements yield elements else for perm in all perms elements for in range len elements nb elements works in both string and list contexts yield perm elements perm couple of alternative approaches are listed in the documentation of itertools permutations here is one def permutations iterable none permutations abcd ab ac ad ba because bd ca cb cd da db dc permutations range pool tuple iterable len pool are if is none else if are return indices range cycles range yield tuple pool for in indices while for in reversed range cycles if cycles indices indices indices cycles else cycles indices indices indices indices yield tuple pool for in indices break else return and another based on itertools product def permutations iterable none pool tuple iterable len pool are if is none else for indices in product range repeat if len set indices yield tuple pool for in indices
|
QA
|
how to generate all permutations of list in python how do you generate all the permutations of list in python independently of the type of elements in that list for example permutations permutations permutations permutations edit eliben pointed to solution that is similar to mine although simpler so am choosing it as the accepted answer although python has builtin solution in the itertools module import itertools itertools permutations
|
and in python onwards import itertools itertools permutations returned as generator use list permutations to return as list
|
QA
|
python implementation of parsec recently wrote parser in python using ply it is python reimplementation of yacc when was almost done with the parser discovered that the grammar need to parse requires me to do some look up during parsing to inform the lexer without doing look up to inform the lexer cannot correctly parse the strings in the language given than can control the state of the lexer from the grammar rules think will be solving my use case using look up table in the parser module but it may become too difficult to maintain test so want to know about some of the other options in haskell would use parsec library of parsing functions known as combinators is there python implementation of parsec or perhaps some other production quality library full of parsing functionality so can build context sensitive parser in python edit all my attempts at context free parsing have failed for this reason do not expect antlr to be useful here
|
nothing prevents you for diverting your parser from the context free path using ply you can pass information to the lexer during parsing and in this way achieve full flexibility am pretty sure that you can parse anything you want with ply this way for hands on example consider it is parser for ansi written in python with ply it solves the classic typedef identifier problem that makes grammar non context sensitive by populating symbol table in the parser that is being used in the lexer to resolve symbol names as either types or not
|
QA
|
what is thread local storage in python and why do need it in python specifically how do variables get shared between threads although have used threading thread before never really understood or saw examples of how variables got shared are they shared between the main thread and the children or only among the children when would need to use thread local storage to avoid this sharing have seen many warnings about synchronizing access to shared data among threads by using locks but have yet to see really good example of the problem thanks in advance
|
in python everything is shared except for function local variables because each function call gets its own set of locals and threads are always separate function calls and even then only the variables themselves the names that refer to objects are local to the function objects themselves are always global and anything can refer to them the thread object for particular thread is not special object in this regard if you store the thread object somewhere all threads can access like global variable then all threads can access that one thread object if you want to atomically modify anything that you did not just create in this very same thread and did not store anywhere another thread can get at it you have to protect it by lock and all threads must of course share this very same lock or it would not be very effective if you want actual thread local storage that is where threading local comes in attributes of threading local are not shared between threads each thread sees only the attributes it itself placed in there if you are curious about its implementation the source is in threading local py in the standard library
|
QA
|
what is thread local storage in python and why do need it in python specifically how do variables get shared between threads although have used threading thread before never really understood or saw examples of how variables got shared are they shared between the main thread and the children or only among the children when would need to use thread local storage to avoid this sharing have seen many warnings about synchronizing access to shared data among threads by using locks but have yet to see really good example of the problem thanks in advance
|
just like in every other language every thread in python has access to the same variables there is no distinction between the main thread and child threads one difference with python is that the global interpreter lock means that only one thread can be running python code at time this is not much help when it comes to synchronising access however as all the usual pre emption issues still apply and you have to use threading primitives just like in other languages it does mean you need to reconsider if you were using threads for performance however
|
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
|
you still need to use locks your code could be interrupted at any time to execute another thread and this can cause data inconsistencies the problem with gil is that it prevents python code from using more cores at the same time or multiple processors if they are available
|
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
|
no the gil just protects python internals from multiple threads altering their state this is very low level of locking sufficient only to keep python own structures in consistent state it does not cover the application level locking you will need to do to cover thread safety in your own code the essence of locking is to ensure that particular block of code is only executed by one thread the gil enforces this for blocks the size of single bytecode but usually you want the lock to span larger block of code than this
|
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
|
this post describes the gil at fairly high level https web archive org web http www pyzine com issue section articles article threadingglobalinterpreter html of particular interest are these quotes every ten instructions this default can be changed the core releases the gil for the current thread at that point the os chooses thread from all the threads competing for the lock possibly choosing the same thread that just released the gil you do not have any control over which thread gets chosen that thread acquires the gil and then runs for another ten bytecodes and note carefully that the gil only restricts pure python code extensions external python libraries usually written in can be written that release the lock which then allows the python interpreter to run separately from the extension until the extension reacquires the lock it sounds like the gil just provides fewer possible instances for context switch and makes multi core processor systems behave as single core with respect to each python interpreter instance so yes you still need to use synchronization mechanisms
|
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
|
the global interpreter lock prevents threads from accessing the interpreter simultaneously thus cpython only ever uses one core however as understand it the threads are still interrupted and scheduled preemptively which means you still need locks on shared data structures lest your threads stomp on each other toes the answer have encountered time and time again is that multithreading in python is rarely worth the overhead because of this have heard good things about the pyprocessing project which makes running multiple processes as simple as multithreading with shared data structures queues etc pyprocessing will be introduced into the standard library of the upcoming python as the multiprocessing module this gets you around the gil as each process has its own interpreter
|
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
|
you will still need locks if you share state between threads the gil only protects the interpreter internally you can still have inconsistent updates in your own code for example usr bin env python import threading shared balance class deposit threading thread def run self for in xrange global shared balance balance shared balance balance shared balance balance class withdraw threading thread def run self for in xrange global shared balance balance shared balance balance shared balance balance threads deposit withdraw for thread in threads thread start for thread in threads thread join print shared balance here your code can be interrupted between reading the shared state balance shared balance and writing the changed result back shared balance balance causing lost update the result is random value for the shared state to make the updates consistent run methods would need to lock the shared state around the read modify write sections inside the loops or have some way to detect when the shared state had changed since it was read
|
QA
|
how can analyze python code to identify problematic areas have large source repository split across multiple projects would like to produce report about the health of the source code identifying problem areas that need to be addressed specifically would like to call out routines with high cyclomatic complexity identify repetition and perhaps run some lint like static analysis to spot suspicious and thus likely erroneous constructs how might go about constructing such report
|
for measuring cyclomatic complexity there is nice tool available at traceback org the page also gives good overview of how to interpret the results for pylint it is great at verifying adherence to coding standards be it pep or your own organization variant which can in the end help to reduce cyclomatic complexity
|
QA
|
making beta code for public django site am about to put beta version of the site am working on up on the web it needs to have beta code to restrict access the site is written in django do not want to change the fundamental auth system to accommodate beta code and do not care particularly that the security of the beta code is iron clad just that it is significant stumbling block how should do this it is fairly large project so adding code to every view is far from ideal that solution works well the middleware class ended up with this this from django http import httpresponseredirect class betamiddleware object require beta code session key in order to view any page def process request self request if request path beta and not request session get in beta return httpresponseredirect next beta request path
|
you should be able to add login required decorators across the board and be done with it unless you have boat load of view functions it should not be too horrible
|
QA
|
making beta code for public django site am about to put beta version of the site am working on up on the web it needs to have beta code to restrict access the site is written in django do not want to change the fundamental auth system to accommodate beta code and do not care particularly that the security of the beta code is iron clad just that it is significant stumbling block how should do this it is fairly large project so adding code to every view is far from ideal that solution works well the middleware class ended up with this this from django http import httpresponseredirect class betamiddleware object require beta code session key in order to view any page def process request self request if request path beta and not request session get in beta return httpresponseredirect next beta request path
|
you can probably restrict access to the entire site via apache with htaccess taking the problem out of the django project space entirely
|
QA
|
how to generate all permutations of list in python how do you generate all the permutations of list in python independently of the type of elements in that list for example permutations permutations permutations permutations edit eliben pointed to solution that is similar to mine although simpler so am choosing it as the accepted answer although python has builtin solution in the itertools module import itertools itertools permutations
|
forgive my python illiteracy as will not be offering the solution in python as do not know what method python uses to generate the permutations and eliben one looks like johnson trotter permutation generation you might look for article in wikipedia on permutations and their generation that looks quite like unrank function in paper by myrvold and ruskey it would seem to me that this could be used in generator in the same way as in other replies to lessen the memory requirement considerably just remember that the permutations will not be in lexicographic order
|
QA
|
making beta code for public django site am about to put beta version of the site am working on up on the web it needs to have beta code to restrict access the site is written in django do not want to change the fundamental auth system to accommodate beta code and do not care particularly that the security of the beta code is iron clad just that it is significant stumbling block how should do this it is fairly large project so adding code to every view is far from ideal that solution works well the middleware class ended up with this this from django http import httpresponseredirect class betamiddleware object require beta code session key in order to view any page def process request self request if request path beta and not request session get in beta return httpresponseredirect next beta request path
|
do what stackoverflow did they had simple email password form it had single hard coded password falkensmaze when the user gets the password right set cookie eg auth do not worry about it being unsecure who care if someone hacks into the beta apache htaccess is also nice and simple solution
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.