prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
how to do makefile dependencies for python code have bunch of files that are generated by collection of python programs that have number of shared python modules and need to account for this in my make system it is easy enough to enumerate which python program need to be run to generate each file what cannot find good solution for is determining which other python files those programs depend on need this so make will know what needs regenerating if one of the shared python files changes is there good system for producing make style dependency rules from collection of python sources
|
modulefinder can be used to get the dependency graph
|
QA
|
any good contact us recipes for cherrypy am looking to implement contact us form with cherrypy and was wondering is there good recipe or bsd licensed set of code that could use instead of reinventing the wheel ideally this would be cherrpy compatible
|
well had to look into solution this works ugly and javascript validation using the smtplib lib also note that stole jeff captcha for this example anyone using this will need to change it edit added validation usr local bin python import smtplib import cherrypy class inputexample cherrypy expose def index self return html head head body href contactus contact us body html cherrypy expose def contactus self message return html head title contact us title script type text javascript function isnotempty elem var str elem value var re if str match re elem focus return false else return true function isemailaddr elem var str elem value var re za if str match re return false else return true function validateform form if isnotempty form firstname isnotempty form lastname if isnotempty form email if isemailaddr form email if isnotempty form captcha if form captcha value egnaro split reverse join if isnotempty form subject alert all required fields are found we will respond shortly return true else alert please enter the word as displayed in the image return false captcha empty else alert please enter valid email address return false email email first and last name alert please fill in all required fields return false script head body message form method post action contactussubmitted onsubmit return validateform this label for firstname first name label input type text id firstname name firstname required br label for lastname last name label input type text id lastname name lastname required br label for email mail address label input type text id email name email required br label for phone phone number label input type text id phone name phone br br this needs to be changed to match your own captcha scheme label for captcha enter the word br img alt rhymes with src http www codinghorror com blog images word png width height border label br href http www codinghorror com blog sounds captcha word spoken mp hear it spoken br input tabindex id captcha name captcha br br label for subject subject label input type text id subject name subject required br label for body details label textarea id body name body textarea br input type submit value contact us form body html message message cherrypy expose def contactussubmitted self firstname lastname email phone captcha subject body if captcha egnaro return self contactus please reenter the word you see in the image self sendemail mail example com mailbox account mailbox pwd me example com email website contact subject sender email email name firstname lastname phone phone body return self index def sendemail self smtpserver mailboxname mailboxpassword contactemail senderemail subject body server smtplib smtp smtpserver smtp example com server login mailboxname mailboxpassword message to contactemail nfrom senderemail nsubject subject ncontent type text plain body message message contactemail contactemail senderemail mailboxname example com subject subject body body server sendmail contactemail contactemail message this is to send it from an internal account to another internal account server quit cherrypy root inputexample cherrypy config update file development conf cherrypy server start
|
QA
|
how do restrict foreign keys choices to related objects only in django have two way foreign relation similar to the following class parent models model name models charfield max length favoritechild models foreignkey child blank true null true class child models model name models charfield max length myparent models foreignkey parent how do restrict the choices for parent favoritechild to only children whose parent is itself tried class parent models model name models charfield max length favoritechild models foreignkey child blank true null true limit choices to myparent self but that causes the admin interface to not list any children
|
this is not how django works you would only create the relation going one way class parent models model name models charfield max length class child models model name models charfield max length myparent models foreignkey parent and if you were trying to access the children from the parent you would do parent object child set all if you set related name in the myparent field then that is what you would refer to it as ex related name children then you would do parent object children all read the docs http docs djangoproject com en dev topics db models many to one relationships for more
|
QA
|
what does the yield keyword do what is the use of the yield keyword in python what does it do for example am trying to understand this code def get child candidates self distance min dist max dist if self leftchild and distance max dist self median yield self leftchild if self rightchild and distance max dist self median yield self rightchild and this is the caller result candidates list self while candidates node candidates pop distance node get dist obj if distance max dist and distance min dist result extend node values candidates extend node get child candidates distance min dist max dist return result what happens when the method get child candidates is called list is returned single element is returned is it called again when will subsequent calls stop the code comes from jochen schulz jrschulz who made great python library for metric spaces this is the link to the complete source module mspace
|
feel like post link to this presentation every day david beazly generator tricks for systems programmers if you are python programmer and you are not extremely familiar with generators you should read this it is very clear explanation of what generators are how they work what the yield statement does and it answers the question do you really want to mess around with this obscure language feature spoiler alert the answer is yes yes you do
|
QA
|
what does the yield keyword do what is the use of the yield keyword in python what does it do for example am trying to understand this code def get child candidates self distance min dist max dist if self leftchild and distance max dist self median yield self leftchild if self rightchild and distance max dist self median yield self rightchild and this is the caller result candidates list self while candidates node candidates pop distance node get dist obj if distance max dist and distance min dist result extend node values candidates extend node get child candidates distance min dist max dist return result what happens when the method get child candidates is called list is returned single element is returned is it called again when will subsequent calls stop the code comes from jochen schulz jrschulz who made great python library for metric spaces this is the link to the complete source module mspace
|
there is one extra thing to mention function that yields does not actually have to terminate have written code like this def fib last cur while true yield cur last cur cur last cur then can use it in other code like this for in fib if some condition break coolfuncs it really helps simplify some problems and makes some things easier to work with
|
QA
|
how do restrict foreign keys choices to related objects only in django have two way foreign relation similar to the following class parent models model name models charfield max length favoritechild models foreignkey child blank true null true class child models model name models charfield max length myparent models foreignkey parent how do restrict the choices for parent favoritechild to only children whose parent is itself tried class parent models model name models charfield max length favoritechild models foreignkey child blank true null true limit choices to myparent self but that causes the admin interface to not list any children
|
do you want to restrict the choices available in the admin interface when creating editing model instance one way to do this is validation of the model this let us you raise an error in the admin interface if the foreign field is not the right choice of course eric answer is correct you only really need one foreign key from child to parent here
|
QA
|
cannot import sqlite with python am running python on unix and when run the interactive prompt sqlite is supposed to be preinstalled get root idev htdocs python python oct gcc red hat linux on linux type help copyright credits or license for more information import sqlite traceback most recent call last file stdin line in module importerror no module named sqlite how do resolve this
|
import sqlite sqlite db api interface for sqlite databases you are missing the so shared object probably an installation step in my linux python installation sqlite is at somewhere lib python lib dynload sqlite so
|
QA
|
lexical closures in python while was investigating problem had with lexical closures in javascript code came along this problem in python flist for in xrange def func return flist append func for in flist print note that this example mindfully avoids lambda it prints which is surprising would expect this equivalent perl code does it right my flist foreach my push flist sub foreach my flist print is printed can you please explain the difference update the problem is not with being global this displays the same behavior flist def outer for in xrange def inner return flist append inner outer print commented because it causes an error for in flist print as the commented line shows is unknown at that point still it prints
|
the variable is global whose value is at each time the function is called would be inclined to implement the behavior you are after as follows class def init self multiplier self multiplier multiplier def call self multiplicand return self multiplier multiplicand flist for in range for in flist response to your update it is not the globalness of per se which is causing this behavior it is the fact that it is variable from an enclosing scope which has fixed value over the times when is called in your second example the value of is taken from the scope of the kkk function and nothing is changing that when you call the functions on flist
|
QA
|
lexical closures in python while was investigating problem had with lexical closures in javascript code came along this problem in python flist for in xrange def func return flist append func for in flist print note that this example mindfully avoids lambda it prints which is surprising would expect this equivalent perl code does it right my flist foreach my push flist sub foreach my flist print is printed can you please explain the difference update the problem is not with being global this displays the same behavior flist def outer for in xrange def inner return flist append inner outer print commented because it causes an error for in flist print as the commented line shows is unknown at that point still it prints
|
look at this for in flist print func closure cell at int object at cell at int object at cell at int object at it means they all point to the same variable instance which will have value of once the loop is over readable solution for in xrange def ffunc def func return return func flist append ffunc
|
QA
|
lexical closures in python while was investigating problem had with lexical closures in javascript code came along this problem in python flist for in xrange def func return flist append func for in flist print note that this example mindfully avoids lambda it prints which is surprising would expect this equivalent perl code does it right my flist foreach my push flist sub foreach my flist print is printed can you please explain the difference update the problem is not with being global this displays the same behavior flist def outer for in xrange def inner return flist append inner outer print commented because it causes an error for in flist print as the commented line shows is unknown at that point still it prints
|
the problem is that all of the local functions bind to the same environment and thus to the same variable the solution workaround is to create separate environments stack frames for each function or lambda lambda lambda for in range
|
QA
|
lexical closures in python while was investigating problem had with lexical closures in javascript code came along this problem in python flist for in xrange def func return flist append func for in flist print note that this example mindfully avoids lambda it prints which is surprising would expect this equivalent perl code does it right my flist foreach my push flist sub foreach my flist print is printed can you please explain the difference update the problem is not with being global this displays the same behavior flist def outer for in xrange def inner return flist append inner outer print commented because it causes an error for in flist print as the commented line shows is unknown at that point still it prints
|
python is actually behaving as defined three separate functions are created but they each have the closure of the environment they are defined in in this case the global environment or the outer function environment if the loop is placed inside another function this is exactly the problem though in this environment is mutated and the closures all refer to the same here is the best solution can come up with create function creater and invoke that instead this will force different environments for each of the functions created with different in each one flist for in xrange def funcc def func return return func flist append funcc for in flist print this is what happens when you mix side effects and functional programming
|
QA
|
cannot import sqlite with python am running python on unix and when run the interactive prompt sqlite is supposed to be preinstalled get root idev htdocs python python oct gcc red hat linux on linux type help copyright credits or license for more information import sqlite traceback most recent call last file stdin line in module importerror no module named sqlite how do resolve this
|
the error importerror no module named sqlite means that sqlite does not find the associated shared library on mac os it is sqlite so and it should be the same on other unix systems to resolve the error you have to locate the sqlite so library on your computer and then check your pythonpath for this directory location to print the python search path enter the following in the python she will import sys print sys path if the directory containing your library is missing you can try adding it interactively with sys path append your dir here and try import sqlite again if this works you have to add this directory permanently to your pythonpath environment variable ps if the library is missing you should re install the module
|
QA
|
cannot import sqlite with python am running python on unix and when run the interactive prompt sqlite is supposed to be preinstalled get root idev htdocs python python oct gcc red hat linux on linux type help copyright credits or license for more information import sqlite traceback most recent call last file stdin line in module importerror no module named sqlite how do resolve this
|
try this from pysqlite import dbapi as sqlite
|
QA
|
cannot import sqlite with python am running python on unix and when run the interactive prompt sqlite is supposed to be preinstalled get root idev htdocs python python oct gcc red hat linux on linux type help copyright credits or license for more information import sqlite traceback most recent call last file stdin line in module importerror no module named sqlite how do resolve this
|
on my system sqlite so located at usr lib python lib dynload sqlite so check that the directory is in your sys path import sys print filter lambda lib dynload in sys path usr lib python lib dynload
|
QA
|
make python enter password when running csh script am writing python script that executes csh script in solaris the csh script prompts the user for the root password which know but am not sure how to make the python script answer the prompt with the password is this possible here is what am using to execute the csh script import commands commands getoutput server stop
|
to avoid having to answer the password question in the python script am just going to run the script as root this question is still unanswered but guess will just do it this way for now
|
QA
|
how do restrict foreign keys choices to related objects only in django have two way foreign relation similar to the following class parent models model name models charfield max length favoritechild models foreignkey child blank true null true class child models model name models charfield max length myparent models foreignkey parent how do restrict the choices for parent favoritechild to only children whose parent is itself tried class parent models model name models charfield max length favoritechild models foreignkey child blank true null true limit choices to myparent self but that causes the admin interface to not list any children
|
ber have added validation to the model similar to this class parent models model name models charfield max length favoritechild models foreignkey child blank true null true def save self force insert false force update false if self favoritechild is not none and self favoritechild myparent id self id raise exception you must select one of your own children as your favorite super parent self save force insert force update which works exactly how want but it would be really nice if this validation could restrict choices in the dropdown in the admin interface rather than validating after the choice
|
QA
|
os walk without digging into directories below how do limit os walk to only return files in the directory provide it def dir list self dir name whitelist outputlist for root dirs files in os walk dir name for in files if os path splitext in whitelist outputlist append os path join root else self email to ignore return outputlist
|
use the walklevel function import os def walklevel some dir level some dir some dir rstrip os path sep assert os path isdir some dir num sep some dir count os path sep for root dirs files in os walk some dir yield root dirs files num sep this root count os path sep if num sep level num sep this del dirs it works just like os walk but you can pass it level parameter that indicates how deep the recursion will go
|
QA
|
splitting strings in python have string which is like this this is bracket test and quotes test am trying to write something in python to split it up by space while ignoring spaces within square braces and quotes the result am looking for is this is bracket test and quotes test
|
here is simplistic solution that works with your test input import re re findall this will return any code that matches either open bracket followed by zero or more non close bracket characters followed by close bracket double quote followed by zero or more non quote characters followed by quote any group of non whitespace characters this works with your example but might fail for many real world strings you may encounter for example you did not say what you expect with unbalanced brackets or quotes or how you want single quotes or escape characters to work for simple cases though the above might be good enough
|
QA
|
splitting strings in python have string which is like this this is bracket test and quotes test am trying to write something in python to split it up by space while ignoring spaces within square braces and quotes the result am looking for is this is bracket test and quotes test
|
here is simplistic parser tested against your example input that introduces the state design pattern in real world you probably want to build real parser using something like ply class simpleparser object def init self self mode none self result none def parse self text self initial mode self result for word in text split self mode handle word word return self result def initial mode self self mode initialmode self def bracket mode self self mode bracketmode self def quote mode self self mode quotemode self class initialmode object def init self parser self parser parser def handle word self word if word startswith self parser bracket mode self parser mode handle word word elif word startswith self parser quote mode self parser mode handle word word else self parser result append word class blockmode object end marker none def init self parser self parser parser self result def handle word self word if word endswith self end marker self result append word self parser result append join self result self parser initial mode else self result append word class bracketmode blockmode end marker class quotemode blockmode end marker
|
QA
|
default parameters to actions with django is there way to have default parameter passed to action in the case where the regex did not match anything using django urlpatterns patterns test name myview displayname myview py def displayname request name write name to response or something have tried setting the third parameter in the urlpatterns to dictionary containing and giving the name parameter default value on the method none of which worked the name parameter always seems to be none really do not want to code check for none if could set default value clarification here is an example of what was changing it to def displayname request name steve return httpresponse name also tried urlpatterns patterns test name myview displayname dict name test when point my browser at the view it displays the text none any ideas
|
thought you could def displayname request name defaultobj that is what have done in the past at least what were you setting the default value to
|
QA
|
splitting strings in python have string which is like this this is bracket test and quotes test am trying to write something in python to split it up by space while ignoring spaces within square braces and quotes the result am looking for is this is bracket test and quotes test
|
here is more procedural approach usr bin env python this is bracket test and quotes test words split wordlist while true try word words pop except indexerror break if word in buildlist word while true try word words pop except indexerror break if word in buildlist append word break buildlist append word wordlist append join buildlist else wordlist append word print wordlist
|
QA
|
default parameters to actions with django is there way to have default parameter passed to action in the case where the regex did not match anything using django urlpatterns patterns test name myview displayname myview py def displayname request name write name to response or something have tried setting the third parameter in the urlpatterns to dictionary containing and giving the name parameter default value on the method none of which worked the name parameter always seems to be none really do not want to code check for none if could set default value clarification here is an example of what was changing it to def displayname request name steve return httpresponse name also tried urlpatterns patterns test name myview displayname dict name test when point my browser at the view it displays the text none any ideas
|
the problem is that when the pattern is matched against test the groupdict captured by the regex contains the mapping name none url match test groupdict name none this means that when the view is invoked using something expect that is similar to below view request groups groupdict which is equivalent to view request name none for test meaning that name is assigned none rather than not assigned this leaves you with two options you can explicitly check for none in the view code which is kind of hackish rewrite the url dispatch rule to make the name capture non optional and introduce second rule to capture when no name is provided for example urlpatterns patterns test name myview displayname note the instead of the test myview displayname when taking the second approach you can simply call the method without the capture pattern and let python handle the default parameter or you can call different view which delegates
|
QA
|
trailing slashes in pylons routes what is the best way to make trailing slashes not matter in the latest version of routes currently am using the clearly non dry map connect logs controller logs action logs map connect logs controller logs action logs think that turning minimization on would do the trick but am under the impression that it was disabled in the newer versions of routes for reason unfortunately documentation does not seem to have caught up with routes development so cannot find any good resources to go to any ideas
|
there are two possible ways to solve this do it entirely in pylons add an htaccess rule to rewrite the trailing slash personally do not like the trailing slash because if you have uri like http example com people you should be able to get the same data in xml format by going to http example com people xml
|
QA
|
splitting strings in python have string which is like this this is bracket test and quotes test am trying to write something in python to split it up by space while ignoring spaces within square braces and quotes the result am looking for is this is bracket test and quotes test
|
to complete bryan post and match exactly the answer import re txt this is bracket test and quotes test if in else for in re findall txt this is bracket test and quotes test do not misunderstand the whole syntax used this is not several statments on single line but single functional statment more bugproof
|
QA
|
how do implement custom code page used by serial device so can convert text to it in python have scrolling led sign that takes messages in either ascii or using some specific code characters from custom code page for example the euro sign should be sent as and is you can find the full code page in the documentation my question is what is the most pythonic way to implement this custom code page and to have codec that can convert utf strings to my custom code page
|
pick name for your encoding maybe led display whatever implement and register codec with the standard library pythonic profit
|
QA
|
environment variables in python on linux python access to environment variables does not accurately reflect the operating system view of the processes environment os getenv and os environ do not function as expected in particular cases is there way to properly get the running process environment to demonstrate what mean take the two roughly equivalent programs the first in the other in python include stdio include stdlib include unistd int main int argc char argv char env for env getenv some variable if env puts env sleep import os import time while true env os getenv some variable if env is not none print env time sleep now if we run the program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this gdb print setenv some variable my value switching to thread lwp gdb print char getenv some variable my value then the aforementioned program will start spewing out my value once every seconds the aforementioned python program however will not is there way to get the python program to function like the program in this case yes realize this is very obscure and potentially damaging action to perform on running process also am currently using python this may have been fixed in later version of python
|
looking at the python source code modules posixmodule gets the environ in convertenviron which gets run at startup see initfunc and stores the environment in platform specific module nt os or posix lib os py looks at sys builtin module names and imports all symbols from either posix nt or os so yes it gets decided at startup os environ is not going to be helpful here if you really want to do this then the most obvious approach that comes to mind is to create your own custom based python module with getenv that always invokes the system call
|
QA
|
environment variables in python on linux python access to environment variables does not accurately reflect the operating system view of the processes environment os getenv and os environ do not function as expected in particular cases is there way to properly get the running process environment to demonstrate what mean take the two roughly equivalent programs the first in the other in python include stdio include stdlib include unistd int main int argc char argv char env for env getenv some variable if env puts env sleep import os import time while true env os getenv some variable if env is not none print env time sleep now if we run the program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this gdb print setenv some variable my value switching to thread lwp gdb print char getenv some variable my value then the aforementioned program will start spewing out my value once every seconds the aforementioned python program however will not is there way to get the python program to function like the program in this case yes realize this is very obscure and potentially damaging action to perform on running process also am currently using python this may have been fixed in later version of python
|
that is very good question it turns out that the os module initializes os environ to the value of posix environ which is set on interpreter start up in other words the standard library does not appear to provide access to the getenv function that is case where it would probably be safe to use ctypes on unix since you would be calling an ultra standard libc function
|
QA
|
python inheritance how to disable function in you can disable function in parent class by declaring it as private in the child class how can this be done in python how can hide parent function from child public interface
|
kurosch method of solving the problem is not quite correct because you can still use foo without getting an attributeerror if you do not invoke the function no error occurs here are two ways that can think to do this import doctest class foo object foo foo foo def foo self print foo def fu self print fu class bar object bar foo traceback most recent call last attributeerror hasattr foo false hasattr fu true def init self self wrapped foo def getattr self attr name if attr name foo raise attributeerror return getattr self wrapped attr name class baz foo baz foo doctest ellipsis traceback most recent call last attributeerror hasattr foo false hasattr fu true foo property if name main doctest testmod bar uses the wrap pattern to restrict access to the wrapped object martelli has good talk dealing with this baz uses the property built in to implement the descriptor protocol for the attribute to override
|
QA
|
javascript style dot notation for dictionary keys unpythonic have started to use constructs like these class dictobj object def init self self def getattr self return self get none def setattr self super setattr self update based on this thread have revised the dictobj implementation to class dotdict dict def getattr self attr return self get attr none setattr dict setitem delattr dict delitem class autoenum object def init self self counter self def getattr self if not in self self self counter self counter return self where dictobj is dictionary that can be accessed via dot notation dictobj something one find it more aesthetically pleasing than something note that accessing an undefined key returns none instead of raising an exception which is also nice update smashery makes good point which mhawke expands on for an easier solution am wondering if there are any undesirable side effects of using dict instead of defining new dictionary if not like mhawke solution lot autoenum is an auto incrementing enum used like this cmd autoenum cmds peek cmd peek look cmd peek help cmd help poke cmd poke modify cmd poke both are working well for me but am feeling unpythonic about them are these in fact bad constructs
|
the one major disadvantage of using something like your dictobj is you either have to limit allowable keys or you cannot have methods on your dictobj such as keys values items etc
|
QA
|
javascript style dot notation for dictionary keys unpythonic have started to use constructs like these class dictobj object def init self self def getattr self return self get none def setattr self super setattr self update based on this thread have revised the dictobj implementation to class dotdict dict def getattr self attr return self get attr none setattr dict setitem delattr dict delitem class autoenum object def init self self counter self def getattr self if not in self self self counter self counter return self where dictobj is dictionary that can be accessed via dot notation dictobj something one find it more aesthetically pleasing than something note that accessing an undefined key returns none instead of raising an exception which is also nice update smashery makes good point which mhawke expands on for an easier solution am wondering if there are any undesirable side effects of using dict instead of defining new dictionary if not like mhawke solution lot autoenum is an auto incrementing enum used like this cmd autoenum cmds peek cmd peek look cmd peek help cmd help poke cmd poke modify cmd poke both are working well for me but am feeling unpythonic about them are these in fact bad constructs
|
it is not wrong to do this and it can be nicer if your dictionaries have strong possibility of turning into objects at some point but be wary of the reasons for having bracket access in the first place dot access cannot use keywords as keys dot access has to use python identifier valid characters in the keys dictionaries can hold any hashable element not just strings also keep in mind you can always make your objects access like dictionaries if you decide to switch to objects later on for case like this would default to the readability counts mantra presumably other python programmers will be reading your code and they probably will not be expecting dictionary object hybrids everywhere if it is good design decision for particular situation use it but would not use it without necessity to do so
|
QA
|
can you do linq like queries in language like python or boo take this simple linq query and imagine that db numbers is an sql table with one column number var result from in db numbers where number select number this will run very efficiently in because it generates an sql query something like select number from numbers where number what it does not do is select all the numbers from the database and then filter them in as it might appear to do at first python supports similar syntax result number for in numbers if number but it the if clause here does the filtering on the client side rather than the server side which is much less efficient is there something as efficient as linq in python am currently evaluating python vs ironpython vs boo so an answer that works in any of those languages is fine
|
key factor for linq is the ability of the compiler to generate expression trees am using macro in nemerle that converts given nemerle expression into an expression tree object can then pass this to the where select etc extension methods on iqueryables it is not quite the syntax of and vb but it is close enough for me got the nemerle macro via link on this post http groups google com group nemerle dev browse thread thread dcfe it should be possible to create similar macro for boo it is quite bit of work however given the large set of possible expressions you need to support ayende has given proof of concept here http ayende com blog archive ugly linq aspx
|
QA
|
lexical closures in python while was investigating problem had with lexical closures in javascript code came along this problem in python flist for in xrange def func return flist append func for in flist print note that this example mindfully avoids lambda it prints which is surprising would expect this equivalent perl code does it right my flist foreach my push flist sub foreach my flist print is printed can you please explain the difference update the problem is not with being global this displays the same behavior flist def outer for in xrange def inner return flist append inner outer print commented because it causes an error for in flist print as the commented line shows is unknown at that point still it prints
|
the functions defined in the loop keep accessing the same variable while its value changes at the end of the loop all the functions point to the same variable which is holding the last value in the loop the effect is what reported in the example in order to evaluate and use its value common pattern is to set it as parameter default parameter defaults are evaluated when the def statement is executed and thus the value of the loop variable is frozen the following works as expected flist for in xrange def func the value of is copied in func environment return flist append func for in flist print
|
QA
|
lexical closures in python while was investigating problem had with lexical closures in javascript code came along this problem in python flist for in xrange def func return flist append func for in flist print note that this example mindfully avoids lambda it prints which is surprising would expect this equivalent perl code does it right my flist foreach my push flist sub foreach my flist print is printed can you please explain the difference update the problem is not with being global this displays the same behavior flist def outer for in xrange def inner return flist append inner outer print commented because it causes an error for in flist print as the commented line shows is unknown at that point still it prints
|
am still not entirely convinced why in some languages this works one way and in some another way in common lisp it is like python defvar flist dotimes setf flist cons lambda flist dolist flist format funcall prints note that here the list is from to and built in reverse while in scheme it works like in perl define flist do set flist cons lambda flist map lambda printf flist prints and as have mentioned already javascript is in the python cl camp it appears there is an implementation decision here which different languages approach in distinct ways would love to understand what is the decision exactly
|
QA
|
are there any web based email clients written in python need to integrate email client in my current python web app anything available am building my app on top of cherrypy
|
you can build one using email for generating and parsing mail imaplib for reading and managing incoming mail from your mail server and smtplib for sending mail to the world
|
QA
|
lexical closures in python while was investigating problem had with lexical closures in javascript code came along this problem in python flist for in xrange def func return flist append func for in flist print note that this example mindfully avoids lambda it prints which is surprising would expect this equivalent perl code does it right my flist foreach my push flist sub foreach my flist print is printed can you please explain the difference update the problem is not with being global this displays the same behavior flist def outer for in xrange def inner return flist append inner outer print commented because it causes an error for in flist print as the commented line shows is unknown at that point still it prints
|
what is happening is that the variable is captured and the functions are returning the value it is bound to at the time it is called in functional languages this kind of situation never arises as would not be rebound however with python and also as you have seen with lisp this is no longer true the difference with your scheme example is to do with the semantics of the do loop scheme is effectively creating new variable each time through the loop rather than reusing an existing binding as with the other languages if you use different variable created external to the loop and mutate it you will see the same behaviour in scheme try replacing your loop with let ii do set flist cons lambda ii flist set ii take look here for some further discussion of this edit possibly better way to describe it is to think of the do loop as macro which performs the following steps define lambda taking single parameter with body defined by the body of the loop an immediate call of that lambda with appropriate values of as its parameter ie the equivalent to the below python flist def loop body extract body of the for loop to function def func return flist append func map loop body xrange for in xrange body the is no longer the one from the parent scope but brand new variable in its own scope ie the parameter to the lambda and so you get the behaviour you observe python does not have this implicit new scope so the body of the for loop just shares the variable
|
QA
|
what is your convention to distinguish between object methods to be called by the outside and object methods to be called by subclass know most of the ins and outs of python approach to private variables members functions however cannot make my mind up on how to distinguish between methods for external use or subclassing use consider the following example class eventmixin object def subscribe self kwargs kwargs should be dict of event callable to be specialized in the subclass def event self name args kwargs def someprivatemethod self in this example want to make it clear that subscribe is method to be used by external users of the class object while event is method that should not be called from the outside but rather by subclass implementations right now consider both part of the public api hence do not use any underscores however for this particular situation it would feel cleaner to for example use no underscores for the external api one underscore for the subclassable api and two underscores for the private internal api however that would become unwieldy because then the internal api would need to be invoked as self eventmixin someprivatemethod so what are your conventions coding wise documentationwise or otherwise
|
use no underscores for the external api one underscore for the subclassable api and two underscores for the private internal api this is reasonable and relatively common way of doing it yes the double underline for actually private as opposed to protected in terms is in practice pretty rare you never really know what behaviours subclass might want to override so assuming protected is generally good bet unless there is really good reason why messing with member might be particularly dangerous however that would become unwieldy because then the internal api would need to be invoked as self eventmixin someprivatemethod nope you can just use the double underlined version and it will be munged automatically it is ugly but it works
|
QA
|
how can use python for large scale development would be interested to learn about large scale development in python and especially in how do you maintain large code base when you make incompatibility changes to the signature of method how do you find all the places where that method is being called in java the compiler will find it for you how do you do it in python when you make changes deep inside the code how do you find out what operations an instance provides since you do not have static type to lookup how do you handle prevent typing errors typos are unittest used as substitute for static type checking as you can guess almost only worked with statically typed languages java but would like to try my hands on python for larger programs but had very bad experience long time ago with the clipper dbase language which was also dynamically typed
|
my eur have several python application in production state our company use java and python we develop with the eclipse ide pydev for python unittests are the key solution for the problem also for and java the less secure world of dynamic typing will make you less careless about your code quality by the way large scale development does not mean that you use one single language large scale development often uses handful of languages specific to the problem so agree to the hammer problem ps static typing python
|
QA
|
how can use python for large scale development would be interested to learn about large scale development in python and especially in how do you maintain large code base when you make incompatibility changes to the signature of method how do you find all the places where that method is being called in java the compiler will find it for you how do you do it in python when you make changes deep inside the code how do you find out what operations an instance provides since you do not have static type to lookup how do you handle prevent typing errors typos are unittest used as substitute for static type checking as you can guess almost only worked with statically typed languages java but would like to try my hands on python for larger programs but had very bad experience long time ago with the clipper dbase language which was also dynamically typed
|
had some experience with modifying frets on fire an open source python guitar hero clone as see it python is not really suitable for really large scale project found myself spending large part of the development time debugging issues related to assignment of incompatible types things that static typed laguages will reveal effortlessly at compile time also since types are determined on run time trying to understand existing code becomes harder because you have no idea what is the type of that parameter you are currently looking at in addition to that calling functions using their name string with the getattr built in function is generally more common in python than in other programming languages thus getting the call graph to certain function somewhat hard although you can call functions with their name in some statically typed languages as well think that python really shines in small scale software rapid prototype development and gluing existing programs together but would not use it for large scale software projects since in those types of programs maintainability becomes the real issue and in my opinion python is relatively weak there
|
QA
|
how can use python for large scale development would be interested to learn about large scale development in python and especially in how do you maintain large code base when you make incompatibility changes to the signature of method how do you find all the places where that method is being called in java the compiler will find it for you how do you do it in python when you make changes deep inside the code how do you find out what operations an instance provides since you do not have static type to lookup how do you handle prevent typing errors typos are unittest used as substitute for static type checking as you can guess almost only worked with statically typed languages java but would like to try my hands on python for larger programs but had very bad experience long time ago with the clipper dbase language which was also dynamically typed
|
the usual answer to that is testing testing testing you are supposed to have an extensive unit test suite and run it often particularly before new version goes online proponents of dynamically typed languages make the case that you have to test anyway because even in statically typed language conformance to the crude rules of the type system covers only small part of what can potentially go wrong
|
QA
|
how can use python for large scale development would be interested to learn about large scale development in python and especially in how do you maintain large code base when you make incompatibility changes to the signature of method how do you find all the places where that method is being called in java the compiler will find it for you how do you do it in python when you make changes deep inside the code how do you find out what operations an instance provides since you do not have static type to lookup how do you handle prevent typing errors typos are unittest used as substitute for static type checking as you can guess almost only worked with statically typed languages java but would like to try my hands on python for larger programs but had very bad experience long time ago with the clipper dbase language which was also dynamically typed
|
do not use screw driver as hammer python is not statically typed language so do not try to use it that way when you use specific tool you use it for what it has been built for python it means duck typing no type checking only behavior matters therefore your code must be designed to use this feature good design means generic signatures no dependences between components high abstraction levels so if you change anything you will not have to change the rest of the code python will not complain either that what it has been built for types are not an issue huge standard library you do not need to change all your calls in the program if you use standard features you have not coded yourself and python come with batteries included keep discovering them everyday had no idea of the number of modules could use when started and tried to rewrite existing stuff like everybody it is ok you cannot get it all right from the beginning you do not write java python php erlang whatever the same way they are good reasons why there is room for each of so many different languages they do not do the same things unit tests are not substitute unit tests must be performed with any language the most famous unit test library junit is from the java world this has nothing to do with types you check behaviors again you avoid trouble with regression you ensure your customer you are on tracks python for large scale projects languages libraries and frameworks do not scale architectures do if you design solid architecture if you are able to make it evolves quickly then it will scale unit tests help automatic code check as well but they are just safety nets and small ones python is especially suitable for large projects because it enforces some good practices and has lot of usual design patterns built in but again do not use it for what it is not designed python is not technology for cpu intensive tasks in huge project you will most likely use several different technologies anyway as sgbd and templating language or else python is no exception you will probably want to use for the part of your code you need to be fast or java to fit in tomcat environment do not know do not care python can play well with these as conclusion my answer may feel bit rude but do not get me wrong this is very good question lot of people come to python with old habits screwed myself trying to code java like python you can but will never get the best of it if you have played want to play with python it is great it is wonderful tool but just tool really
|
QA
|
environment variables in python on linux python access to environment variables does not accurately reflect the operating system view of the processes environment os getenv and os environ do not function as expected in particular cases is there way to properly get the running process environment to demonstrate what mean take the two roughly equivalent programs the first in the other in python include stdio include stdlib include unistd int main int argc char argv char env for env getenv some variable if env puts env sleep import os import time while true env os getenv some variable if env is not none print env time sleep now if we run the program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this gdb print setenv some variable my value switching to thread lwp gdb print char getenv some variable my value then the aforementioned program will start spewing out my value once every seconds the aforementioned python program however will not is there way to get the python program to function like the program in this case yes realize this is very obscure and potentially damaging action to perform on running process also am currently using python this may have been fixed in later version of python
|
do not believe many programs ever expect to have their environment externally modified so loading copy of the passed environment at startup is equivalent you have simply stumbled on an implementation choice if you are seeing all the set at startup values and putenv setenv from within your program works do not think there is anything to be concerned about there are far cleaner ways to pass updated information to running executables
|
QA
|
how can use python for large scale development would be interested to learn about large scale development in python and especially in how do you maintain large code base when you make incompatibility changes to the signature of method how do you find all the places where that method is being called in java the compiler will find it for you how do you do it in python when you make changes deep inside the code how do you find out what operations an instance provides since you do not have static type to lookup how do you handle prevent typing errors typos are unittest used as substitute for static type checking as you can guess almost only worked with statically typed languages java but would like to try my hands on python for larger programs but had very bad experience long time ago with the clipper dbase language which was also dynamically typed
|
since nobody pointed out pychecker pylint and similar tools will pychecker and pylint are tools that can help you find incorrect assumptions about function signatures object attributes etc they will not find everything that compiler might find in statically typed language but they can find problems that such compilers for such languages cannot find too python and any dynamically typed language is fundamentally different in terms of the errors you are likely to cause and how you would detect and fix them it has definite downsides as well as upsides but many including me would argue that in python case the ease of writing code and the ease of making it structurally sound and of modifying code without breaking api compatibility adding new optional arguments providing different objects that have the same set of methods and attributes make it suitable just fine for large codebases
|
QA
|
are there any web based email clients written in python need to integrate email client in my current python web app anything available am building my app on top of cherrypy
|
looking up webmail on pypi gives posterity there is very probably some way to build webmail with very little work using zope components or some other cms guess if you are writing webapp you are probably using one of the popular frameworks we would need to know which one to give more specific answer
|
QA
|
how can use python for large scale development would be interested to learn about large scale development in python and especially in how do you maintain large code base when you make incompatibility changes to the signature of method how do you find all the places where that method is being called in java the compiler will find it for you how do you do it in python when you make changes deep inside the code how do you find out what operations an instance provides since you do not have static type to lookup how do you handle prevent typing errors typos are unittest used as substitute for static type checking as you can guess almost only worked with statically typed languages java but would like to try my hands on python for larger programs but had very bad experience long time ago with the clipper dbase language which was also dynamically typed
|
my general rule of thumb is to use dynamic languages for small non mission critical projects and statically typed languages for big projects find that code written in dynamic language such as python gets tangled more quickly partly that is because it is much quicker to write code in dynamic language and that leads to shortcuts and worse design at least in my case partly it is because have intellij for quick and easy refactoring when use java which do not have for python
|
QA
|
how can use python for large scale development would be interested to learn about large scale development in python and especially in how do you maintain large code base when you make incompatibility changes to the signature of method how do you find all the places where that method is being called in java the compiler will find it for you how do you do it in python when you make changes deep inside the code how do you find out what operations an instance provides since you do not have static type to lookup how do you handle prevent typing errors typos are unittest used as substitute for static type checking as you can guess almost only worked with statically typed languages java but would like to try my hands on python for larger programs but had very bad experience long time ago with the clipper dbase language which was also dynamically typed
|
here are some items that have helped me maintain fairly large system in python structure your code in layers separate biz logic presentaion logic and your persistence layers invest bit of time in defining these layers and make sure everyone on the project is bought in for large systems creating framework that forces you into certain way of development can be key as well tests are key without unit tests you will likely end up with an unmanagable code base several times quicker than with other languages keep in mind that unit tests are often not sufficient make sure to have several integration acceptance tests you can run quickly after any major change use fail fast principle add assertions for cases you feel your code maybe vulnerable have standard logging error handling that will help you quickly navigate to the issue use an ide pydev works for me that provides type ahead pylint checker integration that help you detect common typos right away and promote some coding standards carefull about your imports never do from import or do relative imports without use of do refactor search replace tool with regular expressions is often all you need to do move methods class type refactoring
|
QA
|
what is your convention to distinguish between object methods to be called by the outside and object methods to be called by subclass know most of the ins and outs of python approach to private variables members functions however cannot make my mind up on how to distinguish between methods for external use or subclassing use consider the following example class eventmixin object def subscribe self kwargs kwargs should be dict of event callable to be specialized in the subclass def event self name args kwargs def someprivatemethod self in this example want to make it clear that subscribe is method to be used by external users of the class object while event is method that should not be called from the outside but rather by subclass implementations right now consider both part of the public api hence do not use any underscores however for this particular situation it would feel cleaner to for example use no underscores for the external api one underscore for the subclassable api and two underscores for the private internal api however that would become unwieldy because then the internal api would need to be invoked as self eventmixin someprivatemethod so what are your conventions coding wise documentationwise or otherwise
|
generally find using double to be more trouble that they are worth as it makes unit testing very painful using single as convention for methods attributes that are not intended to be part of the public interface of particular class module is my preferred approach
|
QA
|
what is the best python soap stack for consuming amazon web services wsdl python has number of soap stacks as near as can tell all have substantial defects has anyone had luck consuming and using wsdl for ec and sqs in python my experience is that suds fails when constructing client object after some wrangling zsi generates client code that does not work etc finally am aware of boto but as it is hand rolled wrapper around aws it is incomplete and never up to date with the latest aws wsdl
|
if am not mistaken you can consume amazon web services via rest as well as soap using rest with python would be much easier
|
QA
|
how can use python for large scale development would be interested to learn about large scale development in python and especially in how do you maintain large code base when you make incompatibility changes to the signature of method how do you find all the places where that method is being called in java the compiler will find it for you how do you do it in python when you make changes deep inside the code how do you find out what operations an instance provides since you do not have static type to lookup how do you handle prevent typing errors typos are unittest used as substitute for static type checking as you can guess almost only worked with statically typed languages java but would like to try my hands on python for larger programs but had very bad experience long time ago with the clipper dbase language which was also dynamically typed
|
incompatible changes to the signature of method this does not happen as much in python as it does in java and python has optional arguments default values and far more flexibility in defining method signatures also duck typing means that for example you do not have to switch from some class to an interface as part of significant software change things just are not as complex how do you find all the places where that method is being called grep works for dynamic languages if you need to know every place method is used grep or equivalent ide supported search works great how do you find out what operations an instance provides since you do not have static type to lookup look at the source you do not have the java problem of object libraries and jar files to contend with you do not need all the elaborate aids and tools that those languages require an ide can provide signature information under many common circumstances you can easily defeat your ide reasoning powers when that happens you should probably review what you are doing to be sure it makes sense if your ide cannot reason out your type information perhaps it is too dynamic in python you often work through the interactive interpreter unlike java and you can explore your instances directly and interactively you do not need sophisticated ide example someclass dir how do you handle prevent typing errors same as static languages you do not prevent them you find and correct them java can only find certain class of typos if you have two similar class or variable names you can wind up in deep trouble even with static type checking example class myclass class myclassx extends myclass typo with these two class names can cause havoc but would not put myself in that position with java folks say agreed would not put myself in that position with python either you make classes that are profoundly different and will fail early if they are misused are unittest used as substitute for static type checking here is the other point of view static type checking is substitute for clear simple design have worked with programmers who were not sure why an application worked they could not figure out why things did not compile the did not know the difference between abstract superclass and interface and the could not figure out why change in place makes bunch of other modules in separate jar file crash the static type checking gave them false confidence in flawed design dynamic languages allow programs to be simple simplicity is substitute for static type checking clarity is substitute for static type checking
|
QA
|
how do convert any image to color paletted image using the python imaging library have device that supports color graphics much like cga in the old days wanted to use pil to read the image and convert it using my color palette of red green yellow black but cannot figure out if it is even possible at all found some mailing list archive posts that seem to suggest other people have tried to do so and failed simple python example would be much appreciated bonus points if you add something that then converts the image to byte string where each byte represents pixels of data with each two bits representing color from to
|
you are trying to do quantization of the image there is some tips here for that sort of thing here https web archive org web http nadiana com pil tips converting png gif
|
QA
|
is there way to convert indentation in python code to braces am totally blind programmer who would like to learn python unfortunately the fact that code blocks are represented with different levels of indentation is major stumbling block was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into properly indented representation that the python interpreter could use
|
use eclipse with the pydev extensions since it is an ide have lot of experience with also appreciate the smart indentation it offers for coding if statements loops etc have configured the pindent py script as an external tool that can run on the currently focused python module which makes my life easier so can see what is closed where with out having to constantly check indentation
|
QA
|
what is the best python soap stack for consuming amazon web services wsdl python has number of soap stacks as near as can tell all have substantial defects has anyone had luck consuming and using wsdl for ec and sqs in python my experience is that suds fails when constructing client object after some wrangling zsi generates client code that does not work etc finally am aware of boto but as it is hand rolled wrapper around aws it is incomplete and never up to date with the latest aws wsdl
|
the rest or query apis are definitely easier to use than soap but unfortunately at least once service ec does not provide any alternatives to soap as you have already discovered python existing soap implementations are woefully inadequate for most purposes one workaround approach is to just generate the xml for the soap envelope body directly instead of going through an intermediate soap layer if you are somewhat familiar with xml soap this is not too hard to do in most cases and allows you to work around any particular idiosyncrasies with the soap implementation on the other end this can be quite important as just about every soap stack out there has its own flavour of bugginess weirdness to contend with
|
QA
|
what does the yield keyword do what is the use of the yield keyword in python what does it do for example am trying to understand this code def get child candidates self distance min dist max dist if self leftchild and distance max dist self median yield self leftchild if self rightchild and distance max dist self median yield self rightchild and this is the caller result candidates list self while candidates node candidates pop distance node get dist obj if distance max dist and distance min dist result extend node values candidates extend node get child candidates distance min dist max dist return result what happens when the method get child candidates is called list is returned single element is returned is it called again when will subsequent calls stop the code comes from jochen schulz jrschulz who made great python library for metric spaces this is the link to the complete source module mspace
|
shortcut to grokking yield when you see function with yield statements apply this easy trick to understand what will happen insert line result at the start of the function replace each yield expr with result append expr insert line return result at the bottom of the function yay no more yield statements read and figure out code compare function to original definition this trick may give you an idea of the logic behind the function but what actually happens with yield is significantly different that what happens in the list based approach in many cases the yield approach will be lot more memory efficient and faster too in other cases this trick will get you stuck in an infinite loop even though the original function works just fine read on to learn more do not confuse your iterables iterators and generators first the iterator protocol when you write for in mylist loop body python performs the following two steps gets an iterator for mylist call iter mylist this returns an object with next method or next in python this is the step most people forget to tell you about uses the iterator to loop over items keep calling the next method on the iterator returned from step the return value from next is assigned to and the loop body is executed if an exception stopiteration is raised from within next it means there are no more values in the iterator and the loop is exited the truth is python performs the above two steps anytime it wants to loop over the contents of an object so it could be for loop but it could also be code like otherlist extend mylist where otherlist is python list here mylist is an iterable because it implements the iterator protocol in user defined class you can implement the iter method to make instances of your class iterable this method should return an iterator an iterator is an object with next method it is possible to implement both iter and next on the same class and have iter return self this will work for simple cases but not when you want two iterators looping over the same object at the same time so that is the iterator protocol many objects implement this protocol built in lists dictionaries tuples sets files user defined classes that implement iter generators note that for loop does not know what kind of object it is dealing with it just follows the iterator protocol and is happy to get item after item as it calls next built in lists return their items one by one dictionaries return the keys one by one files return the lines one by one etc and generators return well that is where yield comes in def yield yield yield for item in print item instead of yield statements if you had three return statements in only the first would get executed and the function would exit but is no ordinary function when is called it does not return any of the values in the yield statements it returns generator object also the function does not really exit it goes into suspended state when the for loop tries to loop over the generator object the function resumes from its suspended state at the very next line after the yield it previously returned from executes the next line of code in this case yield statement and returns that as the next item this happens until the function exits at which point the generator raises stopiteration and the loop exits so the generator object is sort of like an adapter at one end it exhibits the iterator protocol by exposing iter and next methods to keep the for loop happy at the other end however it runs the function just enough to get the next value out of it and puts it back in suspended mode why use generators usually you can write code that does not use generators but implements the same logic one option is to use the temporary list trick mentioned before that will not work in all cases for if you have infinite loops or it may make inefficient use of memory when you have really long list the other approach is to implement new iterable class somethingiter that keeps state in instance members and performs the next logical step in it is next or next in python method depending on the logic the code inside the next method may end up looking very complex and be prone to bugs here generators provide clean and easy solution
|
QA
|
how to get file creation modification date times in python have script that needs to do some stuff based on file creation modification dates but has to run on linux windows what is the best cross platform way to get file creation modification date times in python
|
os stat http www python org doc lib module stat html edit in newer code you should probably use os path getmtime thanks christian oudard but note that it returns floating point value of time with fraction seconds if your os supports it
|
QA
|
how to get file creation modification date times in python have script that needs to do some stuff based on file creation modification dates but has to run on linux windows what is the best cross platform way to get file creation modification date times in python
|
you have couple of choices for one you can use the os path getmtime and os path getctime functions import os path time print last modified time ctime os path getmtime file print created time ctime os path getctime file your other option is to use os stat import os time mode ino dev nlink uid gid size atime mtime ctime os stat file print last modified time ctime mtime note ctime does not refer to creation time on nix systems but rather the last time the inode data changed thanks to kojiro for making that fact more clear in the comments by providing link to an interesting blog post
|
QA
|
how to get file creation modification date times in python have script that needs to do some stuff based on file creation modification dates but has to run on linux windows what is the best cross platform way to get file creation modification date times in python
|
there are two methods to get the mod time os path getmtime or os stat but the ctime is not reliable cross platform see below os path getmtime getmtime path return the time of last modification of path the return value is number giving the number of seconds since the epoch see the time module raise os error if the file does not exist or is inaccessible new in version changed in version if os stat float times returns true the result is floating point number os stat stat path perform stat system call on the given path the return value is an object whose attributes correspond to the members of the stat structure namely st mode protection bits st ino inode number st dev device st nlink number of hard links st uid user id of owner st gid group id of owner st size size of file in bytes st atime time of most recent access st mtime time of most recent content modification st ctime platform dependent time of most recent metadata change on unix or the time of creation on windows import os statinfo os stat somefile txt statinfo statinfo st size in the above example you would use statinfo st mtime or statinfo st ctime to get the mtime and ctime respectively
|
QA
|
how to get file creation modification date times in python have script that needs to do some stuff based on file creation modification dates but has to run on linux windows what is the best cross platform way to get file creation modification date times in python
|
os stat returns named tuple with st mtime and st ctime attributes the modification time is st mtime on both platforms unfortunately on windows ctime means creation time whereas on posix it means change time am not aware of any way to get the creation time on posix platforms
|
QA
|
how to get file creation modification date times in python have script that needs to do some stuff based on file creation modification dates but has to run on linux windows what is the best cross platform way to get file creation modification date times in python
|
import os os stat feedparser py st mtime os stat feedparser py st ctime
|
QA
|
is there reason python strings do not have string length method know that python has len function that is used to determine the size of string but was wondering why its not method of the string object update ok realized was embarrassingly mistaken len is actually method of string object it just seems weird to see object oriented code in python using the len function on string objects furthermore it is also weird to see len as the name instead of just len
|
met python import this grep only one there should be one and preferably only one obvious way to do it
|
QA
|
is there reason python strings do not have string length method know that python has len function that is used to determine the size of string but was wondering why its not method of the string object update ok realized was embarrassingly mistaken len is actually method of string object it just seems weird to see object oriented code in python using the len function on string objects furthermore it is also weird to see len as the name instead of just len
|
there is len method string of some length len len method wrapper len of str object at
|
QA
|
is there reason python strings do not have string length method know that python has len function that is used to determine the size of string but was wondering why its not method of the string object update ok realized was embarrassingly mistaken len is actually method of string object it just seems weird to see object oriented code in python using the len function on string objects furthermore it is also weird to see len as the name instead of just len
|
strings do have length method len the protocol in python is to implement this method on objects which have length and use the built in len function which calls it for you similar to the way you would implement iter and use the built in iter function or have the method called behind the scenes for you on objects which are iterable see emulating container types for more information here is good read on the subject of protocols in python python and the principle of least astonishment
|
QA
|
multiple mouse pointers is there way to accept input from more than one mouse separately am interested in making multi user application and thought it would be great if could have or more users holding wireless mice each interacting with the app individually with separate mouse arrow is this something should try to farm out to some other application driver os magic or is there library can use to accomplish this language is not huge deal but and python are preferrable thanks edit found this multi pointer toolkit for linux it is actually multi pointer server http wearables unisa edu au mpx
|
yes know of at least one program that does this kidpad think it is written in java and was developed by juan pablo hourcade now at the university of iowa you would have to ask him how it was implemented
|
QA
|
multiple mouse pointers is there way to accept input from more than one mouse separately am interested in making multi user application and thought it would be great if could have or more users holding wireless mice each interacting with the app individually with separate mouse arrow is this something should try to farm out to some other application driver os magic or is there library can use to accomplish this language is not huge deal but and python are preferrable thanks edit found this multi pointer toolkit for linux it is actually multi pointer server http wearables unisa edu au mpx
|
you could use directinput with there is probably also bindings in other languages you use idirectinput enumdevices using dx same function different interface in other versions of directx to get list of all attached devices then you create the devices and poll them idirectinputdevice poll this should almost definitely work with any number of mice keyboards and other input devices msdn has really good documentation on this
|
QA
|
how do convert any image to color paletted image using the python imaging library have device that supports color graphics much like cga in the old days wanted to use pil to read the image and convert it using my color palette of red green yellow black but cannot figure out if it is even possible at all found some mailing list archive posts that seem to suggest other people have tried to do so and failed simple python example would be much appreciated bonus points if you add something that then converts the image to byte string where each byte represents pixels of data with each two bits representing color from to
|
first your four colour palette black green red yellow has no blue component so you have to accept that your output image will hardly approximate the input image unless there is no blue component to start with try this code import image def estimate color bit error new error if new bit bit error new else bit error new return bit error def image cga am produce sequence of cga pixels from image am im width am size for index in enumerate am getdata if index im width start of line error error bit error estimate color error bit error estimate color error yield bit bit def cvt cga imgfn convert an rgb image to cga image inp im image open imgfn assume it is rgb out im image new inp im size none out im putpalette out im putdata list image cga inp im return out im if name main import sys os for imgfn in sys argv am cvt cga imgfn dirname filename os path split imgfn name ext os path splitext filename newpathname os path join dirname cga png name am save newpathname this creates png palette image with only the first four palette entries set to your colours this sample image becomes it is trivial to take the output of image cga yields sequence of values and pack every four values to byte if you need help about what the code does please ask and will explain edit do not reinvent the wheel of course turns out was too enthusiastic and as thomas discovered the image quantize method can take palette image as argument and do the quantization with far better results than my ad hoc method above def cga quantize image pal image image new pal image putpalette return image convert rgb quantize palette pal image edit cont pack the pixels into bytes for added value here follows code to produce the packed string pixels per byte import itertools as it setup create map with tuples as keys and values chr chr because pil does not yet support colour palette images tuple char assume are pixel before are pixel call it big endian key builder pixel value used as index pixel pixel pixel for little endian uncomment the following line key builder reverse python has itertools product but for compatibility purposes let us do it verbosely for ix px in enumerate key builder for ix px in enumerate key builder for ix px in enumerate key builder for ix px in enumerate key builder tuple char ix ix ix ix chr px px px px another helper function copied almost verbatim from itertools docs def grouper iterable padvalue none grouper abcdefg would return it izip it chain iterable it repeat padvalue now the functions def seq str seq takes sequence of values and packs them into bytes using two bits per value return join tuple char four pixel for four pixel in grouper seq and the image related function note that the following function is correct but is not useful for windows colour bitmaps which start at the bottom row def image str img return seq str img getdata
|
QA
|
will django be good choice for permissions based web app have been exploring the details of django for about week now and like what see however have come upon some negativity in relation to fine grained control of permissions to the crud interface what am writing is an intranet client management web app the organisation is about tiers and need to restrict access to client groups based on tiers continually expanding have fairly good idea how am going to do this but am not sure if will be able to integrate it well into the pre built admin interface have done absolutely zero django development otherwise would probably have better idea on whether this would work or not probably will not use django if the generated admin interface is going to be useless to this project but like said there is heavy reliance on fine grained custom permissions will django let me build custom permissions rules and integrate it seamlessly into the admin crud interface update one want to use the admin app to minimise the repitition of generating crud interfaces so yes consider it must have update two want to describe the permissions required for this project client can belong to one or many stores full time employees should only be able to edit clients at their store even if they belong to another store however they should not be able to see edit clients at another store casuals should only be able to view clients based on what store they are rostered too or if the casual is logged in as the store user more likely management above them need to be able to see all employees for the stores they manage nothing more senior management should be able to edit all employees and grant permissions below themselves after reading the django documentation it says you cannot autmoatically set permissions for sub set of group only the entire group is it easy enough to mock up your own permissions for this purpose
|
if read your updated requirements correctly do not think django existing auth system will be sufficient it sounds like you need full on acl system this subject has come up number of times try googling on django acl random samplings there was summer of code project couple of years ago but am not sure where they got to see http code djangoproject com wiki genericauthorization there is fresh ticket at djngoproject org that might be interesting http code djangoproject com ticket there is some interesting code snips on dumpz org http dumpz org models py http dumpz org signals py but there are zero docs good luck
|
QA
|
any python libs for parsing apache config files any python libs for parsing apache config files or if not python anyone aware of such thing in other languages perl php java as will be able to rewrite them in python
|
no python libraries exist that know of but here is perl one http packages debian org sid libapache configfile perl package libapache configfile perl priority optional section interpreters installed size maintainer michael alan dorman version depends perl description parse an apache style httpd conf configuration file this module parses the apache httpd conf or any compatible config file and provides methods for you to access the values from the config file if you do rewrite it in python please update your post to mention the name of your package on pypi
|
QA
|
environment variables in python on linux python access to environment variables does not accurately reflect the operating system view of the processes environment os getenv and os environ do not function as expected in particular cases is there way to properly get the running process environment to demonstrate what mean take the two roughly equivalent programs the first in the other in python include stdio include stdlib include unistd int main int argc char argv char env for env getenv some variable if env puts env sleep import os import time while true env os getenv some variable if env is not none print env time sleep now if we run the program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this gdb print setenv some variable my value switching to thread lwp gdb print char getenv some variable my value then the aforementioned program will start spewing out my value once every seconds the aforementioned python program however will not is there way to get the python program to function like the program in this case yes realize this is very obscure and potentially damaging action to perform on running process also am currently using python this may have been fixed in later version of python
|
another possibility is to use pdb or some other python debugger instead and change os environ at the python level rather than the level here is small recipe posted to interrupt running python process and provide access to python console on receiving signal alternatively just stick pdb set trace at some point in your code you want to interrupt in either case just run the statement import os os environ some variable my value and you should be updated as far as python is concerned am not sure if this will also update the environment with setenv so if you have modules using getenv directly you may have to do some more work to keep this in sync
|
QA
|
any python libs for parsing bind zone files any python libs for parsing bind zone files basically something that will aid in adding removing zones and records this needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not solution
|
see answer above about bicop as an aside the python package index at http pypi python org pypi is great place to look for python packages edit the below may still be helpful to someone trying to figure out simple parsing but bicop is apparently an existing solution if someone has modified the config by hand and you do not want to overwrite it does that imply that you wish to insert remove lines from an existing config leaving all comments etc intact that does prevent parsing then re outputting the config but that is positive as well you do not need to fully parse the file to accomplish your goal to add record you might try simple approach like define zone you care about and line you wish to insert first then for line in bindfile read out write line if zone in zone you care about in line out write line you wish to insert similar code works for removing line define zone you care about and relevant text to remove then for line in bindfile read if not relevant text to remove in line out write line you may get as far as you need with simple snippets of code like this
|
QA
|
how to disable html encoding when using context in django in my django application am using template to construct email body one of the parameters is url note there are two parametes separated by ampersand in the url loader get template sometemplate context foo bar url http test print render after rendering it produces http test amp amp note the ampersand is html encoded as amp one way around the problem is to pass each parameter separately to my template and construct the url in the template however would like to avoid doing that is there way to disable html encoding of context parameters or at the very least avoid encoding of ampersands
|
to turn it off for single variable use mark safe from django utils safestring import mark safe loader get template sometemplate context foo bar url mark safe http test print render alternatively to totally turn autoescaping off from your python code use the autoescape argument when initialising context context foo bar url http test autoescape false the how to turn automatic html escaping off section of the documentation covers some of the in template options if you would rather do it there
|
QA
|
is there reason python strings do not have string length method know that python has len function that is used to determine the size of string but was wondering why its not method of the string object update ok realized was embarrassingly mistaken len is actually method of string object it just seems weird to see object oriented code in python using the len function on string objects furthermore it is also weird to see len as the name instead of just len
|
jim answer to this question may help copy it here quoting guido van rossum first of all chose len over len for hci reasons def len came much later there are two intertwined reasons actually both hci for some operations prefix notation just reads better than postfix prefix and infix operations have long tradition in mathematics which likes notations where the visuals help the mathematician thinking about problem compare the easy with which we rewrite formula like into to the clumsiness of doing the same thing using raw oo notation when read code that says len know that it is asking for the length of something this tells me two things the result is an integer and the argument is some kind of container to the contrary when read len have to already know that is some kind of container implementing an interface or inheriting from class that has standard len witness the confusion we occasionally have when class that is not implementing mapping has get or keys method or something that isn file has write method saying the same thing in another way see len as built in operation hate to lose that
|
QA
|
is there reason python strings do not have string length method know that python has len function that is used to determine the size of string but was wondering why its not method of the string object update ok realized was embarrassingly mistaken len is actually method of string object it just seems weird to see object oriented code in python using the len function on string objects furthermore it is also weird to see len as the name instead of just len
|
it does not abc len
|
QA
|
multiple mouse pointers is there way to accept input from more than one mouse separately am interested in making multi user application and thought it would be great if could have or more users holding wireless mice each interacting with the app individually with separate mouse arrow is this something should try to farm out to some other application driver os magic or is there library can use to accomplish this language is not huge deal but and python are preferrable thanks edit found this multi pointer toolkit for linux it is actually multi pointer server http wearables unisa edu au mpx
|
have this vague feeling that beos used to let one pair mouse and keyboard and have separate active windows and inputs wow that was long time ago thought that it would be very interesting for paired programming
|
QA
|
how to disable html encoding when using context in django in my django application am using template to construct email body one of the parameters is url note there are two parametes separated by ampersand in the url loader get template sometemplate context foo bar url http test print render after rendering it produces http test amp amp note the ampersand is html encoded as amp one way around the problem is to pass each parameter separately to my template and construct the url in the template however would like to avoid doing that is there way to disable html encoding of context parameters or at the very least avoid encoding of ampersands
|
or just use the safe filter in your template also cannot stress enough how important it is to be familiar with django documentation many common questions like this have easy to find answers and explanations like this one and reading through the docs and getting feel for how everything works will drastically decrease the amount of time you need to spend ask why did it do that and increase the amount of time you spend building things that work the way you want
|
QA
|
python properties and inheritance have base class with property which the get method want to overwrite in the subclass my first thought was something like class foo object def get age self return age property get age class bar foo def get age self return this does not work subclass bar age returns found solution with an lambda expression which works age property lambda self self get age so is this the right solution for using properties and overwrite them in subclass or are there other preferred ways to do this
|
agree with your solution which seems an on the fly template method this article deals with your problem and provides exactly your solution
|
QA
|
python properties and inheritance have base class with property which the get method want to overwrite in the subclass my first thought was something like class foo object def get age self return age property get age class bar foo def get age self return this does not work subclass bar age returns found solution with an lambda expression which works age property lambda self self get age so is this the right solution for using properties and overwrite them in subclass or are there other preferred ways to do this
|
yes this is the way to do it the property declaration executes at the time the parent class definition is executed which means it can only see the versions of the methods which exist on the parent class so when you redefine one or more of those methods on child class you need to re declare the property using the child class version of the method
|
QA
|
python properties and inheritance have base class with property which the get method want to overwrite in the subclass my first thought was something like class foo object def get age self return age property get age class bar foo def get age self return this does not work subclass bar age returns found solution with an lambda expression which works age property lambda self self get age so is this the right solution for using properties and overwrite them in subclass or are there other preferred ways to do this
|
something like this will work class hackedproperty object def init self self def get self inst owner return getattr inst self name class foo object def get age self return age hackedproperty get age class bar foo def get age self return print bar age print foo age
|
QA
|
any python libs for parsing apache config files any python libs for parsing apache config files or if not python anyone aware of such thing in other languages perl php java as will be able to rewrite them in python
|
zconfig think used to ship with schema for parsing apache configuration files it does not seem to anymore but it is oriented around parsing those types of files and turning the config into python object quick glance at the documentation suggests it would not be too hard to set up zconfig schema corresponding to whatever apache options you would like to parse and validate http pypi python org pypi zconfig
|
QA
|
any python libs for parsing apache config files any python libs for parsing apache config files or if not python anyone aware of such thing in other languages perl php java as will be able to rewrite them in python
|
red hat emerging technologies group has augeas written in but with python bindings available generic system configuration tool with lenses for reading and writing several different configuration file formats would consider investigating the availability of lens for apache
|
QA
|
how do parse listing of files to get just the filenames in python so let us say am using python ftplib to retrieve list of log files from an ftp server how would parse that list of files to get just the file names the last column inside list see the link above for example output
|
believe it should work for you file name list join each file split split for each file detail in file list from log notes here am making assumption that you want the data in the program as list not on console each file detail is each line that is being produced by the program join each file split to replace multiple spaces by space
|
QA
|
how do parse listing of files to get just the filenames in python so let us say am using python ftplib to retrieve list of log files from an ftp server how would parse that list of files to get just the file names the last column inside list see the link above for example output
|
using retrlines probably is not the best idea there since it just prints to the console and so you would have to do tricky things to even get at that output likely better bet would be to use the nlst method which returns exactly what you want list of the file names
|
QA
|
how do parse listing of files to get just the filenames in python so let us say am using python ftplib to retrieve list of log files from an ftp server how would parse that list of files to get just the file names the last column inside list see the link above for example output
|
and slightly less optimal method by the way if you are stuck using retrlines for some reason is to pass function as the second argument to retrlines it will be called for each item in the list so something like this assuming you have an ftp object named ftp would work as well filenames ftp retrlines list lambda line filenames append line split the list filenames will then be list of the file names
|
QA
|
how do parse listing of files to get just the filenames in python so let us say am using python ftplib to retrieve list of log files from an ftp server how would parse that list of files to get just the file names the last column inside list see the link above for example output
|
since every filename in the output starts at the same column all you have to do is get the position of the dot on the first line drwxrwsr ftp usr pdmaint mar then slice the filename out of the other lines using the position of that dot as the starting index since the dot is the last character on the line you can use the length of the line minus as the index so the final code is something like this lines ftp retrlines list lines lines split this should split the string into an array of lines filename index len lines files for line in lines files append line filename index
|
QA
|
how do parse listing of files to get just the filenames in python so let us say am using python ftplib to retrieve list of log files from an ftp server how would parse that list of files to get just the file names the last column inside list see the link above for example output
|
is there any reason why ftplib ftp nlst will not work for you just checked and it returns only names of the files in given directory
|
QA
|
how do convert any image to color paletted image using the python imaging library have device that supports color graphics much like cga in the old days wanted to use pil to read the image and convert it using my color palette of red green yellow black but cannot figure out if it is even possible at all found some mailing list archive posts that seem to suggest other people have tried to do so and failed simple python example would be much appreciated bonus points if you add something that then converts the image to byte string where each byte represents pixels of data with each two bits representing color from to
|
john found that first link as well but it did not directly help me with the problem it did make me look deeper into quantize though came up with this yesterday before going to bed import sys import pil import image palette black green red yellow palette image to use for quant pimage image new pimage putpalette palette open the source image image image open sys argv image image convert rgb quantize it using our palette image imagep image quantize palette pimage save imagep save tmp cga png tz tzioy your solution seems to work along the same principles kudos should have stopped working on it and waited for your reply mine is bit simpler although definately not more logical than yours pil is cumbersome to use yours explains what is going on to do it
|
QA
|
how do parse listing of files to get just the filenames in python so let us say am using python ftplib to retrieve list of log files from an ftp server how would parse that list of files to get just the file names the last column inside list see the link above for example output
|
this best answer you may want to use ftp nlst instead of ftp retrlines it will give you exactly what you want if you cannot read the following generators for sysadmin processes in his now famous review generator tricks for systems programmers an introduction david beazley gives lot of receipes to answer to this kind of data problem with wuick and reusable code empty list that will receive all the log entry log we pass callback function bypass the print line that would be called by retrlines we do that only because we cannot use something better than retrlines ftp retrlines list callback log append we use rsplit because it more efficient in our case if we have big file files line rsplit none for line in log get you file list files list list files why do not we generate immediately the list well it is because doing it this way offer you much flexibility you can apply any intermediate generator to filter files before turning it into files list it is just like pipe add line you add process without overheat since it is generators and if you get rid off retrlines it still work be it is even better because you do not store the liste even one time edit well read the comment to the other answer and it says that this will not work if there is any space in the name cool this will illustrate why this method is handy if you want to change something in the process you just change line swap files line rsplit none for line in log and join split the line get all the item from the field then join them files join line split for line in log ok this may no be obvious here but for huge batch process scripts it is nice
|
QA
|
daylight savings time change affecting the outcome of saving and loading an icalendar file have some unit tests that started failing today after switch in daylight savings time we are using the icalendar python module to load and save ics files the following script is simplified version of our test the script works fine in summer and fails in winter as of this morning the failure can be reproduced by setting the clock back manually here is the output of the script root ana icalendar date sat oct cest root ana icalendar python dst py dtstart should represent datetime datetime tzinfo tzfile usr share zoneinfo europe brussels brussels time dtstart should represent datetime datetime tzinfo icalendar prop utc object at cc utc dtstart represents datetime datetime tzinfo icalendar prop utc object at cc brussels time root ana icalendar date sun oct cet root ana icalendar python dst py dtstart should represent datetime datetime tzinfo tzfile usr share zoneinfo europe brussels brussels time dtstart should represent datetime datetime tzinfo icalendar prop utc object at cc utc dtstart represents datetime datetime tzinfo icalendar prop utc object at cc brussels time traceback most recent call last file dst py line in module start dt startutcexpected assertionerror calendar datetime datetime tzinfo icalendar prop utc object at cc expected datetime datetime tzinfo icalendar prop utc object at cc and here is the whole script so questions why would my current time and which part of dst am in affect the loading saving parsing of timestamps would expect it not to how would you unit test this kind of bug if it is bug obviously do not want my unit tests to reset the clock on my computer
|
without looking at your code and the quoted test run script my brain fails to understand right now notice that you try to get time that is in different timezone than the one you are at think of dst as another timezone instead of hour from current timezone this could depending on how you do it lead to gain or loss of hours like when your flying you start at one time and getting to your location before you started all in local time
|
QA
|
python properties and inheritance have base class with property which the get method want to overwrite in the subclass my first thought was something like class foo object def get age self return age property get age class bar foo def get age self return this does not work subclass bar age returns found solution with an lambda expression which works age property lambda self self get age so is this the right solution for using properties and overwrite them in subclass or are there other preferred ways to do this
|
simply prefer to repeat the property as well as you will repeat the classmethod decorator when overriding class method while this seems very verbose at least for python standards you may notice for read only properties property can be used as decorator class foo object property def age self return class bar foo property def age self return in python properties grew pair of methods setter and deleter which can be used to apply to general properties the shortcut already available for read only ones class object property def self return self setter def self value self value
|
QA
|
formatting dict items for wxpython have text box in wxpython that takes the output of dictionary items and displays it to the user as items are added to the dictionary however the raw data is very ugly looking like you because you chm you cpm know dictionary items is list of tuples but cannot seem to figure out how to make nice format that is also compatible with the setvalue method of wxpython have tried iterating through the list and tuples if use print statement the output is fine but when replace the print statement with setvalue it only seems to get the last value of each tuple rather than both items in the tuple have also tried creating string and passing that string to setvalue but again can only get one item in the tuple or the other not both any suggestions edit yes am passing the results of the dictionary items to text field in wxpython application rather than having the results like above am simply looking for something like because chm cmp nothing special just simply pulling each value from each tuple and making visual list have tried making string format and passing that to setvalue but it gets hung up on the two values in the tuple it will either double print each string and add the integers together or it simply returns the integer depending on how format it
|
maybe the pretty print module will help import pprint pprint pformat my key my value my key my value
|
QA
|
refactoring to hit values for game am making game and one of the methods calculates character base hit numbers based on skill values the method currently calculates each value individually since each skill can be used at short medium and long range originally thought could combine the skills into tuple and iterate over it dynamically creating each hit number but do not know if it is actually possible since currently have each hit number assigned to it is own variable also thought about creating method for each range and passing the tuple as an argument could create new tuple or list with the resulting values and then assign them to the individual variables but do not see how it would be any better than do it this way except that it will not look so copy pasted here is what currently have def calcbasehitnumbers self dict calculate character base hit numbers depending on skill level self skill dict dict self rifle self skill dict get crm self pistol self skill dict get pst self big gun self skill dict get lcg self heavy weapon self skill dict get hw self bow self skill dict get lb self skill tuple self rifle self pistol self big gun self heavy weapon self bow short range for skill in self skill tuple self base hit short skill self charattribs bhcrm short self rifle self charattribs bhpst short self pistol self charattribs bhhw short self heavy weapon self charattribs bhlcg short self big gun self charattribs bhlb short self bow med range self charattribs bhcrm med self rifle self charattribs bhpst med self pistol self charattribs bhhw med self heavy weapon self charattribs bhlcg med self big gun self charattribs bhlb med self bow long range self charattribs bhcrm long self rifle self charattribs bhpst long self pistol self charattribs bhhw long self heavy weapon self charattribs bhlcg long self big gun self charattribs bhlb long self bow how would you refactor this so it is more dynamic edit guess what want to do is something like this have tuple like the one commented out and iterate over it times each time making new value for each skill based on the modifier for each particular range the resulting value is then automatically assigned to it is respective variable in my head it makes sense but when actually try to code it get lost the problem think is that this is the first real program have written all have done before are small scripts this is only the version of my program so it is not critical to refactor it now however it seems very un pythonic to do this manually and also want to future proof this in case things change down the road
|
vinko perhaps make calcbasehitnumbers do the if not self calculatedbase check internally and just no op if it is been done before that said cannot see the pressing need for precalculating this information but am no python performance expert
|
QA
|
refactoring to hit values for game am making game and one of the methods calculates character base hit numbers based on skill values the method currently calculates each value individually since each skill can be used at short medium and long range originally thought could combine the skills into tuple and iterate over it dynamically creating each hit number but do not know if it is actually possible since currently have each hit number assigned to it is own variable also thought about creating method for each range and passing the tuple as an argument could create new tuple or list with the resulting values and then assign them to the individual variables but do not see how it would be any better than do it this way except that it will not look so copy pasted here is what currently have def calcbasehitnumbers self dict calculate character base hit numbers depending on skill level self skill dict dict self rifle self skill dict get crm self pistol self skill dict get pst self big gun self skill dict get lcg self heavy weapon self skill dict get hw self bow self skill dict get lb self skill tuple self rifle self pistol self big gun self heavy weapon self bow short range for skill in self skill tuple self base hit short skill self charattribs bhcrm short self rifle self charattribs bhpst short self pistol self charattribs bhhw short self heavy weapon self charattribs bhlcg short self big gun self charattribs bhlb short self bow med range self charattribs bhcrm med self rifle self charattribs bhpst med self pistol self charattribs bhhw med self heavy weapon self charattribs bhlcg med self big gun self charattribs bhlb med self bow long range self charattribs bhcrm long self rifle self charattribs bhpst long self pistol self charattribs bhhw long self heavy weapon self charattribs bhlcg long self big gun self charattribs bhlb long self bow how would you refactor this so it is more dynamic edit guess what want to do is something like this have tuple like the one commented out and iterate over it times each time making new value for each skill based on the modifier for each particular range the resulting value is then automatically assigned to it is respective variable in my head it makes sense but when actually try to code it get lost the problem think is that this is the first real program have written all have done before are small scripts this is only the version of my program so it is not critical to refactor it now however it seems very un pythonic to do this manually and also want to future proof this in case things change down the road
|
let us see if understand you scenario each weapon has its own distinct hit point so rifle may have heavy weapon may have etc then each character has short medium and long value to be multiplied by the hit point of the weapon you should consider using strategy design that is create weapon superclass with hit point property create sub class weapons for rifle pistol bow etc am sure that the differences between the weapons are more than just the hit points then the character has one or more weapons depending on your gameplay to calculate the hit point for particular weapon is as simple as current weapon self medium if you decide to add more weapons later on then you do not have to edit your character code because your character can handle any weapon in pseudo python class weapon hit other properties of weapon class rifle weapon other properties of rifle class pistol weapon other properties of pistol class character weapon rifle long def calchit return self long weapon hit john character john weapon rifle john calchit
|
QA
|
refactoring to hit values for game am making game and one of the methods calculates character base hit numbers based on skill values the method currently calculates each value individually since each skill can be used at short medium and long range originally thought could combine the skills into tuple and iterate over it dynamically creating each hit number but do not know if it is actually possible since currently have each hit number assigned to it is own variable also thought about creating method for each range and passing the tuple as an argument could create new tuple or list with the resulting values and then assign them to the individual variables but do not see how it would be any better than do it this way except that it will not look so copy pasted here is what currently have def calcbasehitnumbers self dict calculate character base hit numbers depending on skill level self skill dict dict self rifle self skill dict get crm self pistol self skill dict get pst self big gun self skill dict get lcg self heavy weapon self skill dict get hw self bow self skill dict get lb self skill tuple self rifle self pistol self big gun self heavy weapon self bow short range for skill in self skill tuple self base hit short skill self charattribs bhcrm short self rifle self charattribs bhpst short self pistol self charattribs bhhw short self heavy weapon self charattribs bhlcg short self big gun self charattribs bhlb short self bow med range self charattribs bhcrm med self rifle self charattribs bhpst med self pistol self charattribs bhhw med self heavy weapon self charattribs bhlcg med self big gun self charattribs bhlb med self bow long range self charattribs bhcrm long self rifle self charattribs bhpst long self pistol self charattribs bhhw long self heavy weapon self charattribs bhlcg long self big gun self charattribs bhlb long self bow how would you refactor this so it is more dynamic edit guess what want to do is something like this have tuple like the one commented out and iterate over it times each time making new value for each skill based on the modifier for each particular range the resulting value is then automatically assigned to it is respective variable in my head it makes sense but when actually try to code it get lost the problem think is that this is the first real program have written all have done before are small scripts this is only the version of my program so it is not critical to refactor it now however it seems very un pythonic to do this manually and also want to future proof this in case things change down the road
|
what sense of dynamic do you mean what is likely to vary the number of skills or the weighting factors the number of ranges short med long or all of these what happens to the bhpst values afterwards do they get combined into one number one thing that leaps out is that the list of skills is hardwired in the code would be inclined to replace the bh variables with method so please take into account do not know the first thing about python def bh short self key skill self skill dict get key return skill now you can keep list of skills that contribute to hit points and iterate over that calling bh short etc possibly also pass the range long med short unto the function or return all three values this all depends on what you are going to do next with the calculated hitpoints basically we need more information about the context this is to be used in
|
QA
|
refactoring to hit values for game am making game and one of the methods calculates character base hit numbers based on skill values the method currently calculates each value individually since each skill can be used at short medium and long range originally thought could combine the skills into tuple and iterate over it dynamically creating each hit number but do not know if it is actually possible since currently have each hit number assigned to it is own variable also thought about creating method for each range and passing the tuple as an argument could create new tuple or list with the resulting values and then assign them to the individual variables but do not see how it would be any better than do it this way except that it will not look so copy pasted here is what currently have def calcbasehitnumbers self dict calculate character base hit numbers depending on skill level self skill dict dict self rifle self skill dict get crm self pistol self skill dict get pst self big gun self skill dict get lcg self heavy weapon self skill dict get hw self bow self skill dict get lb self skill tuple self rifle self pistol self big gun self heavy weapon self bow short range for skill in self skill tuple self base hit short skill self charattribs bhcrm short self rifle self charattribs bhpst short self pistol self charattribs bhhw short self heavy weapon self charattribs bhlcg short self big gun self charattribs bhlb short self bow med range self charattribs bhcrm med self rifle self charattribs bhpst med self pistol self charattribs bhhw med self heavy weapon self charattribs bhlcg med self big gun self charattribs bhlb med self bow long range self charattribs bhcrm long self rifle self charattribs bhpst long self pistol self charattribs bhhw long self heavy weapon self charattribs bhlcg long self big gun self charattribs bhlb long self bow how would you refactor this so it is more dynamic edit guess what want to do is something like this have tuple like the one commented out and iterate over it times each time making new value for each skill based on the modifier for each particular range the resulting value is then automatically assigned to it is respective variable in my head it makes sense but when actually try to code it get lost the problem think is that this is the first real program have written all have done before are small scripts this is only the version of my program so it is not critical to refactor it now however it seems very un pythonic to do this manually and also want to future proof this in case things change down the road
|
it feels like what you really want is class representing the weapon with attributes to handle the base values and calculate hit values with various modifiers here is simple example short range medium range long range short range modifier medium range modifier long range modifier class weapon object def init self code name full name base hit value short range modifier none medium range modifier none long range modifier none self code name self full name code name full name self base hit value base hit value self range modifiers short range short range modifier or short range modifier medium range medium range modifier or medium range modifier long range long range modifier or long range modifier def hit value self range modifier return self base hit value self range modifiers range modifier from there you might create instances of weapon inside your character object like so self rifle weapon crm rifle self pistol weapon pst pistol and then if say the character fires the pistol at short range hit value self pistol hit value short range the extra argument to the hit value method can be used to pass in character or situation specific modifications of course the next step beyond this would be to directly model the weapons as subclasses of weapon perhaps breaking down into specific types of weapons like guns bows grenades etc each with their own base values and add an inventory class to represent the weapons character is carrying all of this is pretty standard boring object oriented design procedure but for plenty of situations this type of thinking will get you off the ground quickly and provide at least little bit of basic flexibility
|
QA
|
formatting dict items for wxpython have text box in wxpython that takes the output of dictionary items and displays it to the user as items are added to the dictionary however the raw data is very ugly looking like you because you chm you cpm know dictionary items is list of tuples but cannot seem to figure out how to make nice format that is also compatible with the setvalue method of wxpython have tried iterating through the list and tuples if use print statement the output is fine but when replace the print statement with setvalue it only seems to get the last value of each tuple rather than both items in the tuple have also tried creating string and passing that string to setvalue but again can only get one item in the tuple or the other not both any suggestions edit yes am passing the results of the dictionary items to text field in wxpython application rather than having the results like above am simply looking for something like because chm cmp nothing special just simply pulling each value from each tuple and making visual list have tried making string format and passing that to setvalue but it gets hung up on the two values in the tuple it will either double print each string and add the integers together or it simply returns the integer depending on how format it
|
text for display join item you unicode value for item value in my dictionary items
|
QA
|
formatting dict items for wxpython have text box in wxpython that takes the output of dictionary items and displays it to the user as items are added to the dictionary however the raw data is very ugly looking like you because you chm you cpm know dictionary items is list of tuples but cannot seem to figure out how to make nice format that is also compatible with the setvalue method of wxpython have tried iterating through the list and tuples if use print statement the output is fine but when replace the print statement with setvalue it only seems to get the last value of each tuple rather than both items in the tuple have also tried creating string and passing that string to setvalue but again can only get one item in the tuple or the other not both any suggestions edit yes am passing the results of the dictionary items to text field in wxpython application rather than having the results like above am simply looking for something like because chm cmp nothing special just simply pulling each value from each tuple and making visual list have tried making string format and passing that to setvalue but it gets hung up on the two values in the tuple it will either double print each string and add the integers together or it simply returns the integer depending on how format it
|
use formatting known in as sprintf dict items number of conversion specifications in the format string should match tuple length in the dict items case the result of the string formatting operator is string so that using it as an argument to setvalue is no problem to translate the whole dict to string join for in dict items the format conversion types are specified in the doc
|
QA
|
what is your convention to distinguish between object methods to be called by the outside and object methods to be called by subclass know most of the ins and outs of python approach to private variables members functions however cannot make my mind up on how to distinguish between methods for external use or subclassing use consider the following example class eventmixin object def subscribe self kwargs kwargs should be dict of event callable to be specialized in the subclass def event self name args kwargs def someprivatemethod self in this example want to make it clear that subscribe is method to be used by external users of the class object while event is method that should not be called from the outside but rather by subclass implementations right now consider both part of the public api hence do not use any underscores however for this particular situation it would feel cleaner to for example use no underscores for the external api one underscore for the subclassable api and two underscores for the private internal api however that would become unwieldy because then the internal api would need to be invoked as self eventmixin someprivatemethod so what are your conventions coding wise documentationwise or otherwise
|
would like to make the suggestion that when you find yourself encountering this kind of distinction it may be good idea to consider using composition instead of inheritance in other words instantiating eventmixin presumably the name would change instead of inheriting it
|
QA
|
formatting dict items for wxpython have text box in wxpython that takes the output of dictionary items and displays it to the user as items are added to the dictionary however the raw data is very ugly looking like you because you chm you cpm know dictionary items is list of tuples but cannot seem to figure out how to make nice format that is also compatible with the setvalue method of wxpython have tried iterating through the list and tuples if use print statement the output is fine but when replace the print statement with setvalue it only seems to get the last value of each tuple rather than both items in the tuple have also tried creating string and passing that string to setvalue but again can only get one item in the tuple or the other not both any suggestions edit yes am passing the results of the dictionary items to text field in wxpython application rather than having the results like above am simply looking for something like because chm cmp nothing special just simply pulling each value from each tuple and making visual list have tried making string format and passing that to setvalue but it gets hung up on the two values in the tuple it will either double print each string and add the integers together or it simply returns the integer depending on how format it
|
that data seems much better displayed as table grid
|
QA
|
how do you log server errors on django sites so when playing with the development can just set settings debug to true and if an error occures can see it nicely formatted with good stack trace and request information but on kind of production site would rather use debug false and show visitors some standard error page with information that am working on fixing this bug at this moment at the same time would like to have some way of logging all those information stack trace and request info to file on my server so can just output it to my console and watch errors scroll email the log to me every hour or something like this what logging solutions would you recomend for django site that would meet those simple requirements have the application running as fcgi server and am using apache web server as frontend although thinking of going to lighttpd
|
well when debug false django will automatically mail full traceback of any error to each person listed in the admins setting which gets you notifications pretty much for free if you would like more fine grained control you can write and add to your settings middleware class which defines method named process exception which will have access to the exception that was raised http docs djangoproject com en dev topics http middleware process exception your process exception method can then perform whatever type of logging you would like writing to console writing to file etc etc edit though it is bit less useful you can also listen for the got request exception signal which will be sent whenever an exception is encountered during request processing http docs djangoproject com en dev ref signals got request exception this does not give you access to the exception object however so the middleware method is much easier to work with
|
QA
|
pattern matching of lists in python want to do some pattern matching on lists in python for example in haskell can do something like the following fun head rest so when pass in list head will be the first element and rest will be the trailing elements likewise in python can automatically unpack tuples var var func that returns tuple want to do something similar with lists in python right now have function that returns list and chunk of code that does the following ls my func head rest ls ls wondered if could somehow do that in one line in python instead of two
|
that is very much pure functional approach and as such is sensible idiom in haskell but it is probably not so appropriate to python python only has very limited concept of patterns in this way and suspect you might need somewhat more rigid type system to implement that sort of construct erlang buffs invited to disagree here what you have is probably as close as you would get to that idiom but you are probably better off using list comprehension or imperative approach rather than recursively calling function with the tail of the list as has been stated on few occasions before python is not actually functional language it just borrows ideas from the fp world it is not inherently tail recursive in the way you would expect to see embedded in the architecture of functional language so you would have some difficulty doing this sort of recursive operation on large data set without using lot of stack space
|
QA
|
pattern matching of lists in python want to do some pattern matching on lists in python for example in haskell can do something like the following fun head rest so when pass in list head will be the first element and rest will be the trailing elements likewise in python can automatically unpack tuples var var func that returns tuple want to do something similar with lists in python right now have function that returns list and chunk of code that does the following ls my func head rest ls ls wondered if could somehow do that in one line in python instead of two
|
so far as know there is no way to make it one liner in current python without introducing another function split list lambda lst lst lst head rest split list my func however in python the specialized syntax used for variadic argument signatures and argument unpacking will become available for this type of general sequence unpacking as well so in you will be able to write head rest my func see pep for details
|
QA
|
pattern matching of lists in python want to do some pattern matching on lists in python for example in haskell can do something like the following fun head rest so when pass in list head will be the first element and rest will be the trailing elements likewise in python can automatically unpack tuples var var func that returns tuple want to do something similar with lists in python right now have function that returns list and chunk of code that does the following ls my func head rest ls ls wondered if could somehow do that in one line in python instead of two
|
well why you want it in line in the first place if you really want to you can always do trick like this def func func return then instead of calling my func call my func head rest my func that is one line
|
QA
|
pattern matching of lists in python want to do some pattern matching on lists in python for example in haskell can do something like the following fun head rest so when pass in list head will be the first element and rest will be the trailing elements likewise in python can automatically unpack tuples var var func that returns tuple want to do something similar with lists in python right now have function that returns list and chunk of code that does the following ls my func head rest ls ls wondered if could somehow do that in one line in python instead of two
|
extended unpacking was introduced in http www python org dev peps pep
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.