prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
why is my instance variable not in dict if create class as follows class def init self self name inspecting the dict member looks like name if however create class class name dict is empty what is the difference between the two and why does not name show up in dict
name is class attribute not an instance attribute it shows up in dict but not in dict the distinction is obscured somewhat because when you access an attribute on an instance the class dict is fallback so in the above example name will give you the value of name
QA
how to escape os system calls in python when using os system it is often necessary to escape filenames and other arguments passed as parameters to commands how can do this preferably something that would work on multiple operating systems shells but in particular for bash am currently doing the following but am sure there must be library function for this or at least more elegant robust efficient option def sh escape return replace replace replace os system cat grep something sort sh escape in filename sh escape out filename edit have accepted the simple answer of using quotes do not know why did not think of that guess because came from windows where and behave little differently regarding security understand the concern but in this case am interested in quick and easy solution which os system provides and the source of the strings is either not user generated or at least entered by trusted user me
believe that os system just invokes whatever command she will is configured for the user so do not think you can do it in platform independent way my command she will could be anything from bash emacs ruby or even quake some of these programs are not expecting the kind of arguments you are passing to them and even if they did there is no guarantee they do their escaping the same way
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing python with modules do you think it is proper for production use in the development of stand alone complex applications think for example to word processor or graphic tool what ide would you suggest the idle provided with python is not enough even for small projects in my opinion
know am probably stating the obvious but do not forget that the quality of the development team and their familiarity with the technology will have major impact on your ability to deliver if you have strong team then it is probably not an issue if they are familiar but if you have people who are more to rs who are not familiar with the technology they will need more support and you would need to make call if the productivity gains are worth whatever the cost of that support is
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing python with modules do you think it is proper for production use in the development of stand alone complex applications think for example to word processor or graphic tool what ide would you suggest the idle provided with python is not enough even for small projects in my opinion
refactoring is inevitable on larger codebases and the lack of static typing makes this much harder in python than in statically typed languages
QA
how to escape os system calls in python when using os system it is often necessary to escape filenames and other arguments passed as parameters to commands how can do this preferably something that would work on multiple operating systems shells but in particular for bash am currently doing the following but am sure there must be library function for this or at least more elegant robust efficient option def sh escape return replace replace replace os system cat grep something sort sh escape in filename sh escape out filename edit have accepted the simple answer of using quotes do not know why did not think of that guess because came from windows where and behave little differently regarding security understand the concern but in this case am interested in quick and easy solution which os system provides and the source of the strings is either not user generated or at least entered by trusted user me
this is what use def shellquote return replace the she will will always accept quoted filename and remove the surrounding quotes before passing it to the program in question notably this avoids problems with filenames that contain spaces or any other kind of nasty she will metacharacter update if you are using python or later use shlex quote instead of rolling your own
QA
how to escape os system calls in python when using os system it is often necessary to escape filenames and other arguments passed as parameters to commands how can do this preferably something that would work on multiple operating systems shells but in particular for bash am currently doing the following but am sure there must be library function for this or at least more elegant robust efficient option def sh escape return replace replace replace os system cat grep something sort sh escape in filename sh escape out filename edit have accepted the simple answer of using quotes do not know why did not think of that guess because came from windows where and behave little differently regarding security understand the concern but in this case am interested in quick and easy solution which os system provides and the source of the strings is either not user generated or at least entered by trusted user me
perhaps you have specific reason for using os system but if not you should probably be using the subprocess module you can specify the pipes directly and avoid using the she will the following is from pep replacing she will pipe line output dmesg grep hda popen dmesg stdout pipe popen grep hda stdin stdout stdout pipe output communicate
QA
django templates and variable attributes am using google app engine and django templates have table that want to display the objects look something like object result items item item users name username item item the django template is table tr align center th user th for item in result items th item th endfor tr for user in result users tr align center td user name td for item in result items td user item td endfor tr endfor table now the django documention states that when it sees in variables it tries several things to get the data one of which is dictionary lookup which is exactly what want but does not seem to happen
am assuming that the part the does not work is user item django will be trying dictionary lookup but using the string item and not the value of the item loop variable django did the same thing when it resolved user name to the name attribute of the user object rather than looking for variable called name think you will need to do some preprocessing of the data in your view before you render it in your template
QA
like structures in python is there way to conveniently define like structure in python am tired of writing stuff like class mystruct def init self field field field self field field self field field self field field
how about dictionary something like this mystruct field some val field some val then you can use this to manipulate values print mystruct field mystruct field some other values and the values do not have to be strings they can be pretty much any other object
QA
like structures in python is there way to conveniently define like structure in python am tired of writing stuff like class mystruct def init self field field field self field field self field field self field field
you can use tuple for lot of things where you would use struct in something like coordinates or rgb colors for example for everything else you can use dictionary or utility class like this one class bunch def init self kwds self dict update kwds mystruct bunch field value field value think the definitive discussion is here in the published version of the python cookbook
QA
like structures in python is there way to conveniently define like structure in python am tired of writing stuff like class mystruct def init self field field field self field field self field field self field field
use named tuple which was added to the collections module in the standard library in python it is also possible to use raymond hettinger named tuple recipe if you need to support python it is nice for your basic example but also covers bunch of edge cases you might run into later as well your fragment above would be written as from collections import namedtuple mystruct namedtuple mystruct field field field the newly created type can be used like this mystruct foo bar baz or you can use named arguments mystruct field foo field bar field baz
QA
like structures in python is there way to conveniently define like structure in python am tired of writing stuff like class mystruct def init self field field field self field field self field field self field field
df that is pretty cool did not know that could access the fields in class using dict mark the situations that wish had this are precisely when want tuple but nothing as heavy as dictionary you can access the fields of class using dictionary because the fields of class its methods and all its properties are stored internally using dicts at least in cpython which leads us to your second comment believing that python dicts are heavy is an extremely non pythonistic concept and reading such comments kills my python zen that is not good you see when you declare class you are actually creating pretty complex wrapper around dictionary so if anything you are adding more overhead than by using simple dictionary an overhead which by the way is meaningless in any case if you are working on performance critical applications use or something
QA
like structures in python is there way to conveniently define like structure in python am tired of writing stuff like class mystruct def init self field field field self field field self field field self field field
you can also pass the init parameters to the instance variables by position abstract struct class class struct def init self argv argd if len argd update by dictionary self dict update argd else update by position attrs filter lambda dir self for in range len argv setattr self attrs argv specific class class point dstruct struct pt point dstruct pt print pt print pt point dstruct print pt pt print pt point dstruct print pt pt pt print
QA
how do sort list of strings in python what is the best way of creating an alphabetically sorted list in python
list sort it really is that simple
QA
how do sort list of strings in python what is the best way of creating an alphabetically sorted list in python
basic answer mylist mylist sort this modifies your original list sorts in place to get sorted copy of the list without changing the original use the sorted function for in sorted mylist print however the examples above are bit naive because they do not take locale into account and perform case sensitive sorting you can take advantage of the optional parameter key to specify custom sorting order the alternative using cmp is deprecated solution as it has to be evaluated multiple times key is only computed once per element so to sort according to the current locale taking language specific rules into account cmp to key is helper function from functools sorted mylist key cmp to key locale strcoll and finally if you need you can specify custom locale for sorting import locale locale setlocale locale lc all en us utf vary depending on your lang locale assert sorted you ab you ad you aa key cmp to key locale strcoll you aa you ab you ad last note you will see examples of case insensitive sorting which use the lower method those are incorrect because they work only for the ascii subset of characters those two are wrong for any non english data this is incorrect mylist sort key lambda lower alternative notation bit faster but still wrong mylist sort key str lower
QA
using an xml catalog with python lxml is there way when parse an xml document using lxml to validate that document against its dtd using an external catalog file need to be able to work the fixed attributes defined in document dtd
it seems that lxml does not expose this libxml feature grepping the source only turns up some defines for the error handling dev grep ir include px id catalog lxml src sed are lxml src lxml dtd pxi catalog lxml src lxml xmlerror pxd xml from catalog the catalog module lxml src lxml xmlerror pxd xml war catalog pi lxml src lxml xmlerror pxd xml catalog missing attr lxml src lxml xmlerror pxd xml catalog entry broken lxml src lxml xmlerror pxd xml catalog prefer value lxml src lxml xmlerror pxd xml catalog not catalog lxml src lxml xmlerror pxd xml catalog recursion lxml src lxml xmlerror pxi catalog lxml src lxml xmlerror pxi war catalog pi lxml src lxml xmlerror pxi catalog missing attr lxml src lxml xmlerror pxi catalog entry broken lxml src lxml xmlerror pxi catalog prefer value lxml src lxml xmlerror pxi catalog not catalog lxml src lxml xmlerror pxi catalog recursion from the catalog implementation in libxml page it seems possible that the transparent handling through installation in etc xml catalog may still work in lxml but if you need more than that you can always abandon lxml and use the default python bindings which do expose the catalog functions
QA
how do sort list of strings in python what is the best way of creating an alphabetically sorted list in python
but how does this handle language specific sorting rules does it take locale into account no list sort is generic sorting function if you want to sort according to the unicode rules you will have to define custom sort key function you can try using the pyuca module but do not know how complete it is
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing python with modules do you think it is proper for production use in the development of stand alone complex applications think for example to word processor or graphic tool what ide would you suggest the idle provided with python is not enough even for small projects in my opinion
one way to judge what python is used for is to look at what products use python at the moment this wikipedia page has long list including various web frameworks content management systems version control systems desktop apps and ides as it says here some of the largest projects that use python are the zope application server youtube and the original bittorrent client large organizations that make use of python include google yahoo cern and nasa ita uses python for some of its components so in short yes it is proper for production use in the development of stand alone complex applications so are many other languages with various pros and cons which is the best language for your particular use case is too subjective to answer so will not try but often the answer will be the one your developers know best
QA
the system cannot find the file specified when invoking subprocess popen in python am trying to use svnmerge py to merge some files under the hood it uses python and when use it get an error the system cannot find the file specified colleagues at work are running the same version of svnmerge py and of python specifically without an issue found this link which describes my problem trying what was outlined there confirmed python could find svn it is in my path python python feb msc bit intel on win type help copyright credits or license for more information import os os popen svn version close readline svn version looking at the svnmerge py code though noticed for python versions and higher it was following different execution path rather than invoking os popen it uses subprocess popen trying that reproduces the error python python feb msc bit intel on win type help copyright credits or license for more information import subprocess subprocess popen svn version stdout subprocess pipe close fds false stderr subprocess pipe traceback most recent call last file line in file python lib subprocess py line in init errread errwrite file python lib subprocess py line in execute child startupinfo windowserror error the system cannot find the file specified for now have commented out the and higher specific code but would like to find proper solution if it is not obvious am complete python newbie but google has not helped any pointers
it is bug see the documentation of subprocess popen there either needs to be she will true option or the first argument needs to be sequence svn version as it is now popen is looking for an executable named literally svn version which it does not find do not know why it would work for your colleagues though if they are running the same os and version of python fwiw it gives me the same error message on mac and either of the two ways gave fixes it
QA
how do sort list of strings in python what is the best way of creating an alphabetically sorted list in python
it is also worth noting the sorted function for in sorted list print this returns new sorted version of list without changing the original list
QA
how do add data to an existing model in django currently am writing up bit of product based cms as my first project here is my question how can add additional data products to my product model have added admin products add to my urls py but do not really know where to go from there how would build both my view and my template please keep in mind that do not really know all that much python and am very new to django how can do this all without using this existing django admin interface
this topic is covered in django tutorials
QA
best way to extract data from filemaker pro database in script my job would be easier or at least less tedious if could come up with an automated way preferably in python script to extract useful information from filemaker pro database am working on linux machine and the filemaker database is on the same lan running on an os machine can log into the webby interface from my machine am quite handy with sql and if somebody could point me to some filemaker plug in that could give me sql access to the data within filemaker would be pleased as punch everything have found only goes the other way having filemaker get data from sql sources not useful it is not my first choice but would use perl instead of python if there was perl solution at hand note xml xslt services as suggested by some folks are only available on fm server not fm pro otherwise that would probably be the best solution odbc is turning out to be extremely difficult to even get working there is absolutely zero feedback from fm when you set it up so you have to dig through var log system log and parse obscure error messages conclusion got it working by running python script locally on the machine that queries the fm database through the odbc connections the script is actually tcpserver that accepts socket connections from other systems on the lan runs the queries and returns the data through the socket connection had to do this to bypass the fact that fm pro only accepts odbc connections locally fm server is required for external connections
you will need the filemaker pro installation cd to get the drivers this document details the process for fmp it is similar for versions and as well versions and earlier are completely different and would not bother trying xdbc support in those previous versions is minimal at best fmp supports sql standard syntax mostly note that rather than querying tables directly you query using the table occurrence name which serves as table alias of sorts if the data tables are stored in multiple files it is possible to create single fmp file with table occurrences aliases pointing to those data tables there is an undocumented feature where such file must have table defined in it as well and that table related to any other table on the relationships graph does not matter which one for odbc access to work otherwise your queries will always return no results the pdf document details all of the limitations of using the xdbc interface fmp provides performance of simple queries is reasonably fast ymmv have found the performance of queries specifying the like operator to be less than stellar fmp also has an xml xslt interface that you can use to query fmp data over an http connection it also provides php class for accessing and using fmp data in web applications
QA
what does double star and star do for python parameters in the following method definitions what does the and do for param def foo param param def bar param param
from the python documentation if there are more positional arguments than there are formal parameter slots typeerror exception is raised unless formal parameter using the syntax identifier is present in this case that formal parameter receives tuple containing the excess positional arguments or an empty tuple if there were no excess positional arguments if any keyword argument does not correspond to formal parameter name typeerror exception is raised unless formal parameter using the syntax identifier is present in this case that formal parameter receives dictionary containing the excess keyword arguments using the keywords as keys and the argument values as corresponding values or new empty dictionary if there were no excess keyword arguments
QA
what does double star and star do for python parameters in the following method definitions what does the and do for param def foo param param def bar param param
the args and kwargs is common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the python documentation the args will give you all function parameters as tuple in def foo args for in args print in foo in foo the kwargs will give you all keyword arguments except for those corresponding to formal parameter as dictionary in def bar kwargs for in kwargs print kwargs in bar name one age age name one both idioms can be mixed with normal arguments to allow set of fixed and some variable arguments def foo kind args kwargs pass another usage of the idiom is to unpack argument lists when calling function in def foo bar lee print bar lee in in foo in python it is possible to use on the left side of an assignment extended iterable unpacking first rest first last also python adds new semantic refer pep def func arg arg arg default kwarg abc kwarg xyz pass such function accepts only positional arguments and everything after can only be passed as keyword argument not positional one in python similar was true for all parameters after args
QA
what does double star and star do for python parameters in the following method definitions what does the and do for param def foo param param def bar param param
the single means that there can be any number of extra positional arguments foo can be invoked like foo in the body of foo param is sequence containing the double means there can be any number of extra named parameters bar can be invoked like bar in the body of bar param is dictionary containing with the following code def foo param param print param print param def bar param param print param print param foo bar the output is
QA
what does double star and star do for python parameters in the following method definitions what does the and do for param def foo param param def bar param param
it is also worth noting that you can use and when calling functions as well this is shortcut that allows you to pass multiple arguments to function directly using either list tuple or dictionary for example if you have the following function def foo print str print str print str you can do things like mylist foo mylist mydict foo mydict mytuple foo mytuple
QA
how do add data to an existing model in django currently am writing up bit of product based cms as my first project here is my question how can add additional data products to my product model have added admin products add to my urls py but do not really know where to go from there how would build both my view and my template please keep in mind that do not really know all that much python and am very new to django how can do this all without using this existing django admin interface
you will want to wire your url to the django create object generic view and pass it either model the model you want to create or form class customized modelform class there are number of other arguments you can also pass to override default behaviors sample urlconf for the simplest case from django conf urls defaults import from django views generic create update import create object from my products app models import product urlpatterns patterns url admin products add create object model product your template will get the context variable form which you just need to wrap in form tag and add submit button the simplest working template by default should go in my products app product form html form action method post form input type submit name submit value add form note that your product model must have get absolute url method or else you must pass in the post save redirect parameter to the view otherwise it will not know where to redirect to after save
QA
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
before pep python did not have an equivalent but you could implement your own myself like keeping it simple have seen some horribly complex examples on the net something like this class animal dog cat animal dog in python pep you can make enum the base class this gets you little bit of extra functionality described in the pep for example enum values are distinct from integers class animal enum dog cat print animal dog animal dog if you do not want to type the values use the following shortcut class animal enum dog cat range
QA
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
hmmm suppose the closest thing to an enum would be dictionary defined either like this months january february or months dict january february then you can use the symbolic name for the constants like this mymonth months january there are other options like list of tuples or tuple of tuples but the dictionary is the only one that provides you with symbolic constant string way to access the value edit like alexandru answer too
QA
resources for lexing tokenising and parsing in python can people point me to resources on lexing parsing and tokenising with python am doing little hacking on an open source project hotwire and wanted to do few changes to the code that lexes parses and tokenises the commands entered into it as it is real working code it is fairly complex and bit hard to work out have not worked on code to lex parse tokenise before so was thinking one approach would be to work through tutorial or two on this aspect would hope to learn enough to navigate around the code actually want to alter is there anything suitable out there ideally it could be done in an afternoon without having to buy and read the dragon book first edit oct none of the below answers quite give what want with them could generate parsers from scratch but want to learn how to write my own basic parser from scratch not using lex and yacc or similar tools having done that can then understand the existing code better so could someone point me to tutorial where can build basic parser from scratch using just python
have look at the standard module shlex and modify one copy of it to match the syntax you use for your she will it is good starting point if you want all the power of complete solution for lexing parsing antlr can generate python too
QA
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
python does not have built in equivalent to enum and other answers have ideas for implementing your own you may also be interested in the over the top version in the python cookbook however in situations where an enum would be called for in usually end up just using simple strings because of the way objects attributes are implemented python is optimized to work very fast with short strings anyway so there would not really be any performance benefit to using integers to guard against typos invalid values you can insert checks in selected places animals cat dog python def take for walk animal assert animal in animals one disadvantage compared to using class is that you lose the benefit of autocomplete
QA
setup django with wsgi and apache have been sold on mod wsgi and apache rather than mod python have all the parts installed django apache mod wsgi but have run into problem deploying am on osx with apache and django mod wsgi my application is called tred here are the relevant files httpd vhosts included in httpd conf namevirtualhost tred servername tred alias admin media usr lib python site packages django contrib admin media order allow deny allow from all alias media users dmg sites tred media order allow deny allow from all alias users dmg sites tred order allow deny allow from all wsgiscriptalias users dmg sites tred mod wsgi handler wsgi wsgidaemonprocess tred user dmg group staff processes threads wsgiprocessgroup tred mod wsgi handle wsgi import sys import os sys path append os path dirname os path abspath file os environ django settings module tred settings import django core handlers wsgi application django core handlers wsgi wsgihandler when go to http tred get directory listing rather than the rendered website think have followed the tutorials correctly but it is obviously not right what can do to make this work
what happens if you remove the alias directive
QA
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
if you need the numeric values here is the quickest way dog cat rabbit range
QA
how to make ruby or python web sites to use multiple cores even though python and ruby have one kernel thread per interpreter thread they have global interpreter lock gil that is used to protect potentially shared data structures so this inhibits multi processor execution even though the portions in those languajes that are written in or can be free threaded that is not possible with pure interpreted code unless you use multiple processes what is the best way to achieve this using fastcgi creating cluster or farm of virtualized servers using their java equivalents jruby and jython
use an interface that runs each response in separate interpreter such as mod wsgi for python this let us multi threading be used without encountering the gil edit apparently mod wsgi no longer supports multiple interpreters per process because idiots could not figure out how to properly implement extension modules it still supports running requests in separate processes fastcgi style though so that is apparently the current accepted solution
QA
how to make ruby or python web sites to use multiple cores even though python and ruby have one kernel thread per interpreter thread they have global interpreter lock gil that is used to protect potentially shared data structures so this inhibits multi processor execution even though the portions in those languajes that are written in or can be free threaded that is not possible with pure interpreted code unless you use multiple processes what is the best way to achieve this using fastcgi creating cluster or farm of virtualized servers using their java equivalents jruby and jython
am not totally sure which problem you want so solve but if you deploy your python django application via an apache prefork mpm using mod python apache will start several worker processes for handling different requests if one request needs so much resources that you want to use multiple cores have look at pyprocessing but do not think that would be wise
QA
django templates and variable attributes am using google app engine and django templates have table that want to display the objects look something like object result items item item users name username item item the django template is table tr align center th user th for item in result items th item th endfor tr for user in result users tr align center td user name td for item in result items td user item td endfor tr endfor table now the django documention states that when it sees in variables it tries several things to get the data one of which is dictionary lookup which is exactly what want but does not seem to happen
should not this user item be this item there is no user object in the context within that loop
QA
how to make ruby or python web sites to use multiple cores even though python and ruby have one kernel thread per interpreter thread they have global interpreter lock gil that is used to protect potentially shared data structures so this inhibits multi processor execution even though the portions in those languajes that are written in or can be free threaded that is not possible with pure interpreted code unless you use multiple processes what is the best way to achieve this using fastcgi creating cluster or farm of virtualized servers using their java equivalents jruby and jython
the standard way to do this with rails is to run pack of mongrel instances ie copies of the rails application and then use apache or nginx or some other piece of software to sit in front of them and act as load balancer this is probably how it is done with other ruby frameworks such as merb etc but have not used those personally the os will take care of running each mongrel on it is own cpu if you install mod rails aka phusion passenger it will start and stop multiple copies of the rails process for you as well so it will end up spreading the load across multiple cpus cores in similar way
QA
setup django with wsgi and apache have been sold on mod wsgi and apache rather than mod python have all the parts installed django apache mod wsgi but have run into problem deploying am on osx with apache and django mod wsgi my application is called tred here are the relevant files httpd vhosts included in httpd conf namevirtualhost tred servername tred alias admin media usr lib python site packages django contrib admin media order allow deny allow from all alias media users dmg sites tred media order allow deny allow from all alias users dmg sites tred order allow deny allow from all wsgiscriptalias users dmg sites tred mod wsgi handler wsgi wsgidaemonprocess tred user dmg group staff processes threads wsgiprocessgroup tred mod wsgi handle wsgi import sys import os sys path append os path dirname os path abspath file os environ django settings module tred settings import django core handlers wsgi application django core handlers wsgi wsgihandler when go to http tred get directory listing rather than the rendered website think have followed the tutorials correctly but it is obviously not right what can do to make this work
it works have no idea why but it does for future reference it works because apache processes alias directives in order and uses the first match it was always hitting alias which will match anything before wsgiscriptalias from the mod alias documentation first all redirects are processed before aliases are processed and therefore request that matches redirect or redirectmatch will never have aliases applied second the aliases and redirects are processed in the order they appear in the configuration files with the first match taking precedence
QA
resources for lexing tokenising and parsing in python can people point me to resources on lexing parsing and tokenising with python am doing little hacking on an open source project hotwire and wanted to do few changes to the code that lexes parses and tokenises the commands entered into it as it is real working code it is fairly complex and bit hard to work out have not worked on code to lex parse tokenise before so was thinking one approach would be to work through tutorial or two on this aspect would hope to learn enough to navigate around the code actually want to alter is there anything suitable out there ideally it could be done in an afternoon without having to buy and read the dragon book first edit oct none of the below answers quite give what want with them could generate parsers from scratch but want to learn how to write my own basic parser from scratch not using lex and yacc or similar tools having done that can then understand the existing code better so could someone point me to tutorial where can build basic parser from scratch using just python
suggest http www canonware com parsing since it is pure python and you do not need to learn grammar but it is not widely used and has comparatively little documentation the heavyweight is antlr and pyparsing antlr can generate java and parsers too and ast walkers but you will have to learn what amounts to new language
QA
how do use python itertools groupby have not been able to find an understandable explanation of how to actually use python itertools groupby function what am trying to do is this take list in this case the children of an objectified lxml element divide it into groups based on some criteria then later iterate over each of these groups separately have reviewed the documentation and the examples but have had trouble trying to apply them beyond simple list of numbers so how do use of itertools groupby is there another technique should be using pointers to good prerequisite reading would also be appreciated
neato trick with groupby is to run length encoding in one line len list cgen for cgen in groupby some string will give you list of tuples where the first element is the char and the nd is the number of repetitions
QA
how can simply inherit methods from an existing instance below have very simple example of what am trying to do want to be able to use htmldecorator with any other class ignore the fact it is called decorator it is just name import cgi class classx object pass with own repr class classy object pass with own repr inst classx inst classy inst for in range inst true class htmldecorator object def html self an enhanced version of repr return cgi escape self repr join print htmldecorator inst html print htmldecorator inst html wrapped htmldecorator inst inst wrapped print wrapped html print htmldecorator inst html output traceback most recent call last file html py line in print htmldecorator inst html typeerror default new takes no parameters is what am trying to do possible if so what am doing wrong
is what am trying to do possible if so what am doing wrong it is certainly possible what is wrong is that htmldecorator init does not accept parameters here is simple example def decorator func def new func return new func func return new func decorator def return def return print new func print decorator new func
QA
filter out html tags and resolve entities in python because regular expressions scare me am trying to find way to remove all html tags and resolve html entities from string in python
how about parsing the html data and extracting the data with the help of the parser would try something like the author described in chapter in the dive into python book
QA
filter out html tags and resolve entities in python because regular expressions scare me am trying to find way to remove all html tags and resolve html entities from string in python
while agree with lucas that regular expressions are not all that scary still think that you should go with specialized html parser this is because the html standard is hairy enough especially if you want to parse arbitrarily html pages taken off the internet that you would need to write lot of code to handle the corner cases it seems that python includes one out of the box you should also check out the python bindings for tidylib which can clean up broken html making the success rate of any html parsing much higher
QA
filter out html tags and resolve entities in python because regular expressions scare me am trying to find way to remove all html tags and resolve html entities from string in python
you might need something more complicated than regular expression web pages often have angle brackets that are not part of tag like this div div stripping the tags with regex will return the string and treat div as single tag and strip it out suggest looking for already written code that does this for you did search and found this http zesty ca python scrape html it also can resolve html entities
QA
filter out html tags and resolve entities in python because regular expressions scare me am trying to find way to remove all html tags and resolve html entities from string in python
use beautifulsoup it is perfect for this where you have incoming markup of dubious virtue and need to get something reasonable out of it just pass in the original text extract all the string tags and join them
QA
filter out html tags and resolve entities in python because regular expressions scare me am trying to find way to remove all html tags and resolve html entities from string in python
use lxml which is the best xml html library for python import lxml html lxml html fromstring text content and if you just want to sanitize the html look at the lxml html clean module
QA
how can simply inherit methods from an existing instance below have very simple example of what am trying to do want to be able to use htmldecorator with any other class ignore the fact it is called decorator it is just name import cgi class classx object pass with own repr class classy object pass with own repr inst classx inst classy inst for in range inst true class htmldecorator object def html self an enhanced version of repr return cgi escape self repr join print htmldecorator inst html print htmldecorator inst html wrapped htmldecorator inst inst wrapped print wrapped html print htmldecorator inst html output traceback most recent call last file html py line in print htmldecorator inst html typeerror default new takes no parameters is what am trying to do possible if so what am doing wrong
john sorry might have misled you with the name bad choice am not really looking for decorator function or anything to do with decorators at all what am after is for the html self def to use classx or classy repr want this to work without modifying classx or classy
QA
how can simply inherit methods from an existing instance below have very simple example of what am trying to do want to be able to use htmldecorator with any other class ignore the fact it is called decorator it is just name import cgi class classx object pass with own repr class classy object pass with own repr inst classx inst classy inst for in range inst true class htmldecorator object def html self an enhanced version of repr return cgi escape self repr join print htmldecorator inst html print htmldecorator inst html wrapped htmldecorator inst inst wrapped print wrapped html print htmldecorator inst html output traceback most recent call last file html py line in print htmldecorator inst html typeerror default new takes no parameters is what am trying to do possible if so what am doing wrong
ah in that case perhaps code like this will be useful it does not really have anything to do with decorators but demonstrates how to pass arguments to class initialization function and to retrieve those arguments for later import cgi class classx object def repr self return class class htmldecorator object def init self wrapped self wrapped wrapped def html self sep cgi escape repr self wrapped return sep join inst classx inst true print htmldecorator inst html print htmldecorator inst html
QA
how can simply inherit methods from an existing instance below have very simple example of what am trying to do want to be able to use htmldecorator with any other class ignore the fact it is called decorator it is just name import cgi class classx object pass with own repr class classy object pass with own repr inst classx inst classy inst for in range inst true class htmldecorator object def html self an enhanced version of repr return cgi escape self repr join print htmldecorator inst html print htmldecorator inst html wrapped htmldecorator inst inst wrapped print wrapped html print htmldecorator inst html output traceback most recent call last file html py line in print htmldecorator inst html typeerror default new takes no parameters is what am trying to do possible if so what am doing wrong
john very close but then lose everything from classx below is something collegue gave me that does do the trick but it is hideous there has to be better way import cgi from math import sqrt class classx object def repr self return best guess class classy object pass with own repr inst classx inst classy inst for in range inst true avoid class init dict weakref class htmldecorator object def init self master self master master for attr in dir self master if not attr startswith or attr not in avoid split and attr not in attr self setattr attr self master getattribute attr def html self an enhanced version of repr return cgi escape self repr join def length self return sqrt sum self iter print htmldecorator inst html print htmldecorator inst html wrapped htmldecorator inst print wrapped length inst wrapped wrapped setitem wrapped getitem print wrapped html print htmldecorator inst html output best guess main classy object at df true
QA
what is the easiest way to read foxpro dbf file from python have got bunch of foxpro vfp dbf files on my ubuntu system is there library to open these in python only need to read them and would preferably have access to the memo fields too update thanks cnu used yusdi santoso dbf py and it works nicely one gotcha the memo file name extension must be lower case fpt not fpt which was how the filename came over from windows
you can try this recipe on active state there is also dbfreader module which you can try for support for memo fields
QA
how can simply inherit methods from an existing instance below have very simple example of what am trying to do want to be able to use htmldecorator with any other class ignore the fact it is called decorator it is just name import cgi class classx object pass with own repr class classy object pass with own repr inst classx inst classy inst for in range inst true class htmldecorator object def html self an enhanced version of repr return cgi escape self repr join print htmldecorator inst html print htmldecorator inst html wrapped htmldecorator inst inst wrapped print wrapped html print htmldecorator inst html output traceback most recent call last file html py line in print htmldecorator inst html typeerror default new takes no parameters is what am trying to do possible if so what am doing wrong
very close but then lose everything from classx below is something collegue gave me that does do the trick but it is hideous there has to be better way looks like you are trying to set up some sort of proxy object scheme that is doable and there are better solutions than your colleague but first consider whether it would be easier to just patch in some extra methods this will not work for built in classes like bool but it will for your user defined classes def htmldecorator obj def html sep cgi escape repr obj return sep join obj html html return obj and here is the proxy version class htmldecorator object def init self wrapped self wrapped wrapped def html self sep cgi escape repr self wrapped return sep join def getattr self name return getattr self wrapped name def setattr self name value if not name startswith htmldecorator setattr self wrapped name value return super htmldecorator self setattr name value def delattr self name delattr self wraped name
QA
filter out html tags and resolve entities in python because regular expressions scare me am trying to find way to remove all html tags and resolve html entities from string in python
regular expressions are not scary but writing your own regexes to strip html is sure path to madness and it will not work either follow the path of wisdom and use one of the many good html parsing libraries lucas example is also broken because sub is not method of python string you would have to import re then call re sub pattern repl string but that is neither here nor there as the correct answer to your question does not involve writing any regexes
QA
how can simply inherit methods from an existing instance below have very simple example of what am trying to do want to be able to use htmldecorator with any other class ignore the fact it is called decorator it is just name import cgi class classx object pass with own repr class classy object pass with own repr inst classx inst classy inst for in range inst true class htmldecorator object def html self an enhanced version of repr return cgi escape self repr join print htmldecorator inst html print htmldecorator inst html wrapped htmldecorator inst inst wrapped print wrapped html print htmldecorator inst html output traceback most recent call last file html py line in print htmldecorator inst html typeerror default new takes no parameters is what am trying to do possible if so what am doing wrong
both of john solutions would work another option that allows htmldecorator to remain very simple and clean is to monkey patch it in as base class this also works only for user defined classes not builtin types import cgi class classx object pass with own repr class classy object pass with own repr inst classx inst classy class htmldecorator def html self an enhanced version of repr return cgi escape self repr join classx bases htmldecorator classy bases htmldecorator print inst html print inst html be warned though monkey patching like this comes with high price in readability and maintainability of your code when you go back to this code year later it can become very difficult to figure out how your classx got that html method especially if classx is defined in some other library
QA
what is the easiest way to read foxpro dbf file from python have got bunch of foxpro vfp dbf files on my ubuntu system is there library to open these in python only need to read them and would preferably have access to the memo fields too update thanks cnu used yusdi santoso dbf py and it works nicely one gotcha the memo file name extension must be lower case fpt not fpt which was how the filename came over from windows
prefer dbfpy it supports both reading and writing of dbf files and can cope with most variations of the format it is the only implementation have found that could both read and write the legacy dbf files of some older systems have worked with
QA
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
the typesafe enum pattern which was used in java pre jdk has number of advantages much like in alexandru answer you create class and class level fields are the enum values however the enum values are instances of the class rather than small integers this has the advantage that your enum values do not inadvertently compare equal to small integers you can control how they are printed add arbitrary methods if that is useful and make assertions using isinstance class animal def init self name self name name def str self return self name def repr self return animal self animal dog animal dog animal cat animal cat animal dog animal dog false recent thread on python dev pointed out there are couple of enum libraries in the wild including flufl enum lazr enum and the imaginatively named enum
QA
what are class methods in python for am teaching myself python and my most recent lesson was that python is not java and so have just spent while turning all my class methods into functions now realise that do not need to use class methods for what would done with static methods in java but now am not sure when would use them all the advice can find about python class methods is along the lines of newbies like me should steer clear of them and the standard documentation is at its most opaque when discussing them does anyone have good example of using class method in python or at least can someone tell me when class methods can be sensibly used
alternative constructors are the classic example
QA
what are class methods in python for am teaching myself python and my most recent lesson was that python is not java and so have just spent while turning all my class methods into functions now realise that do not need to use class methods for what would done with static methods in java but now am not sure when would use them all the advice can find about python class methods is along the lines of newbies like me should steer clear of them and the standard documentation is at its most opaque when discussing them does anyone have good example of using class method in python or at least can someone tell me when class methods can be sensibly used
class methods are for when you need to have methods that are not specific to any particular instance but still involve the class in some way the most interesting thing about them is that they can be overridden by subclasses something that is simply not possible in java static methods or python module level functions if you have class myclass and module level function that operates on myclass factory dependency injection stub etc make it classmethod then it will be available to subclasses
QA
what are class methods in python for am teaching myself python and my most recent lesson was that python is not java and so have just spent while turning all my class methods into functions now realise that do not need to use class methods for what would done with static methods in java but now am not sure when would use them all the advice can find about python class methods is along the lines of newbies like me should steer clear of them and the standard documentation is at its most opaque when discussing them does anyone have good example of using class method in python or at least can someone tell me when class methods can be sensibly used
honestly have never found use for staticmethod or classmethod have yet to see an operation that cannot be done using global function or an instance method it would be different if python used private and protected members more like java does in java need static method to be able to access an instance private members to do stuff in python that is rarely necessary usually see people using staticmethods and classmethods when all they really need to do is use python module level namespaces better
QA
what are class methods in python for am teaching myself python and my most recent lesson was that python is not java and so have just spent while turning all my class methods into functions now realise that do not need to use class methods for what would done with static methods in java but now am not sure when would use them all the advice can find about python class methods is along the lines of newbies like me should steer clear of them and the standard documentation is at its most opaque when discussing them does anyone have good example of using class method in python or at least can someone tell me when class methods can be sensibly used
factory methods alternative constructors are indeed classic example of class methods basically class methods are suitable anytime you would like to have method which naturally fits into the namespace of the class but is not associated with particular instance of the class as an example in the excellent unipath module current directory path cwd return the actual current directory path tmp my temp dir this is class method chdir make self the current directory as the current directory is process wide the cwd method has no particular instance with which it should be associated however changing the cwd to the directory of given path instance should indeed be an instance method hmmm as path cwd does indeed return path instance guess it could be considered to be factory method
QA
retrieving an oracle timestamp using python win odbc module given an oracle table created using the following create table log whenadded timestamp with time zone using the python odbc module from its win extensions from the win all package tried the following import dbi odbc connection odbc odbc driver oracle in orahome dbq server uid user pwd passwd cursor connection cursor cursor execute select whenadded from log results cursor fetchall when run this get the following traceback most recent call last results cursor fetchall dbi operation error oracle odbc ora ora inconsistent datatypes expected got in fetch the other data types have tried varchar blob do not because this problem is there way of retrieving timestamps
my solution to this that hope can be bettered is to use oracle to explicitly convert the timestamp into string cursor execute select to char whenadded yyyy mm dd hh mi ssam from log this works but is not portable would like to use the same python script against sql server database so an oracle specific solution such as to char will not work
QA
what is the best way to return multiple values from function in python have function where need to do something to string need the function to return boolean indicating whether or not the operation succeeded and also need to return the modified string in would use an out parameter for the string but there is no equivalent in python am still very new to python and the only thing can think of is to return tuple with the boolean and modified string related question is it pythonic for function to return multiple values
returning tuple is the usual way to do this in python
QA
what is the best way to return multiple values from function in python have function where need to do something to string need the function to return boolean indicating whether or not the operation succeeded and also need to return the modified string in would use an out parameter for the string but there is no equivalent in python am still very new to python and the only thing can think of is to return tuple with the boolean and modified string related question is it pythonic for function to return multiple values
return tuple def do stuff return true modified string success modified string something
QA
what is the best way to return multiple values from function in python have function where need to do something to string need the function to return boolean indicating whether or not the operation succeeded and also need to return the modified string in would use an out parameter for the string but there is no equivalent in python am still very new to python and the only thing can think of is to return tuple with the boolean and modified string related question is it pythonic for function to return multiple values
def in str out str in str upper return true out str creates tuple automatically succeeded automatic tuple unpacking
QA
what is the best way to return multiple values from function in python have function where need to do something to string need the function to return boolean indicating whether or not the operation succeeded and also need to return the modified string in would use an out parameter for the string but there is no equivalent in python am still very new to python and the only thing can think of is to return tuple with the boolean and modified string related question is it pythonic for function to return multiple values
why not throw an exception if the operation was not successful personally tend to be of the opinion that if you need to return more than one value from function you should reconsider if you are doing things the right way or use an object but more directly to the point if you throw an exception you are forcing them to deal with the problem if you try to return value that indicates failure it is very well possible somebody could not check the value and end up with some potentially hard to debug errors
QA
filter out html tags and resolve entities in python because regular expressions scare me am trying to find way to remove all html tags and resolve html entities from string in python
looking at the amount of sense people are demonstrating in other answers here would say that using regex probably is not the best idea for your situation go for something tried and tested and treat my previous answer as demonstration that regexes need not be that scary
QA
retrieving an oracle timestamp using python win odbc module given an oracle table created using the following create table log whenadded timestamp with time zone using the python odbc module from its win extensions from the win all package tried the following import dbi odbc connection odbc odbc driver oracle in orahome dbq server uid user pwd passwd cursor connection cursor cursor execute select whenadded from log results cursor fetchall when run this get the following traceback most recent call last results cursor fetchall dbi operation error oracle odbc ora ora inconsistent datatypes expected got in fetch the other data types have tried varchar blob do not because this problem is there way of retrieving timestamps
believe this is bug in the oracle odbc driver basically the oracle odbc driver does not support the timestamp with local time zone data types only the timestamp data type as you have discovered one workaround is in fact to use the to char method in your example you are not actually reading the time zone information if you have control of the table you could convert it to straight timestamp column if you do not have control over the table another solution may be to create view that converts from timestamp with time zone to timestamp via string sorry do not know if there is way to convert directly from timestamp with time zone to timestamp
QA
what is the best way to return multiple values from function in python have function where need to do something to string need the function to return boolean indicating whether or not the operation succeeded and also need to return the modified string in would use an out parameter for the string but there is no equivalent in python am still very new to python and the only thing can think of is to return tuple with the boolean and modified string related question is it pythonic for function to return multiple values
throwing an exception for failure is one good way to proceed and if you are returning lot of different values you can return tuple for the specific case you are citing often take an intermediate approach return the modified string on success and return none on failure am enough of an unreconstructed programmer to want to return null pointer to char on failure if were writing routine to be used as part of larger library and consumed by other developers would throw an exception on failure when am eating my own dogfood will probably return different types and test on return
QA
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
davidg recommends using dicts would go one step further and use sets months set january february december now you can test whether value matches one of the values in the set like this if in months like df though usually just use string constants in place of enums
QA
using django time date widgets in custom form how can use the nifty javascript date and time widgets that the default admin uses with my custom view have looked through the django forms documentation and it briefly mentions django contrib admin widgets but do not know how to use it here is my template that want it applied on form action method post table for in form tr td name td td td tr endfor table input type submit name submit value add product form also think it should be noted that have not really written view up myself for this form am using generic view here is the entry from the url py admin products add create object model product post save redirect and am relevantly new to the whole django mvc mtv thing so please go easy
the growing complexity of this answer over time and the many hacks required probably ought to caution you against doing this at all it is relying on undocumented internal implementation details of the admin is likely to break again in future versions of django and is no easier to implement than just finding another js calendar widget and using that that said here is what you have to do if you are determined to make this work define your own modelform subclass for your model best to put it in forms py in your app and tell it to use the admindatewidget admintimewidget adminsplitdatetime replace mydate etc with the proper field names from your model from django import forms from my app models import product from django contrib admin import widgets class productform forms modelform class meta model product def init self args kwargs super productform self init args kwargs self fields mydate widget widgets admindatewidget self fields mytime widget widgets admintimewidget self fields mydatetime widget widgets adminsplitdatetime change your urlconf to pass form class productform instead of model product to the generic create object view that will mean from my app forms import productform instead of from my app models import product of course in the head of your template include form media to output the links to the javascript files and the hacky part the admin date time widgets presume that the js stuff has been loaded and also require core js but do not provide either one automatically so in your template above form media you will need script type text javascript src my admin jsi script script type text javascript src media admin js core js script you may also wish to use the following admin css thanks alex for mentioning this link rel stylesheet type text css href media admin css forms css link rel stylesheet type text css href media admin css base css link rel stylesheet type text css href media admin css global css link rel stylesheet type text css href media admin css widgets css this implies that django admin media admin media prefix is at media admin you can change that for your setup ideally you would use context processor to pass this values to your template instead of hardcoding it but that is beyond the scope of this question this also requires that the url my admin jsi be manually wired up to the django views javascript catalog view or null javascript catalog if you are not using you have to do this yourself instead of going through the admin application so it is accessible regardless of whether you are logged into the admin thanks jeremy for pointing this out sample code for your urlconf my admin jsi django views javascript catalog lastly if you are using django or later you need some additional code in your template to help the widgets find their media load adminmedia at the top of the template in the head section of the template script type text javascript window admin media prefix filter escapejs admin media prefix endfilter script thanks lupefiasco for this addition
QA
how to merge two python dictionaries in single expression have two python dictionaries and want to write single expression that returns these two dictionaries merged the update method would be what need if it returned its result instead of modifying dict in place update print none how can get that final merged dict in not to be extra clear the last one wins conflict handling of dict update is what am looking for as well
dict items items print for items with keys in both dictionaries you can control which one ends up in the output by putting that one last
QA
how to merge two python dictionaries in single expression have two python dictionaries and want to write single expression that returns these two dictionaries merged the update method would be what need if it returned its result instead of modifying dict in place update print none how can get that final merged dict in not to be extra clear the last one wins conflict handling of dict update is what am looking for as well
in your case what you can do is dict items items this will as you want it put the final dict in and make the value for key be properly overridden by the second dict value dict items items if you use python it is only little more complicated to create dict list items list items
QA
ruby is equivalent is there ruby equivalent for python is it tests whether two objects are identical have the same memory location
you could also use id this gives you the objects internal id number which is always unique to check if to objects are the same try id id this is how ruby standard library does it as far as can tell see group by and others
QA
search and replace line in file in python want to loop over the contents of text file and do search and replace on some lines and write the result back to the file could first load the whole file in memory and then write it back but that probably is not the best way to do it what is the best way to do this within the following code open file for line in if line contains foo newline line replace foo bar how to write this newline back to the file
create new file copy lines from the old to the new and do the replacing before you write the lines to the new file
QA
search and replace line in file in python want to loop over the contents of text file and do search and replace on some lines and write the result back to the file could first load the whole file in memory and then write it back but that probably is not the best way to do it what is the best way to do this within the following code open file for line in if line contains foo newline line replace foo bar how to write this newline back to the file
guess something like this should do it it basically writes the content to new file and replaces the old file with the new file from tempfile import mkstemp from shutil import move from os import remove close def replace file path pattern subst create temp file fh abs path mkstemp with open abs path as new file with open file path as old file for line in old file new file write line replace pattern subst close fh remove original file remove file path move new file move abs path file path
QA
search and replace line in file in python want to loop over the contents of text file and do search and replace on some lines and write the result back to the file could first load the whole file in memory and then write it back but that probably is not the best way to do it what is the best way to do this within the following code open file for line in if line contains foo newline line replace foo bar how to write this newline back to the file
as lassevk suggests write out the new file as you go here is some example code fin open txt fout open txt wt for line in fin fout write line replace foo bar fin close fout close
QA
finding file in python module distribution have written python package that includes bsddb database of pre computed values for one of the more time consuming computations for simplicity my setup script installs the database file in the same directory as the code which accesses the database on unix something like usr lib python site packages mypackage how do store the final location of the database file so my code can access it right now am using hack based on the file variable in the module which accesses the database dbname os path join os path dirname file database dat it works but it seems hackish is there better way to do this would like to have the setup script just grab the final installation location from the distutils module and stuff it into dbconfig py file that gets installed alongside the code that accesses the database
that is probably the way to do it without resorting to something more advanced like using setuptools to install the files where they belong notice there is problem with that approach because on oses with real security framework unixes etc the user running your script might not have the rights to access the db in the system directory where it gets installed
QA
how to merge two python dictionaries in single expression have two python dictionaries and want to write single expression that returns these two dictionaries merged the update method would be what need if it returned its result instead of modifying dict in place update print none how can get that final merged dict in not to be extra clear the last one wins conflict handling of dict update is what am looking for as well
an alternative copy update
QA
finding file in python module distribution have written python package that includes bsddb database of pre computed values for one of the more time consuming computations for simplicity my setup script installs the database file in the same directory as the code which accesses the database on unix something like usr lib python site packages mypackage how do store the final location of the database file so my code can access it right now am using hack based on the file variable in the module which accesses the database dbname os path join os path dirname file database dat it works but it seems hackish is there better way to do this would like to have the setup script just grab the final installation location from the distutils module and stuff it into dbconfig py file that gets installed alongside the code that accesses the database
try using pkg resources which is part of setuptools and available on all of the pythons have access to right now import pkg resources pkg resources resource filename name foo config foo config pkg resources resource filename tempfile foo config usr lib python foo config there is more discussion about using pkg resources to get resources on the eggs page and the pkg resources page also note where possible it is probably advisable to use pkg resources resource stream or pkg resources resource string because if the package is part of an egg resource filename will copy the file to temporary directory
QA
why is my instance variable not in dict if create class as follows class def init self self name inspecting the dict member looks like name if however create class class name dict is empty what is the difference between the two and why does not name show up in dict
class def init self self name creates an attribute on the object instance of type and it can therefore be found in dict class name creates an attribute on the class and the attribute can be found in dict alternatively if you have an instance of type you can see the class level attributes in class dict
QA
what is the best way to do bit field manipulation in python am reading some mpeg transport stream protocol over udp and it has some funky bitfields in it length for example am using the struct library to do the broad unpacking but is there simple way to say grab the next bits rather than have to hand tweak the bit manipulation would like something like the way does bit fields without having to revert to suggestions
it is an often asked question there is an aspn cookbook entry on it that has served me in the past and there is an extensive page of requirements one person would like to see from module doing this
QA
how to merge two python dictionaries in single expression have two python dictionaries and want to write single expression that returns these two dictionaries merged the update method would be what need if it returned its result instead of modifying dict in place update print none how can get that final merged dict in not to be extra clear the last one wins conflict handling of dict update is what am looking for as well
another more concise option dict note this has become popular answer but it is important to point out that if has any non string keys the fact that this works at all is an abuse of cpython implementation detail and it does not work in python or in pypy ironpython or jython also guido is not fan so cannot recommend this technique for forward compatible or cross implementation portable code which really means it should be avoided entirely
QA
using in shared multi platform posix environment write tools that are used in shared workspace since there are multiple os working in this space we generally use python and standardize the version that is installed across machines however if wanted to write some things in was wondering if maybe could have the application wrapped in python script that detected the operating system and fired off the correct version of the application each platform has gcc available and uses the same she will one idea was to have the compiled to the users local bin with timestamp comparison with code so it is not compiled each run but only when code is updated another was to just compile it for each platform and have the wrapper script select the proper executable is there an accepted stable process for this are there any catches are there alternatives assuming the absolute need to use native code clarification multiple os are involved that do not share abi eg os various linuxes bsd etc need to be able to update the code in place in shared folders and have the new code working more or less instantaneously distributing binary or source packages is less than ideal
you know you should look at static linking these days we all have huge hard drives and few extra megabytes for carrying around libc and what not is really not that big deal anymore you could also try running your applications in chroot jails and distributing those
QA
using in shared multi platform posix environment write tools that are used in shared workspace since there are multiple os working in this space we generally use python and standardize the version that is installed across machines however if wanted to write some things in was wondering if maybe could have the application wrapped in python script that detected the operating system and fired off the correct version of the application each platform has gcc available and uses the same she will one idea was to have the compiled to the users local bin with timestamp comparison with code so it is not compiled each run but only when code is updated another was to just compile it for each platform and have the wrapper script select the proper executable is there an accepted stable process for this are there any catches are there alternatives assuming the absolute need to use native code clarification multiple os are involved that do not share abi eg os various linuxes bsd etc need to be able to update the code in place in shared folders and have the new code working more or less instantaneously distributing binary or source packages is less than ideal
depending on your mix os oses you might be better off creating packages for each class of system alternatively if they all share the same abi and hardware architecture you could also compile static binaries
QA
using in shared multi platform posix environment write tools that are used in shared workspace since there are multiple os working in this space we generally use python and standardize the version that is installed across machines however if wanted to write some things in was wondering if maybe could have the application wrapped in python script that detected the operating system and fired off the correct version of the application each platform has gcc available and uses the same she will one idea was to have the compiled to the users local bin with timestamp comparison with code so it is not compiled each run but only when code is updated another was to just compile it for each platform and have the wrapper script select the proper executable is there an accepted stable process for this are there any catches are there alternatives assuming the absolute need to use native code clarification multiple os are involved that do not share abi eg os various linuxes bsd etc need to be able to update the code in place in shared folders and have the new code working more or less instantaneously distributing binary or source packages is less than ideal
also you could use autoconf and distribute your application in source form only
QA
javascript locals in python one can get dictionary of all local and global variables in the current scope with the built in functions locals and globals is there some equivalent way of doing this in javascript for instance would like to do something like the following var foo function alert foo var bar function alert bar var foo locals alerts foo is this at all possible or should just be using local object for the lookup
well do not think that there is something like that in js you can always use eval instead of locals like this eval you just have to know that actually function foo exists edit do not use eval use var functionname myfunctionname window functionname
QA
javascript locals in python one can get dictionary of all local and global variables in the current scope with the built in functions locals and globals is there some equivalent way of doing this in javascript for instance would like to do something like the following var foo function alert foo var bar function alert bar var foo locals alerts foo is this at all possible or should just be using local object for the lookup
afaik no if you just want to check the existence of given variable you can do it by testing for it something like this if foo foo
QA
javascript locals in python one can get dictionary of all local and global variables in the current scope with the built in functions locals and globals is there some equivalent way of doing this in javascript for instance would like to do something like the following var foo function alert foo var bar function alert bar var foo locals alerts foo is this at all possible or should just be using local object for the lookup
seem to remember brendan eich commented on this in recent podcast if recall correctly it is not being considered as it adds unreasonable restrictions to optimization he compared it to the arguments local in that while useful for varargs its very existence removes the ability to guess at what function will touch just by looking at its definition by the way believe js did have support for accessing locals through the arguments local at one time quick search shows this has been deprecated though
QA
javascript locals in python one can get dictionary of all local and global variables in the current scope with the built in functions locals and globals is there some equivalent way of doing this in javascript for instance would like to do something like the following var foo function alert foo var bar function alert bar var foo locals alerts foo is this at all possible or should just be using local object for the lookup
bartek think that window functionname will not work if you in some closure and the function name is local to that closure for example function foo var bar function alert hello world var bar window this will not work in this case is bar but the function bar only exists inside the scope of the function foo it is not defined in the window scope of course this does not really answer the original question just wanted to chime in on this response do not believe there is way to do what the original question asked
QA
javascript locals in python one can get dictionary of all local and global variables in the current scope with the built in functions locals and globals is there some equivalent way of doing this in javascript for instance would like to do something like the following var foo function alert foo var bar function alert bar var foo locals alerts foo is this at all possible or should just be using local object for the lookup
pkaeding yes you are right window functionname does not work in this case but eval does if needed something like this would create my own object to keep those functions together var func func bar var bar func
QA
pgp signatures from python what is the easiest way to create and verify pgp gpg signatures from within python application can call pgp or gpg using subprocess and parse the output but was looking for way that did not require an external program to be installed my application is cross platform mac windows unix
think gpgme and the pyme python wrapper should do what you need
QA
javascript locals in python one can get dictionary of all local and global variables in the current scope with the built in functions locals and globals is there some equivalent way of doing this in javascript for instance would like to do something like the following var foo function alert foo var bar function alert bar var foo locals alerts foo is this at all possible or should just be using local object for the lookup
locals no globals yes window is reference to the global scope like globals in python globals foo is the same as window foo
QA
using in shared multi platform posix environment write tools that are used in shared workspace since there are multiple os working in this space we generally use python and standardize the version that is installed across machines however if wanted to write some things in was wondering if maybe could have the application wrapped in python script that detected the operating system and fired off the correct version of the application each platform has gcc available and uses the same she will one idea was to have the compiled to the users local bin with timestamp comparison with code so it is not compiled each run but only when code is updated another was to just compile it for each platform and have the wrapper script select the proper executable is there an accepted stable process for this are there any catches are there alternatives assuming the absolute need to use native code clarification multiple os are involved that do not share abi eg os various linuxes bsd etc need to be able to update the code in place in shared folders and have the new code working more or less instantaneously distributing binary or source packages is less than ideal
launching python interpreter instance just to select the right binary to run would be much heavier than you need would distribute she will rc file which provides aliases in shared bin you put the various binaries shared bin toolname mac shared bin toolname debian shared bin toolname netbsd dreamcast etc then in the common shared she will rc file you put the logic to set the aliases according to platform so that on osx it gets alias toolname shared bin toolname mac and so forth this will not work as well if you are adding new tools all the time because the users will need to reload the aliases would not recommend distributing tools this way though testing and qualifying new builds of the tools should be taking up enough time and effort that the extra time required to distribute the tools to the users is trivial you seem to be optimizing to reduce the distribution time replacing tools that quickly in live environment is all too likely to result in lengthy and confusing downtime if anything goes wrong in writing and building the tools especially when subtle cross platform issues creep in
QA
cx oracle how do get the ora xxxxx error number in try except block how do extract the oracle error number
try cursor execute select from dual except cx oracle databaseerror exc error exc print code error code print message error message this results in the following output code message ora divisor is equal to zero
QA
python deployment and usr bin env portability at the beginning of all my executable python scripts put the shebang line usr bin env python am running these scripts on system where env python yields python environment my scripts quickly fail because have manual check for compatible python version if sys version info raise importerror cannot run with python version do not want to have to change the shebang line on every executable file if it is possible however do not have administrative access to the machine to change the result of env python and do not want to force particular version as in usr bin env python would like to avoid this because system may have newer version than python or may have python but no python what is the elegant solution edit was not specific enough in posing the question would like to let users execute the scripts without manual configuration path alteration or symlinking in bin and ensuring your path has bin before the python path maybe some distribution utility is required to prevent the manual tweaks
env simply executes the first thing it finds in the path env var to switch to different python prepend the directory for that python executable to the path before invoking your script
QA
python deployment and usr bin env portability at the beginning of all my executable python scripts put the shebang line usr bin env python am running these scripts on system where env python yields python environment my scripts quickly fail because have manual check for compatible python version if sys version info raise importerror cannot run with python version do not want to have to change the shebang line on every executable file if it is possible however do not have administrative access to the machine to change the result of env python and do not want to force particular version as in usr bin env python would like to avoid this because system may have newer version than python or may have python but no python what is the elegant solution edit was not specific enough in posing the question would like to let users execute the scripts without manual configuration path alteration or symlinking in bin and ensuring your path has bin before the python path maybe some distribution utility is required to prevent the manual tweaks
if you are running the scripts then you can set your path variable to point to private bin directory first mkdir bin ln which python bin python export path bin path then when you execute your python script it will use python you will have to change your login scripts to change your path alternatively run your python script with the explicit interpreter you want path to python your script
QA
always including the user in the django template context am working on small intranet site for small company where user should be able to post have imagined very simple authentication mechanism where people just enter their email address and gets sent unique login url that sets cookie that will always identify them for future requests in my template setup have base html and the other pages extend this want to show logged in or register button in the base html but how can ensure that the necessary variables are always part of the context it seems that each view just sets up the context as they like and there is no global context population is there way of doing this without including the user in each context creation or will have to make my own custom shortcuts to setup the context properly
if you can hook your authentication into the django authentication scheme you will be able to use request user think this should just be case of calling authenticate and login based on the contents of your cookie edit staale always use the locals trick for my context so all my templates can see request and so request user if you are not then guess it would not be so straightforward
QA
always including the user in the django template context am working on small intranet site for small company where user should be able to post have imagined very simple authentication mechanism where people just enter their email address and gets sent unique login url that sets cookie that will always identify them for future requests in my template setup have base html and the other pages extend this want to show logged in or register button in the base html but how can ensure that the necessary variables are always part of the context it seems that each view just sets up the context as they like and there is no global context population is there way of doing this without including the user in each context creation or will have to make my own custom shortcuts to setup the context properly
in more general sense of not having to explicitly set variables in each view it sounds like you want to look at writing your own context processor from the docs context processor has very simple interface it is just python function that takes one argument an httprequest object and returns dictionary that gets added to the template context each context processor must return dictionary
QA
always including the user in the django template context am working on small intranet site for small company where user should be able to post have imagined very simple authentication mechanism where people just enter their email address and gets sent unique login url that sets cookie that will always identify them for future requests in my template setup have base html and the other pages extend this want to show logged in or register button in the base html but how can ensure that the necessary variables are always part of the context it seems that each view just sets up the context as they like and there is no global context population is there way of doing this without including the user in each context creation or will have to make my own custom shortcuts to setup the context properly
dave to use user username in my templates will then have to use requestcontext rather than just normal map hash http www djangoproject com documentation templates python subclassing context requestcontext so guess there are no globals that the template engine checks but the requestcontext has some prepopulate classes that can look into to solve my problems thanks
QA
how do do monkeypatching in python have had to do some introspection in python and it was not pretty name sys getframe code name os path split name co filename name co firstlineno name co name to get something like foo py bar blah blah in our debugging output would ideally like to prepend anything to stderr with this sort of information is it possible to change the behaviour of print globally within python
print statement does its io through sys stdout write so you can override sys stdout if you want to manipulate the print stream
QA
splitting tuples in python best practice have method in my python code that returns tuple row from sql query let us say it has three fields jobid label username for ease of passing it around between functions have been passing the entire tuple as variable called job eventually however want to get at the bits so have been using code like this jobid label username job have realised however that this is maintenance nightmare because now can never add new fields to the result set without breaking all of my existing code how should have written this here are my two best guesses jobid label username job job job but that does not scale nicely when you have fields or to convert the results from the sql query to dictionary straight away and pass that around do not have control over the fact that it starts life as tuple that is fixed for me
would say that dictionary is definitely the best way to do it it is easily extensible allows you to give each value sensible name and python has lot of built in language features for using and manipulating dictionaries if you need to add more fields later all you need to change is the code that converts the tuple to dictionary and the code that actually makes use of the new values for example job job jobid job label job username querycode
QA
splitting tuples in python best practice have method in my python code that returns tuple row from sql query let us say it has three fields jobid label username for ease of passing it around between functions have been passing the entire tuple as variable called job eventually however want to get at the bits so have been using code like this jobid label username job have realised however that this is maintenance nightmare because now can never add new fields to the result set without breaking all of my existing code how should have written this here are my two best guesses jobid label username job job job but that does not scale nicely when you have fields or to convert the results from the sql query to dictionary straight away and pass that around do not have control over the fact that it starts life as tuple that is fixed for me
with tuple it will always be hassle to add or change fields you are right that dictionary will be much better if you want something with slightly friendlier syntax you might want to take look at the answers this question about simple struct like object that way you can pass around an object say job and access its fields even more easily than tuple or dict job jobid job username jobid username